Add MemoryDb Trie-wrapper (#159)

* Pass along hashing function (keccak or blake2)

* Allow syncify to handle Promises with no return values

* Add sync MemoryDb interface
This commit is contained in:
Jaco Greeff
2018-07-03 14:31:01 +02:00
committed by GitHub
parent 9dbc5589ee
commit 243df6d030
20 changed files with 245 additions and 56 deletions
+2 -2
View File
@@ -16,7 +16,7 @@
"test": "jest --coverage"
},
"devDependencies": {
"@polkadot/dev": "^0.20.8",
"@polkadot/ts": "^0.1.6"
"@polkadot/dev": "^0.20.9",
"@polkadot/ts": "^0.1.8"
}
}
+21 -13
View File
@@ -3,7 +3,7 @@
// 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 { HashFn, NodeFactory, SemaphorePromise } from './types';
import async from 'async';
// @ts-ignore FIXME, we need to properly check the full file
@@ -20,7 +20,7 @@ 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 nodeFactory from './nodeFactory';
import createFactory from './nodeFactory';
import isRawNode from './util/isRawNode';
import prioritizedTaskExecutor from './util/taskExecutor';
import semaphore from './util/semaphore';
@@ -36,11 +36,13 @@ export default class BaseTrie {
_putDBs: any[]; // FIXME
dbDown: any; // FIXME
db: any; // FIXME
hashing: HashFn;
nodeFactory: NodeFactory;
putRaw: RawPutFn;
semaphore: SemaphorePromise;
// @ts-ignore FIXME, we need to properly check the full file
constructor (db, root: Uint8Array) {
constructor (db, root: Uint8Array, hashing: HashFn) {
this.putRaw = this._putRaw;
this.semaphore = semaphore(1);
@@ -48,6 +50,8 @@ export default class BaseTrie {
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)]);
@@ -73,7 +77,7 @@ export default class BaseTrie {
* @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) {
async get (key: Uint8Array): Promise<Uint8Array | null> {
l.debug(() => ['get', 'key ->', u8aToHex(key)]);
const result = await this.findPath(key);
@@ -163,7 +167,7 @@ export default class BaseTrie {
// @ts-ignore FIXME, we need to properly check the full file
async _lookupNode (node) {
if (isRawNode(node)) {
return nodeFactory.fromRaw(node);
return this.nodeFactory.fromRaw(node);
}
let value = await this.getRaw(node);
@@ -171,7 +175,7 @@ export default class BaseTrie {
if (value) {
try {
// @ts-ignore FIXME, we need to properly check the full file
value = nodeFactory.fromRaw(decodeRlp(value));
value = this.nodeFactory.fromRaw(decodeRlp(value));
} catch (error) {
l.error('_lookupNode decoding', typeof value, value);
throw error;
@@ -390,7 +394,9 @@ export default class BaseTrie {
// add an extention to a branch node
keyRemainder.shift();
// create a new leaf
stack.push(nodeFactory.fromLeaf(keyRemainder, value));
stack.push(
this.nodeFactory.fromLeaf(keyRemainder, value)
);
} else {
lastNode.value = value;
}
@@ -399,12 +405,12 @@ export default class BaseTrie {
const lastKey = lastNode.key;
const matchingLength = nibblesMatchingLength(lastKey, keyRemainder);
// @ts-ignore FIXME, we need to properly check the full file
const newBranchNode = nodeFactory.fromBranch();
const newBranchNode = this.nodeFactory.fromBranch();
// create a new extention node
if (matchingLength !== 0) {
const newKey = lastNode.key.slice(0, matchingLength);
const newExtNode = nodeFactory.fromExtention(newKey, value);
const newExtNode = this.nodeFactory.fromExtention(newKey, value);
stack.push(newExtNode);
lastKey.splice(0, matchingLength);
@@ -441,7 +447,9 @@ export default class BaseTrie {
keyRemainder.shift();
// add a leaf node to the new branch node
stack.push(nodeFactory.fromLeaf(keyRemainder, value));
stack.push(
this.nodeFactory.fromLeaf(keyRemainder, value)
);
} else {
newBranchNode.value = value;
}
@@ -613,7 +621,7 @@ export default class BaseTrie {
// create an extention node
// branch->extention->branch
// @ts-ignore FIXME, we need to properly check the full file
stack.push(nodeFactory.fromExtention([branchKey], null));
stack.push(this.nodeFactory.fromExtention([branchKey], null));
key.push(branchKey);
} else {
// branch key is an extention or a leaf
@@ -727,7 +735,7 @@ export default class BaseTrie {
// Creates the initial node from an empty tree
_createInitialNode (key: Uint8Array, value: Uint8Array) {
const newNode = nodeFactory.fromLeaf(key, value);
const newNode = this.nodeFactory.fromLeaf(key, value);
this.root = newNode.hash();
@@ -783,7 +791,7 @@ export default class BaseTrie {
copy () {
l.debug(() => ['Copying BaseTrie', typeof this.dbDown, u8aToHex(this.root)]);
return new BaseTrie(this.dbDown, this.root);
return new BaseTrie(this.dbDown, this.root, this.hashing);
}
/**
+5 -3
View File
@@ -3,6 +3,8 @@
// 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
@@ -34,8 +36,8 @@ export default class CheckpointTrie extends BaseTrie {
__putDBs: any[]; // tslint:disable-line
// @ts-ignore FIXME, we need to properly check the full file
constructor (db, root: Uint8Array) {
super(db, root);
constructor (db, root: Uint8Array, hashing: HashFn) {
super(db, root, hashing);
this._scratch = null;
this._checkpoints = [];
@@ -50,7 +52,7 @@ export default class CheckpointTrie extends BaseTrie {
copy () {
l.debug(() => ['Copying CheckpointTrie', typeof this.dbDown, u8aToHex(this.root)]);
return new CheckpointTrie(this.dbDown, this.root);
return new CheckpointTrie(this.dbDown, this.root, this.hashing);
}
async checkpoint () {
+58
View File
@@ -0,0 +1,58 @@
// 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 { TrieDb } from './types';
import memdown from 'memdown';
import syncify from '@polkadot/util/syncify';
import Trie from './Trie';
export default class MemoryDb implements TrieDb {
trie: Trie;
constructor (root?: Uint8Array) {
this.trie = new Trie(memdown(), root);
}
checkpoint (): void {
return syncify(
this.trie.checkpoint()
);
}
commit (): void {
syncify(
this.trie.commit()
);
}
del (key: Uint8Array): void {
syncify(
this.trie.del(key)
);
}
get (key: Uint8Array): Uint8Array | null {
return syncify(
this.trie.get(key)
);
}
revert (): void {
return syncify(
this.trie.revert()
);
}
put (key: Uint8Array, value: Uint8Array): void {
return syncify(
this.trie.put(key, value)
);
}
trieRoot (): Uint8Array {
return this.trie.root;
}
}
+5 -4
View File
@@ -3,11 +3,10 @@
// 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 } from './types';
import { DecodedRlp, Trie$Node$Type, HashFn } from './types';
import isU8a from '@polkadot/util/is/u8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import keccakAsU8a from '@polkadot/util-crypto/keccak/asU8a';
import encodeRlp from '@polkadot/util-rlp/encode';
import nibblesFromU8a from './nibbles/fromU8a';
@@ -37,10 +36,12 @@ function removeHexPrefix (key: Uint8Array): Uint8Array {
}
export default class TrieNode {
hashing: HashFn;
raw: DecodedRlp;
type: Trie$Node$Type;
constructor (type: Trie$Node$Type, raw: DecodedRlp) {
constructor (hashing: HashFn, type: Trie$Node$Type, raw: DecodedRlp) {
this.hashing = hashing;
this.raw = raw;
this.type = type;
}
@@ -120,7 +121,7 @@ export default class TrieNode {
}
hash (): Uint8Array {
return keccakAsU8a(this.serialize());
return this.hashing(this.serialize());
}
toString (): string {
@@ -3,7 +3,10 @@
// 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 keccakAsU8a from '@polkadot/util-crypto/keccak/asU8a';
import CheckpointTrie from './CheckpointTrie';
import { prove, verifyProof } from './proof';
@@ -15,8 +18,8 @@ export default class Trie extends CheckpointTrie {
static verifyProof = verifyProof;
// @ts-ignore FIXME, we need to properly check the full file
constructor (db, root) {
super(db, root);
constructor (db, root, hashing: HashFn = keccakAsU8a) {
super(db, root, hashing);
l.debug('Created Trie');
}
+13 -13
View File
@@ -4,7 +4,7 @@
// of the MPL-2.0 license. See the LICENSE file for details.
import { Logger } from '@polkadot/util/types';
import { DecodedRlp, Trie$Node, Trie$Node$Type } from './types';
import { HashFn, DecodedRlp, NodeFactory, Trie$Node, Trie$Node$Type } from './types';
import logger from '@polkadot/util/logger';
import u8aToHex from '@polkadot/util/u8a/toHex';
@@ -41,11 +41,11 @@ function getNodeType (node: DecodedRlp): Trie$Node$Type {
throw new Error(`Unable to determine Node type`);
}
function fromBranch (l: Logger) {
function fromBranch (l: Logger, hashing: HashFn) {
return (rlp: DecodedRlp): Trie$Node => {
l.debug(() => ['fromBranch']);
const node = new TrieNode('branch', Array.apply(null, Array(17)));
const node = new TrieNode(hashing, 'branch', Array.apply(null, Array(17)));
// NOTE Removed since
// (1) 'branch' is never called with any keys,
@@ -60,21 +60,21 @@ function fromBranch (l: Logger) {
};
}
function fromRaw (l: Logger) {
function fromRaw (l: Logger, hashing: HashFn) {
return (rlp: DecodedRlp): Trie$Node => {
l.debug(() => ['fromRaw ->', rlpToString(rlp)]);
const node = new TrieNode(getNodeType(rlp), rlp);
const node = new TrieNode(hashing, getNodeType(rlp), rlp);
return node;
};
}
function fromType (l: Logger, type: Trie$Node$Type) {
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)]);
const node = new TrieNode(type, Array(2));
const node = new TrieNode(hashing, type, Array(2));
node.setValue(value);
node.setKey(key);
@@ -83,9 +83,9 @@ function fromType (l: Logger, type: Trie$Node$Type) {
};
}
export default {
fromBranch: fromBranch(l),
fromExtention: fromType(l, 'extention'),
fromLeaf: fromType(l, 'leaf'),
fromRaw: fromRaw(l)
};
export default (hashing: HashFn): NodeFactory => ({
fromBranch: fromBranch(l, hashing),
fromExtention: fromType(l, hashing, 'extention'),
fromLeaf: fromType(l, hashing, 'leaf'),
fromRaw: fromRaw(l, hashing)
});
+6 -3
View File
@@ -3,12 +3,14 @@
// 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 nodeFactory from '../nodeFactory';
import createNodeFactory from '../nodeFactory';
/**
* Verifies a merkle proof for a given key
@@ -19,14 +21,15 @@ import nodeFactory from '../nodeFactory';
* @returns Promise<{String}>
*/
// @ts-ignore FIXME, we need to properly check the full file
export default async function verifyProof (rootHash, _key, proofs) {
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 = keccakAsU8a(proof);
const hash = hashing(proof);
assert(hash.toString() === wantedHash.toString(), `Bad proof node ${i}: hash mismatch`);
+21
View File
@@ -2,11 +2,25 @@
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { Trie$Pairs } from '@polkadot/trie-hash/types';
export interface TrieDb {
checkpoint: () => void,
commit: () => void,
del: (key: Uint8Array) => void,
get: (key: Uint8Array) => Uint8Array | null,
put: (key: Uint8Array, value: Uint8Array) => void,
revert: () => void,
trieRoot: () => Uint8Array
}
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 {
@@ -26,3 +40,10 @@ export type Trie$Base = {
};
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 -1
View File
@@ -5,7 +5,7 @@
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
import Trie from '../src/Trie';
describe('testing checkpoints', () => {
let trie, preRoot, postRoot;
+1 -1
View File
@@ -8,7 +8,7 @@ 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';
import Trie from '../src/Trie';
describe('it should create the genesis state root from ethereum', () => {
const trie4 = new Trie();
+1 -1
View File
@@ -6,7 +6,7 @@
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
import Trie from '../src/Trie';
describe('simple save and retrive', () => {
it('should not crash if given a non-existant root', async () => {
+91
View File
@@ -0,0 +1,91 @@
// 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 MemoryDb from '../src/Memory';
const EMPTY_ROOT = toU8a('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421');
const HELLO_ROOT = toU8a('0x0a915659b88f80bfa200570bd2767a6ab8cb0a4e44fd240cc5ed7a27728c4531');
const FOO_ROOT = toU8a('0xed4e32371288ee83be74f78fb492f01261b7c3dc9c422581bb705c4376492dc6');
describe('MemoryDb', () => {
let memory = new MemoryDb();
it('starts with the default root', () => {
expect(
memory.trieRoot()
).toEqual(EMPTY_ROOT);
});
it('has the correct root after a single insertion', () => {
memory.put(toU8a('hello'), toU8a('world'));
expect(
memory.trieRoot()
).toEqual(
HELLO_ROOT
);
});
it('has the correct root after a deletion', () => {
memory.del(toU8a('hello'));
expect(
memory.trieRoot()
).toEqual(
EMPTY_ROOT
);
});
it('has the correct root after a re-insertion', () => {
memory.put(toU8a('hello'), toU8a('world'));
expect(
memory.trieRoot()
).toEqual(
HELLO_ROOT
);
});
it('has the correct root after a second insertion', () => {
memory.put(toU8a('foo'), toU8a('bar'));
expect(
memory.trieRoot()
).toEqual(
FOO_ROOT
);
});
it('has the correct root after a re-deletion', () => {
memory.del(toU8a('hello'));
expect(
memory.trieRoot()
).toEqual(
toU8a('0x99650c730bbb99f6f58ce8b09bca2a8d90b36ac662e71bf81ec401ed23d199fb')
);
});
it('has the correct root after a re-re-insertion', () => {
memory.put(toU8a('hello'), toU8a('world'));
expect(
memory.trieRoot()
).toEqual(
FOO_ROOT
);
});
it('has the correct root after an update', () => {
memory.put(toU8a('hello'), toU8a('mars'));
expect(
memory.trieRoot()
).toEqual(
toU8a('0x116267e482ab94eb8824af425ea7f20ee84d10a8fa735f26204d80000e2a907e')
);
});
});
+1 -1
View File
@@ -6,7 +6,7 @@
import toU8a from '@polkadot/util/u8a/toU8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import Trie from '../src/index';
import Trie from '../src/Trie';
import { tests } from 'ethereumjs-testing';
const jsonTests = tests.trieTests;
@@ -5,7 +5,7 @@
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
import Trie from '../src/Trie';
const EMPTY_ROOT = '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421';
const HELLO_ROOT = '0x0a915659b88f80bfa200570bd2767a6ab8cb0a4e44fd240cc5ed7a27728c4531';
+1 -1
View File
@@ -6,7 +6,7 @@
import toU8a from '@polkadot/util/u8a/toU8a';
import u8aToUtf8 from '@polkadot/util/u8a/toUtf8';
import Trie from '../src/index';
import Trie from '../src/Trie';
describe('simple merkle proofs generation and verification', () => {
it('create a merkle proof and verify it with a single short key', async () => {
+1 -1
View File
@@ -5,7 +5,7 @@
import randomAsU8a from '@polkadot/util-crypto/random/asU8a';
import Trie from '../src/index';
import Trie from '../src/Trie';
describe('put & get raw functions', () => {
var trie = new Trie();
+1 -1
View File
@@ -5,7 +5,7 @@
import toU8a from '@polkadot/util/u8a/toU8a';
import Trie from '../src/index';
import Trie from '../src/Trie';
describe('kv stream test', () => {
var trie = new Trie();
+4 -2
View File
@@ -5,12 +5,12 @@
import deasync from 'deasync';
import isError from './is/error';
import isUndefined from './is/undefined';
// FIXME: This is currently for Node environments only - for Browser environments deasync is not available, we need a different solution.
export default function syncify (promise: Promise<any>): any {
let result: any;
let hasResult = false;
// tslint:disable-next-line
(async () => {
@@ -19,10 +19,12 @@ export default function syncify (promise: Promise<any>): any {
} catch (error) {
result = error;
}
hasResult = true;
})();
deasync.loopWhile(
() => isUndefined(result)
() => hasResult === false
);
if (isError(result)) {
+6 -6
View File
@@ -691,9 +691,9 @@
lodash "^4.17.5"
to-fast-properties "^2.0.0"
"@polkadot/dev@^0.20.8":
version "0.20.8"
resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.20.8.tgz#48d96f5b8c9b16c3abb94fa0df25705b48055bba"
"@polkadot/dev@^0.20.9":
version "0.20.9"
resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.20.9.tgz#beab8dbf6f359240fa2dd426b8dfe54661d93ee1"
dependencies:
"@babel/cli" "^7.0.0-beta.51"
"@babel/core" "^7.0.0-beta.51"
@@ -736,9 +736,9 @@
tslint-config-semistandard "^7.0.0"
typescript "^2.9.2"
"@polkadot/ts@^0.1.6":
version "0.1.6"
resolved "https://registry.yarnpkg.com/@polkadot/ts/-/ts-0.1.6.tgz#0138490e0e625ea34a9931be94fd436dd6015c7d"
"@polkadot/ts@^0.1.8":
version "0.1.8"
resolved "https://registry.yarnpkg.com/@polkadot/ts/-/ts-0.1.8.tgz#04e936fca0b104b8e0c4902bbfcc75ff5d58b98c"
"@types/async@^2.0.49":
version "2.0.49"