Remove trie-db-old

This commit is contained in:
Jaco Greeff
2018-09-02 00:15:13 +02:00
parent fc054c42fc
commit c6f26eb12e
35 changed files with 0 additions and 3196 deletions
-373
View File
@@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
-30
View File
@@ -1,30 +0,0 @@
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org)
![mpl-2](https://img.shields.io/badge/license-MPL-lightgrey.svg?style=flat-square)
[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard)
[![npm](https://img.shields.io/npm/v/@polkadot/trie-db.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/trie-db)
[![travis](https://img.shields.io/travis/polkadot-js/trie.svg?style=flat-square)](https://travis-ci.org/polkadot-js/trie)
[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/trie.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/trie/maintainability)
[![coverage](https://img.shields.io/coveralls/polkadot-js/trie.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/trie?branch=master)
[![dependency](https://david-dm.org/polkadot-js/trie.svg?style=flat-square&path=packages/trie)](https://david-dm.org/polkadot-js/trie?path=packages/trie-db)
[![devDependency](https://david-dm.org/polkadot-js/trie/dev-status.svg?style=flat-square&path=packages/trie-db)](https://david-dm.org/polkadot-js/trie?path=packages/trie-db#info=devDependencies)
# @polkadot/trie-db
An Implementation of the [Ethereum Merkle Patricia Tree](https://github.com/ethereum/wiki/wiki/Patricia-Tree) that uses Blake2 for hashing.
# Adapted from Ethereum
The has been adapted from the [original EthereumJs implementation](https://github.com/ethereumjs/merkle-patricia-tree) with the following changes -
- Introduce [TypeScript](https://www.typescriptlang.org/) into the mix
- ES6-ify as applicable (Classes, `self` -> `this`, `function() {}` -> `() => {}`)
- Moves to a Promise-based interface (as applicable)
- Support only Uint8Array key/values (Buffer/String in the original)
- Use utilities from [@polkadot/util](https://github.com/polkadot-js/common)
- Supports blake2 hashing (sha3 in the original), aligning with the Polkadot tech stack)
- Updated the build steps with sources moved to [src/](src/)
- Tests updated to use [Jest](https://facebook.github.io/jest/)
- Upgrade interfaces to latest [levelup](https://github.com/Level/levelup)
- Removed the secure interface (not applicable for Substrate chains)
... well at least the above is the _idea_ behind the fork ...
-45
View File
@@ -1,45 +0,0 @@
{
"name": "@polkadot/trie-db-old",
"version": "0.29.4",
"description": "This is an implementation of the modified merkle patricia tree as speficed in Ethereum's yellow paper, adpated for Polkadot.",
"main": "index.js",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [
"mjbecze <mjbecze@gmail.com>",
"Aaron Kumavis <http://aaron.kumavis.me/> (https://github.com/kumavis)"
],
"repository": {
"type": "git",
"url": "https://github.com/polkadot-js/common.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"keywords": [
"merkle",
"radix",
"trie",
"ethereum"
],
"license": "MPL-2.0",
"dependencies": {
"@babel/runtime": "^7.0.0-rc.1",
"@polkadot/trie-hash": "^0.29.4",
"@polkadot/util": "^0.29.4",
"@polkadot/util-crypto": "^0.29.4",
"@polkadot/util-rlp": "^0.29.4",
"@types/async": "^2.0.49",
"@types/semaphore": "^1.1.0",
"async": "^2.6.1",
"encoding-down": "^5.0.3",
"level-ws": "0.1.0",
"levelup": "^3.1.1",
"memdown": "^3.0.0",
"semaphore": ">=1.0.1"
},
"devDependencies": {
"ethereumjs-testing": "1.0.4"
}
}
-847
View File
@@ -1,847 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { HashFn, NodeFactory, SemaphorePromise } from './types';
import async from 'async';
// @ts-ignore FIXME, we need to properly check the full file
import levelup from 'levelup';
import memdown from 'memdown';
import logger from '@polkadot/util/logger';
import assert from '@polkadot/util/assert';
import isU8a from '@polkadot/util/is/u8a';
import promisify from '@polkadot/util/promisify';
import u8aToHex from '@polkadot/util/u8a/toHex';
import keccakAsU8a from '@polkadot/util-crypto/keccak/asU8a';
import decodeRlp from '@polkadot/util-rlp/decode';
import { EMPTY_ROOT_U8A, EMPTY_ROOT_STR } from './constants';
import encoder from './encoder';
import { nibblesMatchingLength, nibblesIsEqual, nibblesFromU8a } from './nibbles';
import ReadStream from './streams/TrieRead';
import createFactory from './nodeFactory';
import isRawNode from './util/isRawNode';
import prioritizedTaskExecutor from './util/taskExecutor';
import semaphore from './util/semaphore';
type RawPutFn = (key: Uint8Array, value: Uint8Array) => Promise<any>;
const l = logger('trie/base');
export default class BaseTrie {
// @ts-ignore we are assigning via this.root in constructor
_root: Uint8Array;
_getDBs: any[]; // FIXME
_putDBs: any[]; // FIXME
dbDown: any; // FIXME
db: any; // FIXME
hashing: HashFn;
nodeFactory: NodeFactory;
putRaw: RawPutFn;
semaphore: SemaphorePromise;
constructor (db: any, root: Uint8Array = EMPTY_ROOT_U8A, hashing: HashFn = keccakAsU8a) {
this.putRaw = this._putRaw;
this.semaphore = semaphore(1);
this.dbDown = db || memdown();
this.db = levelup(encoder(this.dbDown));
this._getDBs = [this.db];
this._putDBs = [this.db];
this.hashing = hashing;
this.nodeFactory = createFactory(hashing);
this.root = root;
// l.debug(() => ['Created BaseTrie', typeof db, u8aToHex(root)]);
}
get root (): Uint8Array {
return this._root;
}
set root (value: Uint8Array) {
if (value) {
assert(isU8a(value) && value.length === 32, 'Invalid root length. Roots are Uint8Array 32 bytes');
} else {
value = EMPTY_ROOT_U8A;
}
this._root = value;
}
/**
* Gets a value given a `key`
* @method get
* @param {Buffer|String} key - the key to search for
* @param {Function} cb A callback `Function` which is given the arguments `err` - for errors that may have occured and `value` - the found value in a `Buffer` or if no value was found `null`
*/
async get (key: Uint8Array): Promise<Uint8Array | null> {
l.debug(() => ['get', 'key ->', u8aToHex(key)]);
const result = await this.findPath(key);
let value = null;
if (result && result.node && result.remainder.length === 0) {
value = result.node.value;
}
return value;
}
/**
* Stores a given `value` at the given `key`
* @method put
* @param {Buffer|String} key
* @param {Buffer|String} Value
* @returns {Function} Promise<void>
*/
async put (key: Uint8Array, value: Uint8Array) {
l.debug(() => ['put', 'key ->', u8aToHex(key), 'value ->', u8aToHex(value, 256)]);
if (!value || value.toString() === '') {
return this.del(key);
}
return this.semaphore(async () => {
if (this.root.toString() === EMPTY_ROOT_STR) {
return this._createInitialNode(key, value); // if no root initialize this trie
}
// first try to find the give key or its nearst node
const result = await this.findPath(key);
l.debug(() => ['put: path', result]);
return this._updateNode(key, value, result && result.remainder, result && result.stack);
});
}
/**
* deletes a value given a `key`
* @method del
* @param {Buffer|String} key
* @param {Function} callback the callback `Function`
*/
del (key: Uint8Array) {
l.debug(() => ['del', 'key ->', u8aToHex(key)]);
return this.semaphore(async () => {
const result = await this.findPath(key);
if (result && result.node) {
return this._deleteNode(key, result.stack);
}
});
}
/**
* Retrieves a raw value in the underlying db
* @method getRaw
* @param {Buffer} key
* @param {Function} callback A callback `Function`, which is given the arguments `err` - for errors that may have occured and `value` - the found value in a `Buffer` or if no value was found `null`.
*/
async getRaw (key: Uint8Array): Promise<Uint8Array> {
let found: Uint8Array;
await Promise.all(
this._getDBs.map(async (db) => {
if (!found) {
try {
found = await db.get(key);
} catch (error) {
// l.error('getRaw', 'key ->', u8aToHex(key), error);
// not doing anything
}
}
return found;
})
);
// @ts-ignore FIXME, we need to properly check the full file
return found;
}
// retrieves a node from dbs by hash
// @ts-ignore FIXME, we need to properly check the full file
async _lookupNode (node) {
if (isRawNode(node)) {
return this.nodeFactory.fromRaw(node);
}
let value = await this.getRaw(node);
if (value) {
try {
// @ts-ignore FIXME, we need to properly check the full file
value = this.nodeFactory.fromRaw(decodeRlp(value));
} catch (error) {
// l.error('_lookupNode decoding', typeof value, value);
throw error;
}
}
return value;
}
// TODO: remove the proxy method when changing the caching
async _putRaw (key: Uint8Array, value: Uint8Array) {
return Promise.all(
this._putDBs.map((db) => {
return db.put(key, value);
})
);
}
/**
* Removes a raw value in the underlying db
* @method delRaw
* @param {Buffer|String} key
* @param {Function} callback A callback `Function`, which is given the argument `err` - for errors that may have occured
*/
delRaw (key: Uint8Array) {
return Promise.all(
this._putDBs.map((db) => {
return db.del(key);
})
);
}
// writes a single node to dbs
// @ts-ignore FIXME, we need to properly check the full file
_putNode (node) {
const hash = node.hash();
const serialized = node.serialize();
return this._putRaw(hash, serialized);
}
// writes many nodes to db
// @ts-ignore FIXME, we need to properly check the full file
_batchNodes (opStack) {
return Promise.all(
this._putDBs.map((db) => {
return db.batch(opStack);
})
);
}
/**
* Trys to find a path to the node for the given key
* It returns a `stack` of nodes to the closet node
* @method findPath
* @param {String|Buffer} - key - the search key
* @param {Function} - cb - the callback function. Its is given the following
* arguments
* - err - any errors encontered
* - node - the last node found
* - remainder - the remaining key nibbles not accounted for
* - stack - an array of nodes that forms the path to node we are searching for
*/
// @ts-ignore FIXME, we need to properly check the full file
findPath (_targetKey) {
const stack: any[] = []; // FIXME
const targetKey = nibblesFromU8a(_targetKey);
// l.debug(() => ['findPath', targetKey.join(', ')]);
// @ts-ignore FIXME, we need to properly check the full file
const processNode = (nodeRef, node, keyProgress, walkController) => {
const nodeKey = node.key || [];
const remainder = targetKey.slice(nibblesMatchingLength(keyProgress, targetKey));
const matchingLen = nibblesMatchingLength(remainder, nodeKey);
stack.push(node);
if (node.type === 'branch') {
if (remainder.length === 0) {
walkController.return(null, { node, remainder: [], stack });
// we exhausted the key without finding a node
} else {
const branchIndex = remainder[0];
const branchNode = node.getValue(branchIndex);
if (!branchNode) {
// there are no more nodes to find and we didn't find the key
walkController.return(null, { node: null, remainder, stack });
} else {
// node found, continuing search
walkController.only(branchIndex);
}
}
} else if (node.type === 'leaf') {
if (nibblesIsEqual(remainder, nodeKey)) {
// keys match, return node with empty key
walkController.return(null, { node, remainder: [], stack });
} else {
// reached leaf but keys dont match
walkController.return(null, { node: null, remainder, stack });
}
} else if (node.type === 'extention') {
if (matchingLen !== nodeKey.length) {
// keys dont match, fail
walkController.return(null, { node: null, remainder, stack });
} else {
// keys match, continue search
walkController.next();
}
}
};
return promisify(this, this._walkTrie, this.root, processNode);
}
/*
* Finds all nodes that store k,v values
*/
// NOTE seems unused
// _findNode = function (key, root, stack, cb) {
// this.findPath(key, (...args) => {
// cb.apply(null, args);
// });
// };
/*
* Finds all nodes that store k,v values
*/
// @ts-ignore FIXME, we need to properly check the full file
_findValueNodes (onFound, cb) {
// @ts-ignore FIXME, we need to properly check the full file
this._walkTrie(this.root, (nodeRef, node, key, walkController) => { // tslint:disable-line
let fullKey = key;
if (node.key) {
fullKey = key.concat(node.key);
}
if (node.type === 'leaf') {
// found leaf node!
onFound(nodeRef, node, fullKey, walkController.next);
} else if (node.type === 'branch' && node.value) {
// found branch with value
onFound(nodeRef, node, fullKey, walkController.next);
} else {
// keep looking for value nodes
walkController.next();
}
}, cb);
}
/*
* Finds all nodes that are stored directly in the db
* (some nodes are stored raw inside other nodes)
*/
// @ts-ignore FIXME, we need to properly check the full file
_findDbNodes (onFound, cb) {
// @ts-ignore FIXME, we need to properly check the full file
this._walkTrie(this.root, (nodeRef, node, key, walkController) => { // tslint:disable-line
if (isRawNode(nodeRef)) {
walkController.next();
} else {
onFound(nodeRef, node, key, walkController.next);
}
}, cb);
}
/**
* Updates a node
* @method _updateNode
* @param {Buffer} key
* @param {Buffer| String} value
* @param {Array} keyRemainder
* @param {Array} stack -
* @param {Function} cb - the callback
*/
// @ts-ignore FIXME, we need to properly check the full file
async _updateNode (key, value, keyRemainder, stack) {
// @ts-ignore FIXME, we need to properly check the full file
const toSave = [];
const lastNode = stack.pop();
// add the new nodes
key = nibblesFromU8a(key);
// Check if the last node is a leaf and the key matches to this
let matchLeaf = false;
if (lastNode.type === 'leaf') {
let l = 0;
for (let i = 0; i < stack.length; i++) {
const n = stack[i];
if (n.type === 'branch') {
l++;
} else {
l += n.key.length;
}
}
if ((nibblesMatchingLength(lastNode.key, key.slice(l)) === lastNode.key.length) && (keyRemainder.length === 0)) {
matchLeaf = true;
}
}
if (matchLeaf) {
// just updating a found value
lastNode.value = value;
stack.push(lastNode);
} else if (lastNode.type === 'branch') {
stack.push(lastNode);
if (keyRemainder !== 0) {
// add an extention to a branch node
keyRemainder.shift();
// create a new leaf
stack.push(
this.nodeFactory.fromLeaf(keyRemainder, value)
);
} else {
lastNode.value = value;
}
} else {
// create a branch node
const lastKey = lastNode.key;
const matchingLength = nibblesMatchingLength(lastKey, keyRemainder);
// @ts-ignore FIXME, we need to properly check the full file
const newBranchNode = this.nodeFactory.fromBranch();
// create a new extention node
if (matchingLength !== 0) {
const newKey = lastNode.key.slice(0, matchingLength);
const newExtNode = this.nodeFactory.fromExtention(newKey, value);
stack.push(newExtNode);
lastKey.splice(0, matchingLength);
keyRemainder.splice(0, matchingLength);
}
stack.push(newBranchNode);
if (lastKey.length !== 0) {
const branchKey = lastKey.shift();
if (lastKey.length !== 0 || lastNode.type === 'leaf') {
// shriking extention or leaf
lastNode.key = lastKey;
// @ts-ignore FIXME, we need to properly check the full file
const formatedNode = this._formatNode(lastNode, false, toSave);
// @ts-ignore FIXME, we need to properly check the full file
newBranchNode.setValue(branchKey, formatedNode);
} else {
// remove extention or attaching
// @ts-ignore FIXME, we need to properly check the full file
this._formatNode(lastNode, false, true, toSave);
// @ts-ignore FIXME, we need to properly check the full file
newBranchNode.setValue(branchKey, lastNode.value);
}
} else {
newBranchNode.value = lastNode.value;
}
if (keyRemainder.length !== 0) {
keyRemainder.shift();
// add a leaf node to the new branch node
stack.push(
this.nodeFactory.fromLeaf(keyRemainder, value)
);
} else {
newBranchNode.value = value;
}
}
// @ts-ignore FIXME, we need to properly check the full file
return this._saveStack(key, stack, toSave);
}
// walk tree
// @ts-ignore FIXME, we need to properly check the full file
async _walkTrie (root, onNode, onDone) {
root = root || this.root;
let isAborted: boolean = false;
// @ts-ignore FIXME, we need to properly check the full file
let returnValues: any[] = [];
if (root.toString() === EMPTY_ROOT_STR) {
onDone();
return;
}
// the maximum pool size should be high enough to utilise the parallelizability of reading nodes from disk and
// low enough to utilize the prioritisation of node lookup.
const maxPoolSize = 500;
const taskExecutor = prioritizedTaskExecutor(maxPoolSize);
// @ts-ignore FIXME, we need to properly check the full file
const processNode = (nodeRef, node, key, cb) => {
if (!node || isAborted) {
return cb();
}
const self = this;
let isStopped = false;
key = key || [];
const walkController = {
stop: function () {
isStopped = true;
cb();
},
// end all traversal and return values to the onDone cb
return: function () {
isAborted = true;
// @ts-ignore FIXME, we need to properly check the full file
returnValues = arguments;
cb();
},
next: async function () {
if (isAborted || isStopped) {
return cb();
}
const children = node.getChildren();
// @ts-ignore FIXME callback
async.forEachOf(children, (childData: any[], index: number, cb) => {
// @ts-ignore FIXME, we need to properly check the full file
const keyExtension = childData[0];
// @ts-ignore FIXME, we need to properly check the full file
const childRef = childData[1];
const childKey = key.concat(keyExtension);
const priority = childKey.length;
// tslint:disable-next-line
taskExecutor(priority, async (taskCallback) => {
const childNode = await self._lookupNode(childRef);
// @ts-ignore FIXME, we need to properly check the full file
taskCallback();
processNode(childRef, childNode, childKey, cb);
});
}, cb);
},
// @ts-ignore FIXME, we need to properly check the full file
only: function (childIndex) {
const childRef = node.getValue(childIndex);
const childKey = key.slice();
childKey.push(childIndex);
const priority = childKey.length;
// tslint:disable-next-line
taskExecutor(priority, async (taskCallback) => {
const childNode = await self._lookupNode(childRef);
// @ts-ignore FIXME, we need to properly check the full file
taskCallback();
processNode(childRef, childNode, childKey, cb);
});
}
};
onNode(nodeRef, node, key, walkController);
};
const node = await this._lookupNode(root);
processNode(root, node, null, (error: Error | null) => {
if (error) {
onDone(error);
return;
}
// @ts-ignore FIXME, we need to properly check the full file
onDone.apply(null, returnValues);
});
}
/**
* saves a stack
* @method _saveStack
* @param {Array} key - the key. Should follow the stack
* @param {Array} stack - a stack of nodes to the value given by the key
* @param {Array} opStack - a stack of levelup operations to commit at the end of this funciton
* @param {Function} cb
*/
// @ts-ignore FIXME, we need to properly check the full file
_saveStack (key, stack, opStack: any[]) {
let lastRoot: any;
// update nodes
while (stack.length) {
const node = stack.pop();
if (node.type === 'leaf') {
key.splice(key.length - node.key.length);
} else if (node.type === 'extention') {
key.splice(key.length - node.key.length);
if (lastRoot) {
node.value = lastRoot;
}
} else if (node.type === 'branch') {
if (lastRoot) {
const branchKey = key.pop();
node.setValue(branchKey, lastRoot);
}
}
// @ts-ignore FIXME, we need to properly check the full file
lastRoot = this._formatNode(node, stack.length === 0, opStack);
l.debug(() => ['_saveStack', { lastRoot, node }]);
}
if (lastRoot) {
this.root = lastRoot;
}
l.debug(() => ['_saveStack', opStack]);
return this._batchNodes(opStack);
}
// @ts-ignore FIXME, we need to properly check the full file
async _deleteNode (key: Uint8Array, stack) {
// @ts-ignore FIXME, we need to properly check the full file
const processBranchNode = (key, branchKey, branchNode, parentNode, stack) => {
// branchNode is the node ON the branch node not THE branch node
const branchNodeKey = branchNode.key;
if (!parentNode || parentNode.type === 'branch') {
// branch->?
if (parentNode) {
stack.push(parentNode);
}
if (branchNode.type === 'branch') {
// create an extention node
// branch->extention->branch
// @ts-ignore FIXME, we need to properly check the full file
stack.push(this.nodeFactory.fromExtention([branchKey], null));
key.push(branchKey);
} else {
// branch key is an extention or a leaf
// branch->(leaf or extention)
branchNodeKey.unshift(branchKey);
branchNode.key = branchNodeKey;
// hackery. This is equvilant to array.concat except we need keep the
// rerfance to the `key` that was passed in.
branchNodeKey.unshift(0);
branchNodeKey.unshift(key.length);
key.splice.apply(key, branchNodeKey);
}
stack.push(branchNode);
} else {
// parent is a extention
let parentKey = parentNode.key;
if (branchNode.type === 'branch') {
// ext->branch
parentKey.push(branchKey);
key.push(branchKey);
parentNode.key = parentKey;
stack.push(parentNode);
} else {
// branch node is an leaf or extention and parent node is an exstention
// add two keys together
// dont push the parent node
branchNodeKey.unshift(branchKey);
key = key.concat(branchNodeKey);
parentKey = parentKey.concat(branchNodeKey);
branchNode.key = parentKey;
}
stack.push(branchNode);
}
return key;
};
// @ts-ignore FIXME, we need to properly check the full file
const opStack: any[] = [];
let lastNode = stack.pop();
let parentNode = stack.pop();
if (!Array.isArray(key)) {
// @ts-ignore FIXME, we need to properly check the full file
key = nibblesFromU8a(key);
}
if (!parentNode) {
// the root here has to be a leaf.
this.root = EMPTY_ROOT_U8A;
} else {
if (lastNode.type === 'branch') {
lastNode.value = null;
} else {
// the lastNode has to be a leaf if its not a branch. And a leaf's parent
// if it has one must be a branch.
const lastNodeKey = lastNode.key;
// @ts-ignore FIXME, we need to properly check the full file
key.splice(key.length - lastNodeKey.length);
// delete the value
this._formatNode(lastNode, false, true, opStack);
// @ts-ignore FIXME, we need to properly check the full file
parentNode.setValue(key.pop(), null);
lastNode = parentNode;
parentNode = stack.pop();
}
// nodes on the branch
// @ts-ignore FIXME, we need to properly check the full file
const branchNodes = [];
// count the number of nodes on the branch
// @ts-ignore FIXME, we need to properly check the full file
lastNode.raw.forEach(function (node, i) {
const val = lastNode.getValue(i);
// @ts-ignore FIXME, we need to properly check the full file
if (val) branchNodes.push([i, val]);
});
// if there is only one branch node left, collapse the branch node
if (branchNodes.length === 1) {
// add the one remaing branch node to node above it
// @ts-ignore FIXME, we need to properly check the full file
const branchNode = branchNodes[0][1];
// @ts-ignore FIXME, we need to properly check the full file
const branchNodeKey = branchNodes[0][0];
// look up node
const foundNode = await this._lookupNode(branchNode);
// @ts-ignore FIXME, we need to properly check the full file
key = processBranchNode(key, branchNodeKey, foundNode, parentNode, stack, opStack);
return this._saveStack(key, stack, opStack);
} else {
// simple removing a leaf and recaluclation the stack
if (parentNode) {
stack.push(parentNode);
}
stack.push(lastNode);
return this._saveStack(key, stack, opStack);
}
}
}
// Creates the initial node from an empty tree
_createInitialNode (key: Uint8Array, value: Uint8Array) {
const newNode = this.nodeFactory.fromLeaf(key, value);
this.root = newNode.hash();
return this._putNode(newNode);
}
// formats node to be saved by levelup.batch.
// returns either the hash that will be used key or the rawNode
// @ts-ignore FIXME, we need to properly check the full file
_formatNode (node: any, topLevel: any, remove: any, opStack: any) {
if (arguments.length === 3) {
opStack = remove;
remove = false;
}
const rlpNode = node.serialize();
if (rlpNode.length >= 32 || topLevel) {
const hashRoot = node.hash();
l.debug(() => ['_formatNode', { hashRoot }]);
// FIXME Actually 2 things wrong here - this is on checkpoint, so one higher-level class...
// @ts-ignore FIXME, we need to properly check the full file
if (remove && this.isCheckpoint) {
opStack.push({
type: 'del',
key: hashRoot
});
} else {
opStack.push({
type: 'put',
key: hashRoot,
value: rlpNode
});
}
return hashRoot;
}
l.debug(() => ['_formatNode', { raw: node.raw }]);
return node.raw;
}
/**
* The `data` event is given an `Object` hat has two properties; the `key` and the `value`. Both should be Buffers.
* @method createReadStream
* @return {stream.Readable} Returns a [stream](https://nodejs.org/dist/latest-v5.x/docs/api/stream.html#stream_class_stream_readable) of the contents of the `trie`
*/
createReadStream () {
return new ReadStream(this);
}
// creates a new trie backed by the same db
// and starting at the same root
copy () {
// l.debug(() => ['Copying BaseTrie', typeof this.dbDown, u8aToHex(this.root)]);
return new BaseTrie(this.dbDown, this.root, this.hashing);
}
/**
* The given hash of operations (key additions or deletions) are executed on the DB
* @method batch
* @example
* const ops = [
* { type: 'del', key: 'father' }
* , { type: 'put', key: 'name', value: 'Yuri Irsenovich Kim' }
* , { type: 'put', key: 'dob', value: '16 February 1941' }
* , { type: 'put', key: 'spouse', value: 'Kim Young-sook' }
* , { type: 'put', key: 'occupation', value: 'Clown' }
* ]
* trie.batch(ops)
* @param {Array} ops
* @param {Function} cb
*/
// @ts-ignore FIXME, we need to properly check the full file
batch (ops: any[]) {
return Promise.all(
// @ts-ignore FIXME, we need to properly check the full file
ops.map((op) => {
if (op.type === 'put') {
return this.put(op.key, op.value);
} else if (op.type === 'del') {
return this.del(op.key);
}
})
);
}
/**
* Checks if a given root exists
* @method checkRoot
* @param {Buffer} root
* @param {Function} cb
*/
async checkRoot (root: Uint8Array): Promise<boolean> {
const value = await this._lookupNode(root);
return !!value;
}
}
-163
View File
@@ -1,163 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { HashFn } from './types';
// @ts-ignore FIXME, we need to properly check the full file
import levelws from 'level-ws';
// @ts-ignore FIXME, we need to properly check the full file
import levelup from 'levelup';
import memdown from 'memdown';
import assert from '@polkadot/util/assert';
// import logger from '@polkadot/util/logger';
// import u8aToHex from '@polkadot/util/u8a/toHex';
import BaseTrie from './BaseTrie';
import encoder from './encoder';
import ScratchReadStream from './streams/ScratchRead';
// const l = logger('trie/checkpt');
function putRaw (key: Uint8Array, value: Uint8Array) {
return Promise.all(
// @ts-ignore FIXME, we need to properly check the full file
this.__putDBs.map((db) => {
return db.put(key, value);
})
);
}
export default class CheckpointTrie extends BaseTrie {
_checkpoints: Array<Uint8Array>;
_scratch: any; // FIXME
// @ts-ignore FIXME, we need to properly check the full file
__putDBs: any[]; // tslint:disable-line
// @ts-ignore FIXME, we need to properly check the full file
constructor (db: any, root?: Uint8Array, hashing?: HashFn) {
super(db, root, hashing);
this._scratch = null;
this._checkpoints = [];
// l.debug(() => 'Created CheckpointTrie');
}
get isCheckpoint () {
return !!this._checkpoints.length;
}
copy () {
// l.debug(() => ['Copying CheckpointTrie', typeof this.dbDown, u8aToHex(this.root)]);
return new CheckpointTrie(this.dbDown, this.root, this.hashing);
}
async checkpoint () {
// l.debug(() => 'Marking checkpoint');
const wasCheckpoint = this.isCheckpoint;
this._checkpoints.push(this.root);
if (!wasCheckpoint && this.isCheckpoint) {
this._enterCpMode();
}
}
commit () {
// l.debug(() => 'Committing checkpoint');
return this.semaphore(async () => {
assert(this.isCheckpoint, 'trying to commit when not checkpointed');
this._checkpoints.pop();
if (this.isCheckpoint) {
return;
}
return this._exitCpMode(true);
});
}
revert () {
// l.debug(() => 'Reverting checkpoint');
return this.semaphore(async () => {
if (!this.isCheckpoint) {
return;
}
this.root = this._checkpoints.pop() as Uint8Array;
if (this.isCheckpoint) {
return;
}
return this._exitCpMode(false);
});
}
// @ts-ignore FIXME, we need to properly check the full file
createScratchReadStream (scratch) {
const trie = this.copy();
scratch = scratch || this._scratch;
// only read from the scratch
trie._getDBs = [scratch];
trie._scratch = scratch;
return new ScratchReadStream(trie);
}
_enterCpMode () {
// l.debug(() => 'Entering checkpoint mode');
this._scratch = levelup(encoder(memdown()));
this._getDBs = [this._scratch].concat(this._getDBs);
this.__putDBs = this._putDBs;
this._putDBs = [this._scratch];
this._putRaw = this.putRaw;
this.putRaw = putRaw;
}
// @ts-ignore FIXME, we need to properly check the full file
_exitCpMode (commitState) {
// l.debug(() => 'Exiting checkpoint mode');
const scratch = this._scratch;
this._scratch = null;
this._getDBs = this._getDBs.slice(1);
this._putDBs = this.__putDBs;
this.putRaw = this._putRaw;
if (!commitState) {
return;
}
return Promise.all(
this._putDBs.map((db) => {
return new Promise((resolve) => {
if (!db.createWriteStream) {
db = levelws(db);
}
this
// @ts-ignore FIXME, we need to properly check the full file
.createScratchReadStream(scratch)
// @ts-ignore FIXME, we need to properly check the full file
.pipe(
// @ts-ignore FIXME, we need to properly check the full file
db.createWriteStream(encoder.options)
)
.on('close', resolve);
});
})
);
}
}
-173
View File
@@ -1,173 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodedRlp, Trie$Node$Type, HashFn } from './types';
import isU8a from '@polkadot/util/is/u8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import encodeRlp from '@polkadot/util-rlp/encode';
import nibblesToU8a from '@polkadot/trie-hash/util/fromNibbles';
import nibblesFromU8a from './nibbles/fromU8a';
function addHexPrefix (key: Array<number>, isTerminator: boolean): Array<number> {
// odd
if (key.length % 2) {
key.unshift(1);
} else {
// even
key.unshift(0);
key.unshift(0);
}
if (isTerminator) {
key[0] += 2;
}
return key;
}
function removeHexPrefix (key: Uint8Array): Uint8Array {
return key[0] % 2
? key.slice(1)
: key.slice(2);
}
export default class TrieNode {
hashing: HashFn;
raw: DecodedRlp;
type: Trie$Node$Type;
constructor (hashing: HashFn, type: Trie$Node$Type, raw: DecodedRlp) {
this.hashing = hashing;
this.raw = raw;
this.type = type;
}
get value () {
return this.getValue();
}
set value (v) {
this.setValue(v);
}
get key () {
return this.getKey();
}
set key (k) {
// @ts-ignore FIXME, we need to properly check the full file
this.setKey(k);
}
setValue (key: number | Uint8Array, value?: Uint8Array) {
if (this.type !== 'branch') {
this.raw[1] = key as Uint8Array;
return;
}
if (arguments.length === 1) {
value = key as Uint8Array;
key = 16;
}
this.raw[key as number] = value as Uint8Array;
}
getValue (key?: number) {
if (this.type !== 'branch') {
return this.raw[1];
}
if (arguments.length === 0) {
key = 16;
}
// @ts-ignore FIXME, we need to properly check the full file
const val = this.raw[key];
if (val !== null && val !== undefined && val.length !== 0) {
return val;
}
}
setKey (key: Array<number> | Uint8Array) {
if (this.type !== 'branch') {
if (Array.isArray(key)) {
key = key.slice(0); // copy the key
} else {
key = nibblesFromU8a(key);
}
key = addHexPrefix(key, this.type === 'leaf');
this.raw[0] = nibblesToU8a(key);
}
}
getKey () {
if (this.type !== 'branch') {
return removeHexPrefix(
// @ts-ignore FIXME, we need to properly check the full file
nibblesFromU8a(this.raw[0])
);
}
}
serialize (): Uint8Array {
return encodeRlp(this.raw);
}
hash (): Uint8Array {
return this.hashing(this.serialize());
}
toString (): string {
const format = (value: any): string => {
if (isU8a(value)) {
return u8aToHex(value);
} else if (Array.isArray(value)) {
return `[${value.map((v) => format(v))}]`;
} else if (value) {
return 'object';
}
return 'empty';
};
return this.raw.reduce((out, el, index) => {
return `${out}${index ? ', ' : ''}${format(el)}`;
}, `${this.type}: [`) + ']';
}
getChildren () {
const children = [];
switch (this.type) {
case 'leaf':
// no children
break;
case 'extention':
// one child
children.push([this.key, this.getValue()]);
break;
case 'branch':
let end = 16;
for (let index = 0; index < end; index++) {
const value = this.getValue(index);
if (value) {
children.push([
[index], value
]);
}
}
break;
}
return children;
}
}
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import trieRoot from '@polkadot/trie-hash/root';
const EMPTY_ROOT_U8A = trieRoot([]);
const EMPTY_ROOT_STR = EMPTY_ROOT_U8A.toString();
export {
EMPTY_ROOT_U8A,
EMPTY_ROOT_STR
};
@@ -1,29 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Logger } from '@polkadot/util/types';
import assert from '@polkadot/util/assert';
import isBuffer from '@polkadot/util/is/buffer';
import isU8a from '@polkadot/util/is/u8a';
import toU8a from '@polkadot/util/u8a/toU8a';
export default function decode (l: Logger) {
return (value: Buffer | Uint8Array | null): Uint8Array => {
// l.debug(() => ['decoding', value]);
if (!value || !value.length) {
return new Uint8Array(0);
}
const isBufferIn = isBuffer(value);
const isU8aIn = isU8a(value);
assert(isBufferIn || isU8aIn, `Expected a Buffer | Uint8Array | null input type, received '${typeof value}'`);
return isBufferIn
? toU8a(value)
: value;
};
}
@@ -1,29 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Logger } from '@polkadot/util/types';
import assert from '@polkadot/util/assert';
import isBuffer from '@polkadot/util/is/buffer';
import isU8a from '@polkadot/util/is/u8a';
import u8aToBuffer from '@polkadot/util/u8a/toBuffer';
export default function encode (l: Logger) {
return (value: Buffer | Uint8Array | null): Buffer => {
// l.debug(() => ['encoding', value ? value.toString() : value]);
if (!value || value.length === 0) {
return Buffer.alloc(0);
}
const isBufferIn = isBuffer(value);
const isU8aIn = isU8a(value);
assert(isBufferIn || isU8aIn, `Expected Buffer | Uint8Array | null input, received '${typeof value}'`);
return isBufferIn
? value as Buffer
: u8aToBuffer(value);
};
}
-36
View File
@@ -1,36 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
// @ts-ignore FIXME, we need to properly check the full file
import { LevelUp$AbstractStorage } from 'levelup';
// @ts-ignore FIXME, we need to properly check the full file
import encodingDown, { EncoderBufferOptions, EncodingBuffer } from 'encoding-down';
import logger from '@polkadot/util/logger';
import decode from './decode';
import encode from './encode';
const l = logger('trie/codec');
const encoding: EncodingBuffer<Uint8Array> = {
buffer: true,
decode: decode(l),
encode: encode(l),
type: 'Uint8Array'
};
const options: EncoderBufferOptions<Uint8Array> = {
keyEncoding: encoding,
valueEncoding: encoding
};
function encoder (db: LevelUp$AbstractStorage) {
return encodingDown(db, options);
}
// @ts-ignore FIXME, we need to properly check the full file
encoder.options = options;
export default encoder;
-23
View File
@@ -1,23 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { HashFn } from './types';
// import logger from '@polkadot/util/logger';
import CheckpointTrie from './CheckpointTrie';
import { prove, verifyProof } from './proof';
// const l = logger('trie');
export default class Trie extends CheckpointTrie {
static prove = prove;
static verifyProof = verifyProof;
constructor (db: any, root?: Uint8Array, hashing?: HashFn) {
super(db, root, hashing);
// l.debug('Created Trie');
}
}
@@ -1,17 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
export default function nibblesFromU8a (key: Uint8Array | Buffer): Array<number> {
const nibbles = [];
for (let i = 0; i < key.length; i++) {
const q = i * 2;
nibbles[q] = key[i] >> 4;
nibbles[q + 1] = key[i] % 16;
}
return nibbles;
}
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import nibblesFromU8a from './fromU8a';
import nibblesIsEqual from './isEqual';
import nibblesMatchingLength from './matchingLength';
export {
nibblesFromU8a,
nibblesIsEqual,
nibblesMatchingLength
};
@@ -1,12 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import matchingLength from './matchingLength';
export default function isEqual (keyA: Array<number>, keyB: Array<number>) {
const length = matchingLength(keyA, keyB);
return length === keyA.length && length === keyB.length;
}
@@ -1,14 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
export default function matchingLength (nib1: Array<number>, nib2: Array<number>): number {
let index = 0;
while (nib1[index] === nib2[index] && nib1.length > index) {
index++;
}
return index;
}
-90
View File
@@ -1,90 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Logger } from '@polkadot/util/types';
import { HashFn, DecodedRlp, NodeFactory, Trie$Node, Trie$Node$Type } from './types';
import logger from '@polkadot/util/logger';
import nibblesFromU8a from '@polkadot/trie-hash/util/asNibbles';
// import rlpToString from './util/rlpToString';
import TrieNode from './Node';
const l = logger('trie/node');
/**
* Determines the node type.
* @returns {String} - the node type
* - leaf - if the node is a leaf
* - branch - if the node is a branch
* - extention - if the node is an extention
*/
function getNodeType (node: DecodedRlp): Trie$Node$Type {
if (node.length === 17) {
return 'branch';
}
if (node.length === 2) {
const key = nibblesFromU8a(node[0] as Uint8Array);
if (key[0] > 1) {
return 'leaf';
}
return 'extention';
}
throw new Error(`Unable to determine Node type`);
}
function fromBranch (l: Logger, hashing: HashFn) {
return (rlp: DecodedRlp): Trie$Node => {
// l.debug(() => ['fromBranch']);
const node = new TrieNode(hashing, 'branch', Array.apply(null, Array(17)));
// NOTE Removed since
// (1) 'branch' is never called with any keys,
// (b) `this.set` points to what exactly?
// if (key) {
// key.forEach(function (keyVal) {
// this.set.apply(this, keyVal);
// });
// }
return node;
};
}
function fromRaw (l: Logger, hashing: HashFn) {
return (rlp: DecodedRlp): Trie$Node => {
// l.debug(() => ['fromRaw ->', rlpToString(rlp)]);
const node = new TrieNode(hashing, getNodeType(rlp), rlp);
return node;
};
}
function fromType (l: Logger, hashing: HashFn, type: Trie$Node$Type) {
return (key: Uint8Array, value: Uint8Array): Trie$Node => {
// l.debug(() => ['fromType', 'type ->', type, 'key ->', u8aToHex(key), 'value ->', u8aToHex(value, 256)]);
const node = new TrieNode(hashing, type, Array(2));
node.setValue(value);
node.setKey(key);
return node;
};
}
export default (hashing: HashFn): NodeFactory => ({
fromBranch: fromBranch(l, hashing),
fromExtention: fromType(l, hashing, 'extention'),
fromLeaf: fromType(l, hashing, 'leaf'),
fromRaw: fromRaw(l, hashing)
});
-11
View File
@@ -1,11 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import prove from './prove';
import verifyProof from './verifyProof';
export {
prove,
verifyProof
};
-35
View File
@@ -1,35 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import assert from '@polkadot/util/assert';
/**
* Returns a merkle proof for a given key
* @method Trie.prove
* @param {Trie} trie
* @param {String} key
* @return Promise<{Array.<TrieNode>}> `proof`
*/
// @ts-ignore FIXME, we need to properly check the full file
export default async function prove (trie, key) {
const result = await trie.findPath(key);
assert(result, 'findPath does not contain a valid path');
const { remainder, stack } = result;
assert(remainder.length === 0, 'Node does not contain the key');
// @ts-ignore FIXME, we need to properly check the full file
return stack.reduce((proofs, node, index) => {
const rlp = node.serialize();
if ((rlp.length >= 32) || (index === 0)) {
proofs.push(rlp);
}
return proofs;
}, []);
}
@@ -1,88 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { HashFn } from '../types';
import assert from '@polkadot/util/assert';
import decodeRlp from '@polkadot/util-rlp/decode';
import keccakAsU8a from '@polkadot/util-crypto/keccak/asU8a';
import { nibblesMatchingLength, nibblesFromU8a } from '../nibbles';
import createNodeFactory from '../nodeFactory';
/**
* Verifies a merkle proof for a given key
* @method Trie.verifyProof
* @param {Buffer | Uint8Array} rootHash
* @param {String} key
* @param {Array.<TrieNode>} proof
* @returns Promise<{String}>
*/
// @ts-ignore FIXME, we need to properly check the full file
export default async function verifyProof (rootHash, _key, proofs, hashing: HashFn = keccakAsU8a) {
const nodeFactory = createNodeFactory(hashing);
const lastIndex = proofs.length - 1;
let key = nibblesFromU8a(_key);
let wantedHash = rootHash;
for (let i = 0; i < proofs.length; i++) {
const proof = proofs[i];
const hash = hashing(proof);
assert(hash.toString() === wantedHash.toString(), `Bad proof node ${i}: hash mismatch`);
// @ts-ignore FIXME, we need to properly check the full file
const node = nodeFactory.fromRaw(decodeRlp(proof));
let cld;
if (node.type === 'branch') {
if (key.length === 0) {
assert(i === lastIndex, 'Additional nodes at end of proof (branch)');
return node.value;
}
cld = node.raw[key[0]];
key = key.slice(1);
if (cld.length === 2) {
// @ts-ignore FIXME, we need to properly check the full file
const embeddedNode = nodeFactory.fromRaw(cld);
assert(i === lastIndex, 'Additional nodes at end of proof (embeddedNode)');
// @ts-ignore FIXME, we need to properly check the full file
assert(nibblesMatchingLength(embeddedNode.key, key) === embeddedNode.key.length, 'Key length does not match with the proof one (embeddedNode)');
// @ts-ignore FIXME, we need to properly check the full file
key = key.slice(embeddedNode.key.length);
assert(key.length === 0, 'Key does not match with the proof one (embeddedNode)');
return embeddedNode.value;
} else {
wantedHash = cld;
}
} else if ((node.type === 'extention') || (node.type === 'leaf')) {
// @ts-ignore FIXME, we need to properly check the full file
assert(nibblesMatchingLength(node.key, key) === node.key.length, 'Key does not match with the proof one (extention|leaf)');
cld = node.value;
// @ts-ignore FIXME, we need to properly check the full file
key = key.slice(node.key.length);
if (key.length === 0) {
assert(i === lastIndex, 'Additional nodes at end of proof (extention|leaf)');
return cld;
} else {
wantedHash = cld;
}
} else {
throw new Error('Invalid node type');
}
}
throw new Error('Unexpected end of proof');
}
@@ -1,58 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Trie$Base } from '../types';
// @ts-ignore FIXME, we need to properly check the full file
import { Readable } from 'readable-stream';
// import logger from '@polkadot/util/logger';
// import u8aToHex from '@polkadot/util/u8a/toHex';
// import rlpToString from '../util/rlpToString';
// const l = logger('trie/scratch');
export default class ScratchReadStream extends Readable {
trie: Trie$Base;
next: null; // FIXME
// @ts-ignore FIXME, we need to properly check the full file
_started: boolean;
constructor (trie: Trie$Base) {
super({ objectMode: true });
this.trie = trie;
this.next = null;
}
_read () {
if (this._started) {
return;
}
const onDone = () => {
// l.debug(() => 'onDone');
// @ts-ignore FIXME, we need to properly check the full file
this.push(null);
};
// @ts-ignore FIXME, we need to properly check the full file
const onFound = (nodeRef, node, key, next) => {
// l.debug(() => ['onFound', u8aToHex(nodeRef), node.type, rlpToString(node.raw)]);
// @ts-ignore FIXME, we need to properly check the full file
this.push({
key: nodeRef,
value: node.serialize()
});
next();
};
// l.debug(() => 'Starting stream');
this._started = true;
this.trie._findDbNodes(onFound, onDone);
}
}
@@ -1,58 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Trie$Base } from '../types';
// @ts-ignore FIXME, we need to properly check the full file
import { Readable } from 'readable-stream';
import nibblesToU8a from '@polkadot/trie-hash/util/fromNibbles';
// import logger from '@polkadot/util/logger';
// import u8aToHex from '@polkadot/util/u8a/toHex';
// const l = logger('trie/read');
export default class TrieReadStream extends Readable {
trie: Trie$Base;
next: null; // FIXME
// @ts-ignore FIXME, we need to properly check the full file
_started: boolean;
constructor (trie: Trie$Base) {
super({ objectMode: true });
this.trie = trie;
this.next = null;
this._started = false;
}
_read () {
if (this._started) {
return;
}
const onDone = () => {
// l.debug(() => 'onDone');
// @ts-ignore FIXME, we need to properly check the full file
this.push(null);
};
// @ts-ignore FIXME, we need to properly check the full file
const onFound = (nodeRef, node, nibbles, next) => {
// l.debug(() => ['onFound', nibbles, u8aToHex(node.value)]);
// @ts-ignore FIXME, we need to properly check the full file
this.push({
key: nibblesToU8a(nibbles),
value: node.value
});
next();
};
// l.debug(() => 'Starting stream');
this._started = true;
this.trie._findValueNodes(onFound, onDone);
}
}
-37
View File
@@ -1,37 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
export type Callback = (error?: Error | null, result?: any) => void;
// NOTE This is actually DecodedRlp = Array<Uint8Array | DecodedRlp>, but since the decoder is relatively simple, we get away with the definition below
export type DecodedRlp = Array<Uint8Array | Array<Uint8Array>>;
export type HashFn = (data: Uint8Array) => Uint8Array;
export type Trie$Node$Type = 'branch' | 'extention' | 'leaf';
export interface Trie$Node {
hash: () => Uint8Array,
serialize: () => Uint8Array,
raw: DecodedRlp,
type: Trie$Node$Type,
value: Uint8Array
}
type Trie$Find$OnResult = (nodeRef: Uint8Array, node: Trie$Node, nibbles: Array<number>, next: () => void) => void;
export type Trie$Base = {
_findDbNodes (onResult: Trie$Find$OnResult, onDone: Callback): void,
_findValueNodes (onResult: Trie$Find$OnResult, onDone: Callback): void
};
export type SemaphorePromise = (fn: () => Promise<any>) => Promise<any>;
type NodeFactory = {
fromBranch (rlp: DecodedRlp): Trie$Node
fromRaw (rlp: DecodedRlp): Trie$Node,
fromExtention (key: Uint8Array, value: Uint8Array): Trie$Node,
fromLeaf (key: Uint8Array, value: Uint8Array): Trie$Node
}
@@ -1,10 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import isU8a from '@polkadot/util/is/u8a';
export default function isRawNode (node: Array<number> | Buffer | Uint8Array) {
return Array.isArray(node) && !isU8a(node);
}
@@ -1,19 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodedRlp } from '../types';
import assert from '@polkadot/util/assert';
import isU8a from '@polkadot/util/is/u8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
export default function rlpToString (rlp: Uint8Array | DecodedRlp): string {
if (Array.isArray(rlp)) {
return `[ ${rlp.map(rlpToString).join(', ')} ]`;
}
assert(isU8a(rlp), `Expected Array | Uint8Array inside rlp, found type '${typeof rlp}'`);
return u8aToHex(rlp);
}
@@ -1,27 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { SemaphorePromise } from '../types';
import semaphore from 'semaphore';
export default function semaphorePromise (max: number): SemaphorePromise {
const _semaphore = semaphore(max);
return (fn: () => Promise<any>): Promise<any> => {
return new Promise((resolve, reject) => {
_semaphore.take(async () => {
try {
const result = await fn();
_semaphore.leave();
resolve(result);
} catch (error) {
_semaphore.leave();
reject(error);
}
});
});
};
}
@@ -1,53 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
type Task$Fn = (taskCb: (value: any) => any) => any;
type Task = {
fn: Task$Fn,
priority: number,
reject: (error: Error) => void,
resolve: (value: any) => void
};
// https://github.com/ethereumjs/merkle-patricia-tree/pull/38
export default function taskExecutor (maxPoolSize: number) {
let currentPoolSize = 0;
const queue: Array<Task> = [];
const execute = (task: Task | undefined) => {
if (task === undefined) {
return;
}
if (currentPoolSize < maxPoolSize) {
currentPoolSize++;
task.fn((value: any): void => {
currentPoolSize--;
task.resolve(value);
if (queue.length > 0) {
queue.sort((a, b) =>
b.priority - a.priority
);
execute(queue.shift());
}
});
return;
}
queue.push(task);
};
return (priority: number, fn: Task$Fn): Promise<any> => {
return new Promise((resolve, reject) => {
execute({ fn, reject, resolve, priority });
});
};
}
@@ -1,73 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import mkdirp from 'mkdirp';
import toU8a from '@polkadot/util/u8a/toU8a';
// import diskdown from '@polkadot/db-diskdown/index';
import Trie from '../src/index';
// const DISKPATH = `${process.cwd()}/--test--db--`;
// mkdirp(DISKPATH);
describe.skip('testing checkpoints', () => {
let trie, preRoot, postRoot;
it('sets up the trie', async () => {
// trie = new Trie(diskdown(DISKPATH));
trie = new Trie();
await trie.put(toU8a('do'), toU8a('verb'));
await trie.put(toU8a('doge'), toU8a('coin'));
preRoot = trie.root;
});
it('should create a checkpoint', async () => {
await trie.checkpoint();
});
it('should save to the cache', async () => {
await trie.put(toU8a('test'), toU8a('something'));
await trie.put(toU8a('love'), toU8a('emotion'));
postRoot = trie.root;
});
it('should revert to the orginal root', async () => {
expect(trie.isCheckpoint).toEqual(true);
await trie.revert();
expect(trie.root).toEqual(preRoot);
expect(trie.isCheckpoint).toEqual(false);
});
it('should commit a checkpoint', async () => {
await trie.checkpoint();
await trie.put(toU8a('test'), toU8a('something'));
await trie.put(toU8a('love'), toU8a('emotion'));
await trie.commit();
expect(trie.isCheckpoint).toEqual(false);
expect(trie.root).toEqual(postRoot);
});
it('should commit a nested checkpoint', async () => {
await trie.checkpoint();
await trie.put(toU8a('test'), toU8a('something else'));
const root = trie.root;
await trie.checkpoint();
await trie.put(toU8a('the feels'), toU8a('emotion'));
await trie.revert();
await trie.commit();
expect(trie.isCheckpoint).toEqual(false);
expect(trie.root).toEqual(root);
});
});
@@ -1,41 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import keccakAsU8a from '@polkadot/util-crypto/keccak/asU8a';
import encodeRlp from '@polkadot/util-rlp/encode';
import Trie from '../src/index';
describe.skip('it should create the genesis state root from ethereum', () => {
const trie4 = new Trie();
const g = toU8a('0x8a40bfaa73256b60764c1bf40675a99083efb075');
const j = toU8a('0xe6716f9544a56c530d868e4bfbacb172315bdead');
const v = toU8a('0x1e12515ce3e0f817a4ddef9ca55788a1d66bd2df');
const a = toU8a('0x1a26338f0d905e295fccb71fa9ea849ffa12aaf4');
const stateRoot = new Uint8Array(32);
const startAmount = new Uint8Array(26);
startAmount[0] = 1;
const account = [startAmount, 0, stateRoot, keccakAsU8a(new Uint8Array())];
const genesisStateRoot = '0x2f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d';
const cppRlp = '0xf85e9a010000000000000000000000000000000000000000000000000080a00000000000000000000000000000000000000000000000000000000000000000a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
const rlpAccount = encodeRlp(account);
it('matches the initial rlp', () => {
expect(cppRlp).toEqual(u8aToHex(rlpAccount));
});
it('shall match the root', async () => {
await trie4.put(g, rlpAccount);
await trie4.put(j, rlpAccount);
await trie4.put(v, rlpAccount);
await trie4.put(a, rlpAccount);
expect(u8aToHex(trie4.root)).toEqual(genesisStateRoot);
});
});
-237
View File
@@ -1,237 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
describe.skip('simple save and retrive', () => {
it('should not crash if given a non-existant root', async () => {
const root = toU8a('0x3f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d');
const trie = new Trie(null, root);
const value = await trie.get(toU8a('test'));
expect(value).toEqual(null);
});
var trie = new Trie();
it('starts with a valid root', () => {
expect(
trie.root
).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', async () => {
await trie.put(toU8a('test'), toU8a('one'));
expect(
trie.root
).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', async () => {
const value = await trie.get(toU8a('test'));
expect(value).toEqual(toU8a('one'));
});
it('should update a value', async () => {
await trie.put(toU8a('test'), toU8a('two'));
const value = await trie.get(toU8a('test'));
expect(value).toEqual(toU8a('two'));
expect(trie.root).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', async () => {
await trie.del(toU8a('test'));
const value = await trie.get(toU8a('test'));
expect(value).toEqual(null);
expect(trie.root).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', async () => {
await trie.put(toU8a('test'), toU8a('one'));
expect(trie.root).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', async () => {
const value = await trie.get(toU8a('test'));
expect(value).toEqual(toU8a('one'));
});
it('should create a branch here', async () => {
await trie.put(toU8a('doge'), toU8a('coin'));
expect(
toU8a('0xde8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc')
).toEqual(trie.root);
});
it('should get a value that is in a branch', async () => {
const value = await trie.get(toU8a('doge'));
expect(value).toEqual(toU8a('coin'));
});
it('should delete from a branch', async () => {
await trie.del(toU8a('doge'));
const value = await trie.get(toU8a('doge'));
expect(value).toEqual(null);
expect(trie.root).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.skip('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', async () => {
await trie.put(toU8a('done'), toU8a(longString));
expect(trie.root).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('stores subsequent values', async () => {
await trie.put(toU8a('doge'), toU8a('coin'));
expect(longStringRoot).toEqual(u8aToHex(trie.root));
});
it('should retreive a longer value', async () => {
const value = await trie.get(toU8a('done'));
expect(value).toEqual(toU8a(longString));
});
it('should when being modiefied delete the old value', async () => {
await trie.put(toU8a('done'), toU8a('test'));
expect(trie.root).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.skip('testing Extentions and branches', () => {
const trie = new Trie();
it('should store a value', async () => {
await trie.put(toU8a('doge'), toU8a('coin'));
});
it('should create extention to store this value', async () => {
await trie.put(toU8a('do'), toU8a('verb'));
expect(
toU8a('0xf803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9')
).toEqual(trie.root);
});
it('should store this value under the extention ', async () => {
await trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.root));
});
});
describe.skip('testing Extentions and branches - reverse', () => {
const trie = new Trie();
it('should create extention to store this value', async () => {
await trie.put(toU8a('do'), toU8a('verb'));
const value = await trie.get(toU8a('do'));
expect(value).toEqual(toU8a('verb'));
});
it('should store a value', async () => {
await trie.put(toU8a('doge'), toU8a('coin'));
});
it('should store this value under the extention ', async () => {
await trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.root));
});
});
describe.skip('testing deletions cases', () => {
const trie = new Trie();
it('should delete from a branch->branch-branch', async () => {
await Promise.all([
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'))
]);
await trie.del(new Uint8Array([12, 22, 22]));
const value = await trie.get(new Uint8Array([12, 22, 22]));
expect(null).toEqual(value);
});
it('should delete from a branch->branch-extention', async () => {
await Promise.all([
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'))
]);
await trie.del(new Uint8Array([12, 22, 22]));
const value = await trie.get(new Uint8Array([12, 22, 22]));
expect(null).toEqual(value);
});
it('should delete from a extention->branch-extention', async () => {
await trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
await trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
await trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch'));
await trie.put(new Uint8Array([12, 33, 44]), toU8a('create the last branch'));
await trie.del(new Uint8Array([11, 11, 11]));
const value = await trie.get(new Uint8Array([11, 11, 11]));
expect(null).toEqual(value);
});
it('should delete from a extention->branch-branch', async () => {
await trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
await trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
await trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch'));
await trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch'));
await trie.del(new Uint8Array([11, 11, 11]));
const value = await trie.get(new Uint8Array([11, 11, 11]));
expect(null).toEqual(value);
});
});
-63
View File
@@ -1,63 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import Trie from '../src/index';
import getTests from '../../../test/getTests';
const trietest = getTests('TrieTests/trietest.json');
const trieanyorder = getTests('TrieTests/trieanyorder.json');
describe.skip('official tests', () => {
let trie;
beforeEach(() => {
trie = new Trie();
});
describe.skip('ordered tests', () => {
const testNames = Object.keys(trietest);
trietest.forEach(({ name, input, root }) => {
it(name, async () => {
await Promise.all(
input.map((input) =>
trie.put(toU8a(input[0]), toU8a(input[1]))
)
);
expect(
u8aToHex(trie.root)
).toEqual(
root
);
});
});
});
describe.skip('unordered tests', () => {
const testNames = Object.keys(trieanyorder);
trieanyorder.forEach(({ name, input, root }) => {
const keys = Object.keys(input);
it(name, async () => {
await Promise.all(
keys.map((key) =>
trie.put(toU8a(key), toU8a(input[key]))
)
);
expect(
u8aToHex(trie.root)
).toEqual(
root
);
});
});
});
});
@@ -1,94 +0,0 @@
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
const EMPTY_ROOT = '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421';
const HELLO_ROOT = '0x0a915659b88f80bfa200570bd2767a6ab8cb0a4e44fd240cc5ed7a27728c4531';
const FOO_ROOT = '0xed4e32371288ee83be74f78fb492f01261b7c3dc9c422581bb705c4376492dc6';
describe.skip('@polkadot refactoring', () => {
const trie = new Trie();
it('has the correct starting trieroot', () => {
expect(
u8aToHex(trie.root)
).toEqual(
EMPTY_ROOT
);
});
it('has the correct root after a single insertion', async () => {
await trie.put(toU8a('hello'), toU8a('world'));
expect(
u8aToHex(trie.root)
).toEqual(
HELLO_ROOT
);
});
it('has the correct root after a deletion', async () => {
await trie.del(toU8a('hello'));
expect(
u8aToHex(trie.root)
).toEqual(
EMPTY_ROOT
);
});
it('has the correct root after a re-insertion', async () => {
await trie.put(toU8a('hello'), toU8a('world'));
expect(
u8aToHex(trie.root)
).toEqual(
HELLO_ROOT
);
});
it('has the correct root after a second insertion', async () => {
await trie.put(toU8a('foo'), toU8a('bar'));
expect(
u8aToHex(trie.root)
).toEqual(
FOO_ROOT
);
});
it('has the correct root after a re-deletion', async () => {
await trie.del(toU8a('hello'));
expect(
u8aToHex(trie.root)
).toEqual(
'0x99650c730bbb99f6f58ce8b09bca2a8d90b36ac662e71bf81ec401ed23d199fb'
);
});
it('has the correct root after a re-re-insertion', async () => {
await trie.put(toU8a('hello'), toU8a('world'));
expect(
u8aToHex(trie.root)
).toEqual(
FOO_ROOT
);
});
it('has the correct root after an update', async () => {
await trie.put(toU8a('hello'), toU8a('mars'));
expect(
u8aToHex(trie.root)
).toEqual(
'0x116267e482ab94eb8824af425ea7f20ee84d10a8fa735f26204d80000e2a907e'
);
});
});
-106
View File
@@ -1,106 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import u8aToUtf8 from '@polkadot/util/u8a/toUtf8';
import Trie from '../src/index';
describe.skip('simple merkle proofs generation and verification', () => {
it('create a merkle proof and verify it with a single short key', async () => {
const trie = new Trie();
await trie.put(toU8a('key1aa'), toU8a('01234'));
const prove = await Trie.prove(trie, toU8a('key1aa'));
const value = await Trie.verifyProof(trie.root, toU8a('key1aa'), prove);
expect(u8aToUtf8(value)).toEqual('01234');
});
it('create a merkle proof and verify it with a single long key', async () => {
const trie = new Trie();
await trie.put(toU8a('key1aa'), toU8a('0123456789012345678901234567890123456789xx'));
const prove = await Trie.prove(trie, toU8a('key1aa'));
const value = await Trie.verifyProof(trie.root, toU8a('key1aa'), prove);
expect(u8aToUtf8(value)).toEqual('0123456789012345678901234567890123456789xx');
});
it('create a merkle proof and verify it', async () => {
const trie = new Trie();
await trie.put(toU8a('key1aa'), toU8a('0123456789012345678901234567890123456789xx'));
await trie.put(toU8a('key2bb'), toU8a('aval2'));
await trie.put(toU8a('key3cc'), toU8a('aval3'));
let prove = await Trie.prove(trie, toU8a('key2bb'));
let value = await Trie.verifyProof(trie.root, toU8a('key2bb'), prove);
expect(u8aToUtf8(value)).toEqual('aval2');
prove = await Trie.prove(trie, toU8a('key1aa'));
value = await Trie.verifyProof(trie.root, toU8a('key1aa'), prove);
expect(u8aToUtf8(value)).toEqual('0123456789012345678901234567890123456789xx');
prove = await Trie.prove(trie, toU8a('key2bb'));
try {
await Trie.verifyProof(trie.root, toU8a('randomkey'), prove);
expect('it should').toEqual('get here');
} catch (error) {
expect(error).not.toEqual(null);
}
prove = await Trie.prove(trie, toU8a('key2bb'));
try {
await Trie.verifyProof(trie.root, toU8a('key2b'), prove);
expect('it should').toEqual('get here');
} catch (error) {
expect(error).not.toEqual(null);
}
prove = await Trie.prove(trie, toU8a('key2bb'));
prove.push(toU8a('123456'));
try {
await Trie.verifyProof(trie.root, toU8a('key2b'), prove);
expect('it should').toEqual('get here');
} catch (error) {
expect(error).not.toEqual(null);
}
});
it('create a merkle proof and verify it with keys in the midle', async () => {
const trie = new Trie();
await trie.put(toU8a('key1aa'), toU8a('0123456789012345678901234567890123456789xxx'));
await trie.put(toU8a('key1'), toU8a('0123456789012345678901234567890123456789Very_Long'));
await trie.put(toU8a('key2bb'), toU8a('aval3'));
await trie.put(toU8a('key2'), toU8a('short'));
await trie.put(toU8a('key3cc'), toU8a('aval3'));
await trie.put(toU8a('key3'), toU8a('1234567890123456789012345678901'));
let prove = await Trie.prove(trie, toU8a('key1'));
let value = await Trie.verifyProof(trie.root, toU8a('key1'), prove);
expect(u8aToUtf8(value)).toEqual('0123456789012345678901234567890123456789Very_Long');
prove = await Trie.prove(trie, toU8a('key2'));
value = await Trie.verifyProof(trie.root, toU8a('key2'), prove);
expect(u8aToUtf8(value)).toEqual('short');
prove = await Trie.prove(trie, toU8a('key3'));
value = await Trie.verifyProof(trie.root, toU8a('key3'), prove);
expect(u8aToUtf8(value)).toEqual('1234567890123456789012345678901');
});
});
-72
View File
@@ -1,72 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import randomAsU8a from '@polkadot/util-crypto/random/asU8a';
import Trie from '../src/index';
describe.skip('put & get raw functions', () => {
var trie = new Trie();
var key = randomAsU8a(32);
var val = randomAsU8a(32);
it('putRaw', async () => {
await trie.putRaw(key, val);
});
it('getRaw', async () => {
const rVal = await trie.getRaw(key);
expect(rVal).toEqual(val);
});
it('should checkpoint and get the rawVal', async () => {
await trie.checkpoint();
const rVal = await trie.getRaw(key);
expect(rVal).toEqual(val);
});
var key2 = randomAsU8a(32);
var val2 = randomAsU8a(32);
it('should store while in a checkpoint', async () => {
await trie.putRaw(key2, val2);
});
it('should retrieve from a checkpoint', async () => {
const rVal = await trie.getRaw(key2);
expect(rVal).toEqual(val2);
});
it('should not retieve after revert', async () => {
await trie.revert();
});
it('should delete raw', async () => {
await trie.delRaw(val2);
});
it('should not get val after delete ', async () => {
const rVal = await trie.getRaw(val2);
expect(rVal).not.toBeDefined();
});
var key3 = randomAsU8a(32);
var val3 = randomAsU8a(32);
it('test commit behavoir', async () => {
await trie.checkpoint();
await trie.putRaw(key3, val3);
await trie.commit();
const rVal = await trie.getRaw(key3);
expect(rVal).toEqual(val3);
});
});
-177
View File
@@ -1,177 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
describe.skip('kv stream test', () => {
var trie = new Trie();
var init = [{
type: 'del',
key: 'father'
}, {
type: 'put',
key: 'name',
value: 'Yuri Irsenovich Kim'
}, {
type: 'put',
key: 'dob',
value: '16 February 1941'
}, {
type: 'put',
key: 'spouse',
value: 'Kim Young-sook'
}, {
type: 'put',
key: 'occupation',
value: 'Clown'
}, {
type: 'put',
key: 'nameads',
value: 'Yuri Irsenovich Kim'
}, {
type: 'put',
key: 'namfde',
value: 'Yuri Irsenovich Kim'
}, {
type: 'put',
key: 'namsse',
value: 'Yuri Irsenovich Kim'
}, {
type: 'put',
key: 'dofab',
value: '16 February 1941'
}, {
type: 'put',
key: 'spoudse',
value: 'Kim Young-sook'
}, {
type: 'put',
key: 'occupdsation',
value: 'Clown'
}, {
type: 'put',
key: 'dozzzb',
value: '16 February 1941'
}, {
type: 'put',
key: 'spouszze',
value: 'Kim Young-sook'
}, {
type: 'put',
key: 'occupatdfion',
value: 'Clown'
}, {
type: 'put',
key: 'dssob',
value: '16 February 1941'
}, {
type: 'put',
key: 'spossuse',
value: 'Kim Young-sook'
}, {
type: 'put',
key: 'occupssation',
value: 'Clown'
}].map(({ type, key, value }) => ({
type,
key: toU8a(key),
value: toU8a(value)
}));
const valObj = init.reduce((result, { key, type, value }) => {
if (type === 'put') {
result[toU8a(key)] = toU8a(value);
}
return result;
}, {});
it('should populate trie', async () => {
await trie.batch(init);
});
it('should fetch all of the nodes', (done) => {
const stream = trie.createReadStream();
stream.on('data', ({ key, value }) => {
expect(valObj[key]).toEqual(value);
delete valObj[key];
});
stream.on('end', () => {
const keys = Object.keys(valObj);
expect(keys).toHaveLength(0);
done();
});
});
});
describe.skip('db stream test', () => {
var trie = new Trie();
var init = [{
type: 'put',
key: 'color',
value: 'purple'
}, {
type: 'put',
key: 'food',
value: 'sushi'
}, {
type: 'put',
key: 'fight',
value: 'fire'
}, {
type: 'put',
key: 'colo',
value: 'trolo'
}, {
type: 'put',
key: 'color',
value: 'blue'
}, {
type: 'put',
key: 'color',
value: 'pink'
}].map(({ type, key, value }) => ({
type,
key: toU8a(key),
value: toU8a(value)
}));
var expectedNodes = [
'0x3c38d9aa6ad288c8e27da701e17fe99a5b67c8b12fd0469651c80494d36bc4c1',
'0xd5f61e1ff2b918d1c2a2c4b1732a3c68bd7e3fd64f35019f2f084896d4546298',
'0xe64329dadee2fb8a113b4c88cfe973aeaa9b523d4dc8510b84ca23f9d5bfbd90',
'0xc916d458bfb5f27603c5bd93b00f022266712514a59cde749f19220daffc743f',
'0x2386bfb0de9cf93902a110f5ab07b917ffc0b9ea599cb7f4f8bb6fd1123c866c'
].reduce((result, hex) => {
result[toU8a(hex)] = true;
return result;
}, {});
it('should populate trie', async () => {
await trie.checkpoint();
await trie.batch(init);
});
it('should only fetch nodes in the current trie', (done) => {
const stream = trie.createScratchReadStream();
stream.on('data', ({ key }) => {
expect(!!expectedNodes[key]).toEqual(true);
delete expectedNodes[key];
});
stream.on('end', () => {
expect(Object.keys(expectedNodes)).toHaveLength(0);
done();
});
});
});
@@ -1,30 +0,0 @@
// Copyright 2015-2018 authors & contributors of https://github.com/ethereumjs/merkle-patricia-tree
// Copyright 2017-2018 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import taskExecutor from '../src/util/taskExecutor';
const executor = taskExecutor(2);
describe.skip('taskExecutor', () => {
it('executes in order', async () => {
var tasks = [1, 2, 3, 4, 5, 6, 7];
var executionOrder = [];
await Promise.all(
tasks.map((priority) =>
executor(priority, (cb) => {
executionOrder.push(priority);
setTimeout(cb, 50);
})
)
);
expect(
executionOrder
).toEqual(
[1, 2, 7, 6, 5, 4, 3]
);
});
});