From 3061de7c41e87190f55bcb5babdd74d8c2c8b6c7 Mon Sep 17 00:00:00 2001 From: Sina Mahmoodi Date: Mon, 29 Jul 2019 12:46:42 +0200 Subject: [PATCH] Migrate files to TS, ignoring some errors --- package.json | 7 +- src/{baseTrie.js => baseTrie.ts} | 258 +++++++++--------- src/{checkpointTrie.js => checkpointTrie.ts} | 66 +++-- src/{db.js => db.ts} | 26 +- src/index.js | 1 - src/index.ts | 3 + ...Executor.js => prioritizedTaskExecutor.ts} | 21 +- src/readStream.js | 28 -- src/readStream.ts | 34 +++ src/{scratch.js => scratch.ts} | 20 +- src/scratchReadStream.js | 29 -- src/scratchReadStream.ts | 36 +++ src/{secure.js => secure.ts} | 30 +- src/{trieNode.js => trieNode.ts} | 90 +++--- src/util/{async.js => async.ts} | 24 +- src/util/{hex.js => hex.ts} | 12 +- src/util/{nibbles.js => nibbles.ts} | 15 +- test/checkpoint.js | 2 +- test/db.js | 2 +- test/encodeing.js | 2 +- test/failingRefactorTests.js | 2 +- test/index.js | 2 +- test/offical.js | 2 +- test/prioritizedTaskExecutor.js | 2 +- test/proof.js | 2 +- test/scratch.js | 4 +- test/secure.js | 2 +- test/streams.js | 2 +- 28 files changed, 393 insertions(+), 331 deletions(-) rename src/{baseTrie.js => baseTrie.ts} (75%) rename src/{checkpointTrie.js => checkpointTrie.ts} (71%) rename src/{db.js => db.ts} (82%) delete mode 100644 src/index.js create mode 100644 src/index.ts rename src/{prioritizedTaskExecutor.js => prioritizedTaskExecutor.ts} (75%) delete mode 100644 src/readStream.js create mode 100644 src/readStream.ts rename src/{scratch.js => scratch.ts} (68%) delete mode 100644 src/scratchReadStream.js create mode 100644 src/scratchReadStream.ts rename src/{secure.js => secure.ts} (54%) rename src/{trieNode.js => trieNode.ts} (58%) rename src/util/{async.js => async.ts} (61%) rename src/util/{hex.js => hex.ts} (79%) rename src/util/{nibbles.js => nibbles.ts} (80%) diff --git a/package.json b/package.json index 9f07085..2f67e08 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "tsc": "ethereumjs-config-tsc", "test": "npm run test:node && npm run test:browser", "test:browser": "karma start karma.conf.js", - "test:node": "babel-tape-runner ./test/*.js" + "test:node": "npm run build && tape ./test/*.js" }, "husky": { "hooks": { @@ -50,11 +50,11 @@ "license": "MPL-2.0", "dependencies": { "async": "^2.6.1", - "ethereumjs-util": "^5.2.0", + "ethereumjs-util": "^6.1.0", "level-mem": "^3.0.1", "level-ws": "^1.0.0", "readable-stream": "^3.0.6", - "rlp": "^2.0.0", + "rlp": "^2.2.3", "semaphore": ">=1.0.1" }, "devDependencies": { @@ -66,6 +66,7 @@ "@ethereumjs/config-prettier": "^1.1.1", "@ethereumjs/config-tsc": "^1.1.1", "@ethereumjs/config-tslint": "^1.1.1", + "@types/bn.js": "^4.11.5", "babel-tape-runner": "^3.0.0", "babelify": "^10.0.0", "browserify": "^13.0.0", diff --git a/src/baseTrie.js b/src/baseTrie.ts similarity index 75% rename from src/baseTrie.js rename to src/baseTrie.ts index e355a3d..c231a89 100644 --- a/src/baseTrie.js +++ b/src/baseTrie.ts @@ -1,14 +1,14 @@ +import * as rlp from 'rlp' +import * as ethUtil from 'ethereumjs-util' +import { DB, BatchDBOp } from './db' +import { TrieNode } from './trieNode' +import { TrieReadStream as ReadStream } from './readStream' +import { PrioritizedTaskExecutor } from './prioritizedTaskExecutor' +import { callTogether } from './util/async' +import { stringToNibbles, matchingNibbleLength, doKeysMatch } from './util/nibbles' const assert = require('assert') const async = require('async') -const rlp = require('rlp') -const ethUtil = require('ethereumjs-util') const semaphore = require('semaphore') -const DB = require('./db') -const TrieNode = require('./trieNode') -const ReadStream = require('./readStream') -const PrioritizedTaskExecutor = require('./prioritizedTaskExecutor') -const { callTogether } = require('./util/async') -const { stringToNibbles, matchingNibbleLength, doKeysMatch } = require('./util/nibbles') /** * Use `require('merkel-patricia-tree')` for the base interface. In Ethereum applications @@ -22,34 +22,23 @@ const { stringToNibbles, matchingNibbleLength, doKeysMatch } = require('./util/n * @prop {Buffer} root The current root of the `trie` * @prop {Buffer} EMPTY_TRIE_ROOT the Root for an empty trie */ -module.exports = class Trie { - constructor (db, root) { - const self = this +export class Trie { + EMPTY_TRIE_ROOT: Buffer + db: DB + protected sem: any + private _root: Buffer + + constructor (db?: any, root?: Buffer) { this.EMPTY_TRIE_ROOT = ethUtil.KECCAK256_RLP this.sem = semaphore(1) - this.db = db ? new DB(db) : new DB() - - Object.defineProperty(this, 'root', { - set (value) { - if (value) { - value = ethUtil.toBuffer(value) - assert(value.length === 32, 'Invalid root length. Roots are 32 bytes') - } else { - value = self.EMPTY_TRIE_ROOT - } - - this._root = value - }, - get () { - return this._root - } - }) - - this.root = root + this._root = this.EMPTY_TRIE_ROOT + if (root) { + this.setRoot(root) + } } - static fromProof (proofNodes, cb, proofTrie) { + static fromProof (proofNodes: Buffer[], cb: Function, proofTrie?: Trie) { let opStack = proofNodes.map((nodeValue) => { return {type: 'put', key: ethUtil.keccak(nodeValue), value: ethUtil.toBuffer(nodeValue)} }) @@ -59,29 +48,48 @@ module.exports = class Trie { if (opStack[0]) { proofTrie.root = opStack[0].key } } - proofTrie.db.batch(opStack, (e) => { + proofTrie.db.batch(opStack, (e: Error) => { cb(e, proofTrie) }) } - static prove (trie, key, cb) { - trie.findPath(key, function (err, node, remaining, stack) { + static prove (trie: Trie, key: Buffer, cb: Function) { + trie.findPath(key, function (err: Error, node: TrieNode, remaining: number[], stack: TrieNode[]) { if (err) return cb(err) let p = stack.map((stackElem) => { return stackElem.serialize() }) cb(null, p) }) } - static verifyProof (rootHash, key, proofNodes, cb) { + static verifyProof (rootHash: Buffer, key: Buffer, proofNodes: Buffer[], cb: Function) { let proofTrie = new Trie(null, rootHash) - Trie.fromProof(proofNodes, (error, proofTrie) => { + Trie.fromProof(proofNodes, (error: Error, proofTrie: Trie) => { if (error) cb(new Error('Invalid proof nodes given'), null) - proofTrie.get(key, (e, r) => { + proofTrie.get(key, (e: Error, r: Buffer | null) => { return cb(e, r) }) }, proofTrie) } + set root (value: Buffer) { + this.setRoot(value) + } + + get root (): Buffer { + return this._root + } + + setRoot (value?: Buffer) { + if (value) { + value = ethUtil.toBuffer(value) + assert(value.length === 32, 'Invalid root length. Roots are 32 bytes') + } else { + value = this.EMPTY_TRIE_ROOT + } + + this._root = value + } + /** * Gets a value given a `key` * @method get @@ -89,10 +97,10 @@ module.exports = class Trie { * @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` */ - get (key, cb) { + get (key: Buffer, cb: Function) { key = ethUtil.toBuffer(key) - this.findPath(key, (err, node, remainder, stack) => { + this.findPath(key, (err: Error, node: TrieNode, remainder: number[], stack: TrieNode[]) => { let value = null if (node && remainder.length === 0) { @@ -111,7 +119,7 @@ module.exports = class Trie { * @param {Buffer|String} Value * @param {Function} cb A callback `Function` which is given the argument `err` - for errors that may have occured */ - put (key, value, cb) { + put (key: Buffer, value: Buffer, cb: Function) { key = ethUtil.toBuffer(key) value = ethUtil.toBuffer(value) @@ -123,7 +131,7 @@ module.exports = class Trie { this.sem.take(() => { if (this.root.toString('hex') !== ethUtil.KECCAK256_RLP.toString('hex')) { // first try to find the give key or its nearst node - this.findPath(key, (err, foundValue, keyRemainder, stack) => { + this.findPath(key, (err: Error, foundValue: TrieNode, keyRemainder: number[], stack: TrieNode[]) => { if (err) { return cb(err) } @@ -144,12 +152,12 @@ module.exports = class Trie { * @param {Buffer|String} key * @param {Function} callback the callback `Function` */ - del (key, cb) { + del (key: Buffer, cb: Function) { key = ethUtil.toBuffer(key) cb = callTogether(cb, this.sem.leave) this.sem.take(() => { - this.findPath(key, (err, foundValue, keyRemainder, stack) => { + this.findPath(key, (err: Error, foundValue: TrieNode, keyRemainder: number[], stack: TrieNode[]) => { if (err) { return cb(err) } @@ -166,7 +174,7 @@ module.exports = class Trie { * Retrieves a value directly from key/value db. * @deprecated */ - getRaw (key, cb) { + getRaw (key: Buffer, cb: Function) { this.db.get(key, cb) } @@ -175,7 +183,7 @@ module.exports = class Trie { * key/value db. * @deprecated */ - putRaw (key, value, cb) { + putRaw (key: Buffer, value: Buffer, cb: Function) { this.db.put(key, value, cb) } @@ -183,28 +191,29 @@ module.exports = class Trie { * Deletes key directly from underlying key/value db. * @deprecated */ - delRaw (key, cb) { + delRaw (key: Buffer, cb: Function) { this.db.del(key, cb) } // retrieves a node from dbs by hash - _lookupNode (node, cb) { + _lookupNode (node: Buffer, cb: Function) { if (TrieNode.isRawNode(node)) { cb(null, new TrieNode(node)) } else { - this.db.get(node, (err, value) => { + this.db.get(node, (err: Error, value: Buffer | null) => { + let node = null if (value) { - value = new TrieNode(rlp.decode(value)) + node = new TrieNode(rlp.decode(value)) } else { err = new Error('Missing node in DB') } - cb(err, value) + cb(err, node) }) } } // writes a single node to dbs - _putNode (node, cb) { + _putNode (node: TrieNode, cb: Function) { const hash = node.hash() const serialized = node.serialize() this.db.put(hash, serialized, cb) @@ -223,13 +232,13 @@ module.exports = class Trie { * - keyRemainder - the remaining key nibbles not accounted for * - stack - an array of nodes that forms the path to node we are searching for */ - findPath (targetKey, cb) { - const stack = [] - targetKey = stringToNibbles(targetKey) + findPath (key: Buffer, cb: Function) { + const stack: TrieNode[] = [] + let targetKey = stringToNibbles(key) this._walkTrie(this.root, processNode, cb) - function processNode (nodeRef, node, keyProgress, walkController) { + function processNode (nodeRef: Buffer, node: TrieNode, keyProgress: number[], walkController: any) { const nodeKey = node.key || [] const keyRemainder = targetKey.slice(matchingNibbleLength(keyProgress, targetKey)) const matchingLen = matchingNibbleLength(keyRemainder, nodeKey) @@ -271,20 +280,21 @@ module.exports = class Trie { } } + // TODO: see if needs to be deprecated. can't find any usage /* * Finds all nodes that store k,v values */ - _findNode (key, root, stack, cb) { + /*_findNode (key: Buffer, root: Buffer, stack, cb) { this.findPath(key, () => { cb.apply(null, arguments) }) - } + }*/ /* * Finds all nodes that store k,v values */ - _findValueNodes (onFound, cb) { - this._walkTrie(this.root, (nodeRef, node, key, walkController) => { + _findValueNodes (onFound: Function, cb: Function) { + this._walkTrie(this.root, (nodeRef: Buffer, node: TrieNode, key: number[], walkController: any) => { let fullKey = key if (node.key) { @@ -308,8 +318,8 @@ module.exports = class Trie { * Finds all nodes that are stored directly in the db * (some nodes are stored raw inside other nodes) */ - _findDbNodes (onFound, cb) { - this._walkTrie(this.root, (nodeRef, node, key, walkController) => { + _findDbNodes (onFound: Function, cb: Function) { + this._walkTrie(this.root, (nodeRef: Buffer, node: TrieNode, key: number[], walkController: any) => { if (TrieNode.isRawNode(nodeRef)) { walkController.next() } else { @@ -328,12 +338,15 @@ module.exports = class Trie { * @param {Array} stack - * @param {Function} cb - the callback */ - _updateNode (key, value, keyRemainder, stack, cb) { - const toSave = [] + _updateNode (k: Buffer, value: Buffer, keyRemainder: number[], stack: TrieNode[], cb: Function) { + const toSave: BatchDBOp[] = [] const lastNode = stack.pop() + if (!lastNode) { + throw new Error('Stack underflow') + } // add the new nodes - key = stringToNibbles(key) + let key = stringToNibbles(k) // Check if the last node is a leaf and the key matches to this let matchLeaf = false @@ -389,16 +402,16 @@ module.exports = class Trie { stack.push(newBranchNode) if (lastKey.length !== 0) { - const branchKey = lastKey.shift() + const branchKey = lastKey.shift() as number if (lastKey.length !== 0 || lastNode.type === 'leaf') { // shriking extention or leaf lastNode.key = lastKey const formatedNode = this._formatNode(lastNode, false, toSave) - newBranchNode.setValue(branchKey, formatedNode) + newBranchNode.setValue(branchKey, formatedNode as Buffer) } else { // remove extention or attaching - this._formatNode(lastNode, false, true, toSave) + this._formatNode(lastNode, false, toSave, true) newBranchNode.setValue(branchKey, lastNode.value) } } else { @@ -419,22 +432,22 @@ module.exports = class Trie { } // walk tree - _walkTrie (root, onNode, onDone) { + _walkTrie (root: Buffer, onNode: Function, onDone: Function) { const self = this root = root || this.root onDone = onDone || function () {} let aborted = false - let returnValues = [] + let returnValues: any = [] if (root.toString('hex') === ethUtil.KECCAK256_RLP.toString('hex')) { return onDone() } - this._lookupNode(root, (e, node) => { + this._lookupNode(root, (e: Error, node: TrieNode) => { if (e) { return onDone(e, node) } - processNode(root, node, null, err => { + processNode(root, node, [], (err: Error) => { if (err) { return onDone(err) } @@ -448,13 +461,12 @@ module.exports = class Trie { const maxPoolSize = 500 const taskExecutor = new PrioritizedTaskExecutor(maxPoolSize) - function processNode (nodeRef, node, key, cb) { + function processNode (nodeRef: Buffer, node: TrieNode, key: number[] = [], cb: Function) { if (!node || aborted) { return cb() } let stopped = false - key = key || [] const walkController = { stop: function () { @@ -462,9 +474,9 @@ module.exports = class Trie { cb() }, // end all traversal and return values to the onDone cb - return: function () { + return: function (...args: any) { aborted = true - returnValues = arguments + returnValues = args cb() }, next: function () { @@ -473,13 +485,13 @@ module.exports = class Trie { } const children = node.getChildren() - async.forEachOf(children, (childData, index, cb) => { - const keyExtension = childData[0] - const childRef = childData[1] + async.forEachOf(children, (childData: (Buffer | number[])[], index: number, cb: Function) => { + const keyExtension = childData[0] as number[] + const childRef = childData[1] as Buffer const childKey = key.concat(keyExtension) const priority = childKey.length - taskExecutor.execute(priority, taskCallback => { - self._lookupNode(childRef, (e, childNode) => { + taskExecutor.execute(priority, (taskCallback: Function) => { + self._lookupNode(childRef, (e: Error, childNode: TrieNode) => { if (e) { return cb(e, node) } @@ -489,13 +501,13 @@ module.exports = class Trie { }) }, cb) }, - only: function (childIndex) { + only: function (childIndex: number) { const childRef = node.getValue(childIndex) const childKey = key.slice() childKey.push(childIndex) const priority = childKey.length - taskExecutor.execute(priority, taskCallback => { - self._lookupNode(childRef, (e, childNode) => { + taskExecutor.execute(priority, (taskCallback: Function) => { + self._lookupNode(childRef, (e: Error, childNode: TrieNode) => { if (e) { return cb(e, node) } @@ -519,12 +531,12 @@ module.exports = class Trie { * @param {Array} opStack - a stack of levelup operations to commit at the end of this funciton * @param {Function} cb */ - _saveStack (key, stack, opStack, cb) { + _saveStack (key: number[], stack: TrieNode[], opStack: BatchDBOp[], cb: Function) { let lastRoot // update nodes while (stack.length) { - const node = stack.pop() + const node = stack.pop() as TrieNode if (node.type === 'leaf') { key.splice(key.length - node.key.length) } else if (node.type === 'extention') { @@ -535,10 +547,10 @@ module.exports = class Trie { } else if (node.type === 'branch') { if (lastRoot) { const branchKey = key.pop() - node.setValue(branchKey, lastRoot) + node.setValue(branchKey!, lastRoot) } } - lastRoot = this._formatNode(node, stack.length === 0, opStack) + lastRoot = this._formatNode(node, stack.length === 0, opStack) as Buffer } if (lastRoot) { @@ -548,8 +560,8 @@ module.exports = class Trie { this.db.batch(opStack, cb) } - _deleteNode (key, stack, cb) { - function processBranchNode (key, branchKey, branchNode, parentNode, stack) { + _deleteNode (k: Buffer, stack: TrieNode[], cb: Function) { + function processBranchNode (key: number[], branchKey: number, branchNode: TrieNode, parentNode: TrieNode, stack: TrieNode[]) { // branchNode is the node ON the branch node not THE branch node const branchNodeKey = branchNode.key if (!parentNode || parentNode.type === 'branch') { @@ -574,6 +586,8 @@ module.exports = class Trie { // rerfance to the `key` that was passed in. branchNodeKey.unshift(0) branchNodeKey.unshift(key.length) + // TODO + // @ts-ignore key.splice.apply(key, branchNodeKey) } stack.push(branchNode) @@ -603,14 +617,12 @@ module.exports = class Trie { return key } - let lastNode = stack.pop() + let lastNode = stack.pop() as TrieNode + assert(lastNode) let parentNode = stack.pop() - const opStack = [] + const opStack: BatchDBOp[] = [] - if (!Array.isArray(key)) { - // convert key to nibbles - key = stringToNibbles(key) - } + let key = stringToNibbles(k) if (!parentNode) { // the root here has to be a leaf. @@ -618,6 +630,7 @@ module.exports = class Trie { cb() } else { if (lastNode.type === 'branch') { + // @ts-ignore lastNode.value = null } else { // the lastNode has to be a leaf if its not a branch. And a leaf's parent @@ -625,14 +638,16 @@ module.exports = class Trie { const lastNodeKey = lastNode.key key.splice(key.length - lastNodeKey.length) // delete the value - this._formatNode(lastNode, false, true, opStack) - parentNode.setValue(key.pop(), null) + this._formatNode(lastNode, false, opStack, true) + // @ts-ignore + parentNode.setValue(key.pop() as number, null) lastNode = parentNode + assert(lastNode) parentNode = stack.pop() } // nodes on the branch - const branchNodes = [] + const branchNodes: [number, Buffer][] = [] // count the number of nodes on the branch lastNode.raw.forEach((node, i) => { const val = lastNode.getValue(i) @@ -649,11 +664,11 @@ module.exports = class Trie { const branchNodeKey = branchNodes[0][0] // look up node - this._lookupNode(branchNode, (e, foundNode) => { + this._lookupNode(branchNode, (e: Error, foundNode: TrieNode) => { if (e) { return cb(e, foundNode) } - key = processBranchNode(key, branchNodeKey, foundNode, parentNode, stack, opStack) + key = processBranchNode(key, branchNodeKey, foundNode, parentNode as TrieNode, stack) this._saveStack(key, stack, opStack, cb) }) } else { @@ -669,7 +684,7 @@ module.exports = class Trie { } // Creates the initial node from an empty tree - _createInitialNode (key, value, cb) { + _createInitialNode (key: Buffer, value: Buffer, cb: Function) { const newNode = new TrieNode('leaf', key, value) this.root = newNode.hash() this._putNode(newNode, cb) @@ -677,29 +692,17 @@ module.exports = class Trie { // formats node to be saved by levelup.batch. // returns either the hash that will be used key or the rawNode - _formatNode (node, topLevel, remove, opStack) { - if (arguments.length === 3) { - opStack = remove - remove = false - } - + _formatNode (node: TrieNode, topLevel: boolean, opStack: BatchDBOp[], remove: boolean = false): Buffer | Buffer[] { const rlpNode = node.serialize() if (rlpNode.length >= 32 || topLevel) { const hashRoot = node.hash() - if (remove && this.isCheckpoint) { - opStack.push({ - type: 'del', - key: hashRoot - }) - } else { - opStack.push({ - type: 'put', - key: hashRoot, - value: rlpNode - }) - } + opStack.push({ + type: 'put', + key: hashRoot, + value: rlpNode + }) return hashRoot } @@ -713,13 +716,13 @@ module.exports = class Trie { * @memberof Trie * @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 () { + createReadStream (): ReadStream { return new ReadStream(this) } // creates a new trie backed by the same db // and starting at the same root - copy () { + copy (): Trie { const db = this.db.copy() return new Trie(db._leveldb, this.root) } @@ -740,9 +743,10 @@ module.exports = class Trie { * @param {Array} ops * @param {Function} cb */ - batch (ops, cb) { - async.eachSeries(ops, (op, cb2) => { + batch (ops: BatchDBOp[], cb: Function) { + async.eachSeries(ops, (op: BatchDBOp, cb2: Function) => { if (op.type === 'put') { + if (!op.value) throw new Error('Invalid batch db operation') this.put(op.key, op.value, cb2) } else if (op.type === 'del') { this.del(op.key, cb2) @@ -754,14 +758,10 @@ module.exports = class Trie { /** * Checks if a given root exists - * @method checkRoot - * @memberof Trie - * @param {Buffer} root - * @param {Function} cb */ - checkRoot (root, cb) { + checkRoot (root: Buffer, cb: Function) { root = ethUtil.toBuffer(root) - this._lookupNode(root, (e, value) => { + this._lookupNode(root, (e: Error, value: TrieNode) => { cb(null, !!value) }) } diff --git a/src/checkpointTrie.js b/src/checkpointTrie.ts similarity index 71% rename from src/checkpointTrie.js rename to src/checkpointTrie.ts index 9485dcf..21ccb50 100644 --- a/src/checkpointTrie.js +++ b/src/checkpointTrie.ts @@ -1,12 +1,18 @@ +import { Trie as BaseTrie } from './baseTrie' +import { ScratchReadStream } from './scratchReadStream' +import { ScratchDB } from './scratch' +import { callTogether } from './util/async' +import { DB, BatchDBOp } from './db' +import { TrieNode } from './trieNode' const async = require('async') const WriteStream = require('level-ws') -const BaseTrie = require('./baseTrie') -const ScratchReadStream = require('./scratchReadStream') -const ScratchDB = require('./scratch') -const { callTogether } = require('./util/async') -module.exports = class CheckpointTrie extends BaseTrie { - constructor (...args) { +export class CheckpointTrie extends BaseTrie { + _mainDB: DB + _scratch: ScratchDB | null + _checkpoints: Buffer[] + + constructor (...args: any) { super(...args) // Reference to main DB instance this._mainDB = this.db @@ -28,7 +34,6 @@ module.exports = class CheckpointTrie extends BaseTrie { * After this is called, no changes to the trie will be permanently saved * until `commit` is called. Calling `putRaw` overrides the checkpointing * mechanism and would directly write to db. - * @method checkpoint */ checkpoint () { const wasCheckpoint = this.isCheckpoint @@ -47,7 +52,7 @@ module.exports = class CheckpointTrie extends BaseTrie { * @param {Function} cb the callback * @throws If not during a checkpoint phase */ - commit (cb) { + commit (cb: Function) { cb = callTogether(cb, this.sem.leave) this.sem.take(() => { @@ -68,15 +73,13 @@ module.exports = class CheckpointTrie extends BaseTrie { * Reverts the trie to the state it was at when `checkpoint` was first called. * If during a nested checkpoint, sets root to most recent checkpoint, and sets * parent checkpoint as current. - * @method revert - * @param {Function} cb the callback */ - revert (cb) { + revert (cb: Function) { cb = callTogether(cb, this.sem.leave) this.sem.take(() => { if (this.isCheckpoint) { - this.root = this._checkpoints.pop() + this.root = this._checkpoints.pop()! if (!this.isCheckpoint) { this._exitCpMode(false, cb) return @@ -94,12 +97,12 @@ module.exports = class CheckpointTrie extends BaseTrie { * @param {boolean} includeCheckpoints - If true and during a checkpoint, the copy will * contain the checkpointing metadata and will use the same scratch as underlying db. */ - copy (includeCheckpoints = true) { + copy (includeCheckpoints: boolean = true): CheckpointTrie { const db = this._mainDB.copy() const trie = new CheckpointTrie(db._leveldb, this.root) if (includeCheckpoints && this.isCheckpoint) { trie._checkpoints = this._checkpoints.slice() - trie._scratch = this._scratch.copy() + trie._scratch = this._scratch!.copy() trie.db = trie._scratch } return trie @@ -110,7 +113,7 @@ module.exports = class CheckpointTrie extends BaseTrie { * key/value db, disregarding checkpoints. * @deprecated */ - putRaw (key, value, cb) { + putRaw (key: Buffer, value: Buffer, cb: Function) { this._mainDB.put(key, value, cb) } @@ -127,8 +130,8 @@ module.exports = class CheckpointTrie extends BaseTrie { * Exit from checkpoint mode. * @private */ - _exitCpMode (commitState, cb) { - const scratch = this._scratch + _exitCpMode (commitState: boolean, cb: Function) { + const scratch = this._scratch as ScratchDB this._scratch = null this.db = this._mainDB @@ -147,10 +150,37 @@ module.exports = class CheckpointTrie extends BaseTrie { * @method createScratchReadStream * @private */ - _createScratchReadStream (scratch) { + _createScratchReadStream (scratch: ScratchDB) { scratch = scratch || this._scratch const trie = new BaseTrie(scratch._leveldb, this.root) trie.db = scratch return new ScratchReadStream(trie) } + + // formats node to be saved by levelup.batch. + // returns either the hash that will be used key or the rawNode + _formatNode (node: TrieNode, topLevel: boolean, opStack: BatchDBOp[], remove: boolean = false) { + const rlpNode = node.serialize() + + if (rlpNode.length >= 32 || topLevel) { + const hashRoot = node.hash() + + if (remove && this.isCheckpoint) { + opStack.push({ + type: 'del', + key: hashRoot + }) + } else { + opStack.push({ + type: 'put', + key: hashRoot, + value: rlpNode + }) + } + + return hashRoot + } + + return node.raw + } } diff --git a/src/db.js b/src/db.ts similarity index 82% rename from src/db.js rename to src/db.ts index f51ab5d..aab259f 100644 --- a/src/db.js +++ b/src/db.ts @@ -1,18 +1,26 @@ const level = require('level-mem') -const ENCODING_OPTS = { keyEncoding: 'binary', valueEncoding: 'binary' } +export const ENCODING_OPTS = { keyEncoding: 'binary', valueEncoding: 'binary' } + +export interface BatchDBOp { + type: string + key: Buffer + value?: Buffer +} /** * DB is a thin wrapper around the underlying levelup db, * which validates inputs and sets encoding type. */ -module.exports = class DB { +export class DB { + _leveldb: any + /** * Initialize a DB instance. If `leveldb` is not provided, DB * defaults to an [in-memory store](https://github.com/Level/memdown). * @param {Object} [leveldb] - An abstract-leveldown compliant store */ - constructor (leveldb) { + constructor (leveldb?: any) { this._leveldb = leveldb || level() } @@ -23,10 +31,10 @@ module.exports = class DB { * `err` - for errors that may have occured * and `value` - the found value in a `Buffer` or if no value was found `null`. */ - get (key, cb) { + get (key: Buffer, cb: Function) { if (!Buffer.isBuffer(key)) throw new Error('Invalid input: expected buffer') - this._leveldb.get(key, ENCODING_OPTS, (err, v) => { + this._leveldb.get(key, ENCODING_OPTS, (err: Error, v?: Buffer) => { if (err || !v) { cb(null, null) } else { @@ -42,7 +50,7 @@ module.exports = class DB { * @param {Function} cb A callback `Function`, which is given the argument * `err` - for errors that may have occured */ - put (key, val, cb) { + put (key: Buffer, val: Buffer, cb: Function) { if (!Buffer.isBuffer(key)) throw new Error('Invalid input: expected buffer') if (!Buffer.isBuffer(val)) throw new Error('Invalid input: expected buffer') @@ -55,7 +63,7 @@ module.exports = class DB { * @param {Function} cb A callback `Function`, which is given the argument * `err` - for errors that may have occured */ - del (key, cb) { + del (key: Buffer, cb: Function) { if (!Buffer.isBuffer(key)) throw new Error('Invalid input: expected buffer') this._leveldb.del(key, ENCODING_OPTS, cb) @@ -67,7 +75,7 @@ module.exports = class DB { * @param {Function} cb A callback `Function`, which is given the argument * `err` - for errors that may have occured */ - batch (opStack, cb) { + batch (opStack: BatchDBOp[], cb: Function) { if (!Array.isArray(opStack)) throw new Error('Invalid input: expected buffer') this._leveldb.batch(opStack, ENCODING_OPTS, cb) @@ -77,7 +85,7 @@ module.exports = class DB { * Returns a copy of the DB instance, with a reference * to the **same** underlying leveldb instance. */ - copy () { + copy (): DB { return new DB(this._leveldb) } } diff --git a/src/index.js b/src/index.js deleted file mode 100644 index dd7bc96..0000000 --- a/src/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./checkpointTrie') diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..5f76722 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,3 @@ +export { CheckpointTrie } from './checkpointTrie' +export { SecureTrie } from './secure' +export { Trie as BaseTrie } from './baseTrie' diff --git a/src/prioritizedTaskExecutor.js b/src/prioritizedTaskExecutor.ts similarity index 75% rename from src/prioritizedTaskExecutor.js rename to src/prioritizedTaskExecutor.ts index f837f93..d77eb21 100644 --- a/src/prioritizedTaskExecutor.js +++ b/src/prioritizedTaskExecutor.ts @@ -1,4 +1,13 @@ -module.exports = class PrioritizedTaskExecutor { +interface Task { + priority: number + fn: Function +} + +export class PrioritizedTaskExecutor { + private maxPoolSize: number + private currentPoolSize: number + private queue: Task[] + /** * Executes tasks up to maxPoolSize at a time, other items are put in a priority queue. * @class PrioritizedTaskExecutor @@ -8,7 +17,7 @@ module.exports = class PrioritizedTaskExecutor { * @prop {Number} currentPoolSize The current size of the pool * @prop {Array} queue The task queue */ - constructor (maxPoolSize) { + constructor (maxPoolSize: number) { this.maxPoolSize = maxPoolSize this.currentPoolSize = 0 this.queue = [] @@ -20,21 +29,21 @@ module.exports = class PrioritizedTaskExecutor { * @param {Number} priority The priority of the task * @param {Function} task The function that accepts the callback, which must be called upon the task completion. */ - execute (priority, task) { + execute (priority: number, fn: Function) { if (this.currentPoolSize < this.maxPoolSize) { this.currentPoolSize++ - task(() => { + fn(() => { this.currentPoolSize-- if (this.queue.length > 0) { this.queue.sort((a, b) => b.priority - a.priority) const item = this.queue.shift() - this.execute(item.priority, item.task) + this.execute(item!.priority, item!.fn) } }) } else { this.queue.push({ priority: priority, - task: task + fn: fn }) } } diff --git a/src/readStream.js b/src/readStream.js deleted file mode 100644 index fe5d95e..0000000 --- a/src/readStream.js +++ /dev/null @@ -1,28 +0,0 @@ -const Readable = require('readable-stream').Readable -const { nibblesToBuffer } = require('./util/nibbles') - -module.exports = class TrieReadStream extends Readable { - constructor (trie) { - super({ objectMode: true }) - - this.trie = trie - this.next = null - } - - _read () { - if (!this._started) { - this._started = true - this.trie._findValueNodes((nodeRef, node, key, next) => { - this.push({ - key: nibblesToBuffer(key), - value: node.value - }) - - next() - }, () => { - // close stream - this.push(null) - }) - } - } -} diff --git a/src/readStream.ts b/src/readStream.ts new file mode 100644 index 0000000..50465a2 --- /dev/null +++ b/src/readStream.ts @@ -0,0 +1,34 @@ +//import { Readable } from 'readable-stream' +import { nibblesToBuffer } from './util/nibbles' +import { Trie as BaseTrie } from './baseTrie' +import { TrieNode } from './trieNode' +const Readable = require('readable-stream').Readable + +export class TrieReadStream extends Readable { + private trie: BaseTrie + private _started: boolean + + constructor (trie: BaseTrie) { + super({ objectMode: true }) + + this.trie = trie + this._started = false + } + + _read () { + if (!this._started) { + this._started = true + this.trie._findValueNodes((nodeRef: Buffer, node: TrieNode, key: number[], next: Function) => { + this.push({ + key: nibblesToBuffer(key), + value: node.value + }) + + next() + }, () => { + // close stream + this.push(null) + }) + } + } +} diff --git a/src/scratch.js b/src/scratch.ts similarity index 68% rename from src/scratch.js rename to src/scratch.ts index d6ec9b2..e740dd1 100644 --- a/src/scratch.js +++ b/src/scratch.ts @@ -1,7 +1,5 @@ -const DB = require('./db') -const { asyncFirstSeries } = require('./util/async') - -const ENCODING_OPTS = { keyEncoding: 'binary', valueEncoding: 'binary' } +import { DB, ENCODING_OPTS } from './db' +import { asyncFirstSeries } from './util/async' /** * An in-memory wrap over `DB` with an upstream DB @@ -9,8 +7,10 @@ const ENCODING_OPTS = { keyEncoding: 'binary', valueEncoding: 'binary' } * in the in-memory scratch. This class is used to implement * checkpointing functionality in CheckpointTrie. */ -module.exports = class ScratchDB extends DB { - constructor (upstreamDB) { +export class ScratchDB extends DB { + private _upstream: DB + + constructor (upstreamDB: DB) { super() this._upstream = upstreamDB } @@ -19,10 +19,10 @@ module.exports = class ScratchDB extends DB { * Similar to `DB.get`, but first searches in-memory * scratch DB, if key not found, searches upstream DB. */ - get (key, cb) { + get (key: Buffer, cb: Function) { const getDBs = this._upstream._leveldb ? [this._leveldb, this._upstream._leveldb] : [this._leveldb] - const dbGet = (db, cb2) => { - db.get(key, ENCODING_OPTS, (err, v) => { + const dbGet = (db: any, cb2: Function) => { + db.get(key, ENCODING_OPTS, (err: Error, v: Buffer | null) => { if (err || !v) { cb2(null, null) } else { @@ -34,7 +34,7 @@ module.exports = class ScratchDB extends DB { asyncFirstSeries(getDBs, dbGet, cb) } - copy () { + copy (): ScratchDB { const scratch = new ScratchDB(this._upstream) scratch._leveldb = this._leveldb return scratch diff --git a/src/scratchReadStream.js b/src/scratchReadStream.js deleted file mode 100644 index 05cc454..0000000 --- a/src/scratchReadStream.js +++ /dev/null @@ -1,29 +0,0 @@ -const { Readable } = require('readable-stream') - -// ScratchReadStream -// this is used to minimally dump the scratch into the db -module.exports = class ScratchReadStream extends Readable { - constructor (trie) { - super({ objectMode: true }) - - this.trie = trie - this.next = null - } - - _read () { - if (!this._started) { - this._started = true - this.trie._findDbNodes((nodeRef, node, key, next) => { - this.push({ - key: nodeRef, - value: node.serialize() - }) - - next() - }, () => { - // close stream - this.push(null) - }) - } - } -} diff --git a/src/scratchReadStream.ts b/src/scratchReadStream.ts new file mode 100644 index 0000000..84ef4b8 --- /dev/null +++ b/src/scratchReadStream.ts @@ -0,0 +1,36 @@ +//import { Readable } from 'readable-stream' +import { Trie as BaseTrie } from './baseTrie' +import { TrieNode } from './trieNode' +const Readable = require('readable-stream').Readable + +/* + * This is used to minimally dump the scratch into the db. + */ +export class ScratchReadStream extends Readable { + private trie: BaseTrie + private _started: boolean + + constructor (trie: BaseTrie) { + super({ objectMode: true }) + + this.trie = trie + this._started = false + } + + _read () { + if (!this._started) { + this._started = true + this.trie._findDbNodes((nodeRef: Buffer, node: TrieNode, key: number[], next: Function) => { + this.push({ + key: nodeRef, + value: node.serialize() + }) + + next() + }, () => { + // close stream + this.push(null) + }) + } + } +} diff --git a/src/secure.js b/src/secure.ts similarity index 54% rename from src/secure.js rename to src/secure.ts index bd64a5c..f69d6ab 100644 --- a/src/secure.js +++ b/src/secure.ts @@ -1,5 +1,5 @@ -const ethUtil = require('ethereumjs-util') -const CheckpointTrie = require('./checkpointTrie') +import { keccak256 } from 'ethereumjs-util' +import { CheckpointTrie } from './checkpointTrie' /** * You can create a secure Trie where the keys are automatically hashed @@ -9,29 +9,29 @@ const CheckpointTrie = require('./checkpointTrie') * @extends Trie * @public */ -module.exports = class SecureTrie extends CheckpointTrie { - constructor (...args) { +export class SecureTrie extends CheckpointTrie { + constructor (...args: any) { super(...args) } - static prove (trie, key, cb) { - const hash = ethUtil.keccak256(key) + static prove (trie: SecureTrie, key: Buffer, cb: Function) { + const hash = keccak256(key) super.prove(trie, hash, cb) } - static verifyProof (rootHash, key, proof, cb) { - const hash = ethUtil.keccak256(key) + static verifyProof (rootHash: Buffer, key: Buffer, proof: Buffer[], cb: Function) { + const hash = keccak256(key) super.verifyProof(rootHash, hash, proof, cb) } - copy () { + copy (): SecureTrie { const trie = super.copy(false) const db = trie.db.copy() return new SecureTrie(db._leveldb, this.root) } - get (key, cb) { - const hash = ethUtil.keccak256(key) + get (key: Buffer, cb: Function) { + const hash = keccak256(key) super.get(hash, cb) } @@ -39,17 +39,17 @@ module.exports = class SecureTrie extends CheckpointTrie { * For a falsey value, use the original key * to avoid double hashing the key. */ - put (key, val, cb) { + put (key: Buffer, val: Buffer, cb: Function) { if (!val) { this.del(key, cb) } else { - const hash = ethUtil.keccak256(key) + const hash = keccak256(key) super.put(hash, val, cb) } } - del (key, cb) { - const hash = ethUtil.keccak256(key) + del (key: Buffer, cb: Function) { + const hash = keccak256(key) super.del(hash, cb) } } diff --git a/src/trieNode.js b/src/trieNode.ts similarity index 58% rename from src/trieNode.js rename to src/trieNode.ts index 98b7248..35e190b 100644 --- a/src/trieNode.js +++ b/src/trieNode.ts @@ -1,20 +1,31 @@ -const rlp = require('rlp') -const ethUtil = require('ethereumjs-util') -const { stringToNibbles, nibblesToBuffer } = require('./util/nibbles') -const { isTerminator, addHexPrefix, removeHexPrefix } = require('./util/hex') +import * as rlp from 'rlp' +import { keccak256 } from 'ethereumjs-util' +import { stringToNibbles, nibblesToBuffer } from './util/nibbles' +import { isTerminator, addHexPrefix, removeHexPrefix } from './util/hex' + +enum NodeType { + Leaf = 'leaf', + Branch = 'branch', + Extension = 'extention', // FIXME + Unknown = 'unknown' // TODO +} + +export class TrieNode { + raw: Buffer[] + type: NodeType -module.exports = class TrieNode { - constructor (type, key, value) { + constructor (type: any, key?: any, value?: any) { if (Array.isArray(type)) { - // parse raw node - this.parseNode(type) + this.raw = type + this.type = TrieNode.getNodeType(type) } else { this.type = type if (type === 'branch') { var values = key + // @ts-ignore this.raw = Array.apply(null, Array(17)) if (values) { - values.forEach(function (keyVal) { + values.forEach(function (this: any, keyVal: any) { this.set.apply(this, keyVal) }) } @@ -35,24 +46,25 @@ module.exports = class TrieNode { * - extention - if the node is an extention * - unknown - if something else got borked */ - static getNodeType (node) { + static getNodeType (node: Buffer[]): NodeType { if (node.length === 17) { - return 'branch' + return NodeType.Branch } else if (node.length === 2) { var key = stringToNibbles(node[0]) if (isTerminator(key)) { - return 'leaf' + return NodeType.Leaf } - return 'extention' + return NodeType.Extension } + throw new Error('invalid node type') } - static isRawNode (node) { + static isRawNode (node: any): boolean { return Array.isArray(node) && !Buffer.isBuffer(node) } - get value () { + get value (): Buffer { return this.getValue() } @@ -60,7 +72,7 @@ module.exports = class TrieNode { this.setValue(v) } - get key () { + get key (): number[] { return this.getKey() } @@ -68,39 +80,42 @@ module.exports = class TrieNode { this.setKey(k) } - parseNode (rawNode) { + parseNode (rawNode: Buffer[]) { this.raw = rawNode this.type = TrieNode.getNodeType(rawNode) } - setValue (key, value) { + // TODO: refactor + setValue (key: Buffer | number, value?: Buffer) { if (this.type !== 'branch') { - this.raw[1] = key + this.raw[1] = key as Buffer } else { if (arguments.length === 1) { - value = key + value = key as Buffer key = 16 } - this.raw[key] = value + this.raw[key as number] = value as Buffer } } - getValue (key) { + // @ts-ignore + getValue (key?: number): Buffer { if (this.type === 'branch') { if (arguments.length === 0) { key = 16 } - var val = this.raw[key] + var val = this.raw[key as number] if (val !== null && val !== undefined && val.length !== 0) { return val } } else { return this.raw[1] } + //throw new Error('invalid node') } - setKey (key) { + setKey (key: Buffer | number[]) { if (this.type !== 'branch') { if (Buffer.isBuffer(key)) { key = stringToNibbles(key) @@ -113,24 +128,27 @@ module.exports = class TrieNode { } } - getKey () { + // @ts-ignore + getKey (): number[] { if (this.type !== 'branch') { - var key = this.raw[0] - key = removeHexPrefix(stringToNibbles(key)) - return (key) + let key = this.raw[0] + let nibbles = removeHexPrefix(stringToNibbles(key)) + return nibbles } + //throw new Error('invalid node') } - serialize () { + serialize (): Buffer { return rlp.encode(this.raw) } - hash () { - return ethUtil.keccak256(this.serialize()) + hash (): Buffer { + return keccak256(this.serialize()) } - toString () { - var out = this.type + toString (): string { + // @ts-ignore + let out = NodeType[this.type] out += ': [' this.raw.forEach(function (el) { if (Buffer.isBuffer(el)) { @@ -146,7 +164,7 @@ module.exports = class TrieNode { return out } - getChildren () { + getChildren (): (Buffer | number[])[][] { var children = [] switch (this.type) { case 'leaf': @@ -157,8 +175,8 @@ module.exports = class TrieNode { children.push([this.key, this.getValue()]) break case 'branch': - for (var index = 0, end = 16; index < end; index++) { - var value = this.getValue(index) + for (let index = 0, end = 16; index < end; index++) { + const value = this.getValue(index) if (value) { children.push([ [index], value diff --git a/src/util/async.js b/src/util/async.ts similarity index 61% rename from src/util/async.js rename to src/util/async.ts index 92447c9..d24eac2 100644 --- a/src/util/async.js +++ b/src/util/async.ts @@ -1,30 +1,24 @@ const async = require('async') -module.exports = { - callTogether: callTogether, - asyncFirstSeries: asyncFirstSeries -} - /** * Take two or more functions and returns a function that will execute all of * the given functions */ -function callTogether () { - var funcs = arguments - var length = funcs.length - var index = length +export function callTogether (...funcs: Function[]) { + let length = funcs.length + const index = length if (!length) { return function () {} } - return function () { + return function (this: any, ...args: any) { length = index while (length--) { - var fn = funcs[length] + const fn = funcs[length] if (typeof fn === 'function') { - var result = funcs[length].apply(this, arguments) + var result = funcs[length].apply(this, args) } } return result @@ -35,11 +29,11 @@ function callTogether () { * Take a collection of async fns, call the cb on the first to return a truthy value. * If all run without a truthy result, return undefined */ -function asyncFirstSeries (array, iterator, cb) { +export function asyncFirstSeries (array: any[], iterator: Function, cb: Function) { var didComplete = false - async.eachSeries(array, function (item, next) { + async.eachSeries(array, function (item: any, next: Function) { if (didComplete) return next - iterator(item, function (err, result) { + iterator(item, function (err: Error, result: any) { if (result) { didComplete = true process.nextTick(cb.bind(null, null, result)) diff --git a/src/util/hex.js b/src/util/hex.ts similarity index 79% rename from src/util/hex.js rename to src/util/hex.ts index de65f5a..26439a0 100644 --- a/src/util/hex.js +++ b/src/util/hex.ts @@ -4,7 +4,7 @@ * @param {Array} Array of nibbles * @returns {Array} - returns buffer of encoded data **/ -function addHexPrefix (key, terminator) { +export function addHexPrefix (key: number[], terminator: boolean): number[] { // odd if (key.length % 2) { key.unshift(1) @@ -27,7 +27,7 @@ function addHexPrefix (key, terminator) { * @param {Array} Array of nibbles * @private */ -function removeHexPrefix (val) { +export function removeHexPrefix (val: number[]): number[] { if (val[0] % 2) { val = val.slice(1) } else { @@ -43,12 +43,6 @@ function removeHexPrefix (val) { * @param {Array} key - an hexprefixed array of nibbles * @private */ -function isTerminator (key) { +export function isTerminator (key: number[]): boolean { return key[0] > 1 } - -module.exports = { - addHexPrefix, - removeHexPrefix, - isTerminator -} diff --git a/src/util/nibbles.js b/src/util/nibbles.ts similarity index 80% rename from src/util/nibbles.js rename to src/util/nibbles.ts index ecea2e5..18c5b6e 100644 --- a/src/util/nibbles.js +++ b/src/util/nibbles.ts @@ -4,7 +4,7 @@ * @param {Buffer| String} key * @private */ -function stringToNibbles (key) { +export function stringToNibbles (key: Buffer): number[] { const bkey = new Buffer(key) let nibbles = [] @@ -24,7 +24,7 @@ function stringToNibbles (key) { * @param {Array} Nibble array * @private */ -function nibblesToBuffer (arr) { +export function nibblesToBuffer (arr: number[]): Buffer { let buf = new Buffer(arr.length / 2) for (let i = 0; i < buf.length; i++) { let q = i * 2 @@ -40,7 +40,7 @@ function nibblesToBuffer (arr) { * @param {Array} nib2 * @private */ -function matchingNibbleLength (nib1, nib2) { +export function matchingNibbleLength (nib1: number[], nib2: number[]): number { let i = 0 while (nib1[i] === nib2[i] && nib1.length > i) { i++ @@ -53,14 +53,7 @@ function matchingNibbleLength (nib1, nib2) { * @param {Array} keyA * @param {Array} keyB */ -function doKeysMatch (keyA, keyB) { +export function doKeysMatch (keyA: number[], keyB: number[]): boolean { const length = matchingNibbleLength(keyA, keyB) return length === keyA.length && length === keyB.length } - -module.exports = { - stringToNibbles, - nibblesToBuffer, - matchingNibbleLength, - doKeysMatch -} diff --git a/test/checkpoint.js b/test/checkpoint.js index 21aba13..da670cb 100644 --- a/test/checkpoint.js +++ b/test/checkpoint.js @@ -1,5 +1,5 @@ const tape = require('tape') -const Trie = require('../src/checkpointTrie') +const Trie = require('../dist/checkpointTrie').CheckpointTrie tape('testing checkpoints', function (tester) { let trie, preRoot, postRoot, trieCopy diff --git a/test/db.js b/test/db.js index 2f69128..b7096ff 100644 --- a/test/db.js +++ b/test/db.js @@ -1,5 +1,5 @@ const tape = require('tape') -const DB = require('../src/db') +const DB = require('../dist/db').DB tape('DB basic functionality', (t) => { const db = new DB() diff --git a/test/encodeing.js b/test/encodeing.js index 8ddceea..537b6e8 100644 --- a/test/encodeing.js +++ b/test/encodeing.js @@ -1,4 +1,4 @@ -const Trie = require('../src/index.js') +const Trie = require('../dist/index.js').CheckpointTrie const tape = require('tape') const trie = new Trie() const trie2 = new Trie() diff --git a/test/failingRefactorTests.js b/test/failingRefactorTests.js index 121a9b1..b5f67d9 100644 --- a/test/failingRefactorTests.js +++ b/test/failingRefactorTests.js @@ -1,7 +1,7 @@ const async = require('async') const tape = require('tape') -const Trie = require('../src/secure.js') +const Trie = require('../dist/secure.js').SecureTrie const trie = new Trie() const a = new Buffer('f8448080a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0a155280bc3c09fd31b0adebbdd4ef3d5128172c0d2008be964dc9e10e0f0fedf', 'hex') const ak = new Buffer('095e7baea6a6c7c4c2dfeb977efac326af552d87', 'hex') diff --git a/test/index.js b/test/index.js index 97419bf..0059a28 100644 --- a/test/index.js +++ b/test/index.js @@ -1,4 +1,4 @@ -const Trie = require('../src/index.js') +const Trie = require('../dist/index.js').CheckpointTrie const async = require('async') const rlp = require('rlp') const tape = require('tape') diff --git a/test/offical.js b/test/offical.js index bda7fca..040c02d 100644 --- a/test/offical.js +++ b/test/offical.js @@ -1,4 +1,4 @@ -const Trie = require('../src/index.js') +const Trie = require('../dist/index.js').CheckpointTrie const async = require('async') const tape = require('tape') diff --git a/test/prioritizedTaskExecutor.js b/test/prioritizedTaskExecutor.js index 474980d..5b0d76f 100644 --- a/test/prioritizedTaskExecutor.js +++ b/test/prioritizedTaskExecutor.js @@ -1,4 +1,4 @@ -const PrioritizedTaskExecutor = require('../src/prioritizedTaskExecutor.js') +const PrioritizedTaskExecutor = require('../dist/prioritizedTaskExecutor.js').PrioritizedTaskExecutor const tape = require('tape') const taskExecutor = new PrioritizedTaskExecutor(2) diff --git a/test/proof.js b/test/proof.js index 9362e6b..8c4eb1c 100644 --- a/test/proof.js +++ b/test/proof.js @@ -1,4 +1,4 @@ -const Trie = require('../src/index.js') +const Trie = require('../dist/index.js').CheckpointTrie const async = require('async') const tape = require('tape') diff --git a/test/scratch.js b/test/scratch.js index 5be8aa6..9bd6905 100644 --- a/test/scratch.js +++ b/test/scratch.js @@ -1,6 +1,6 @@ const tape = require('tape') -const ScratchDB = require('../src/scratch') -const DB = require('../src/db') +const ScratchDB = require('../dist/scratch').ScratchDB +const DB = require('../dist/db').DB tape('ScratchDB', (t) => { const upstream = new DB() diff --git a/test/secure.js b/test/secure.js index 1c2d5dd..5fd5e2d 100644 --- a/test/secure.js +++ b/test/secure.js @@ -1,4 +1,4 @@ -const Trie = require('../src/secure.js') +const Trie = require('../dist/secure.js').SecureTrie const async = require('async') const tape = require('tape') diff --git a/test/streams.js b/test/streams.js index bf1d5f7..289d3e7 100644 --- a/test/streams.js +++ b/test/streams.js @@ -1,4 +1,4 @@ -const Trie = require('../src/index.js') +const Trie = require('../dist/index.js').CheckpointTrie const describe = require('tape') describe('kv stream test', function (tester) {