diff --git a/index.js b/index.js index ba5ee5fc..e02a15c4 100644 --- a/index.js +++ b/index.js @@ -535,7 +535,7 @@ class Hypercore extends EventEmitter { get fork () { if (this.opened === false) return 0 - return this.core.tree.fork + return this.state.tree.fork } get peers () { diff --git a/lib/core.js b/lib/core.js index acb954cb..7234071f 100644 --- a/lib/core.js +++ b/lib/core.js @@ -406,7 +406,7 @@ module.exports = class Core { signature = this.verifier.sign(state.tree.batch(), keyPair) } - const tree = await this.state._overwrite(state, length, treeLength, signature, false, atom) + const tree = await this.state._overwrite(state, this.tree.fork, length, treeLength, signature, false, atom) // gc blocks from source if (treeLength < length) { diff --git a/lib/session-state.js b/lib/session-state.js index 8699c84b..80add55e 100644 --- a/lib/session-state.js +++ b/lib/session-state.js @@ -404,7 +404,7 @@ module.exports = class SessionState { } } - async _overwrite (source, length, treeLength, signature, isDependent, atom) { + async _overwrite (source, fork, length, treeLength, signature, isDependent, atom) { const blockPromises = [] const treePromises = [] const rootPromises = [] @@ -481,21 +481,27 @@ module.exports = class SessionState { } const tree = { - fork: this.tree.fork, + fork, length, rootHash: crypto.tree(roots), signature } - const upgraded = treeLength < this.tree.length || this.tree.length < length + const upgraded = treeLength < this.tree.length || this.tree.length < length || tree.fork !== this.tree.fork - if (upgraded) writer.setCoreHead(tree) + if (upgraded) { + writer.setCoreHead(tree) + } const dependency = isDependent ? updateDependency(this, length) : null await this.flushWriteBatch() - if (upgraded) this.tree.setRoots(roots, signature) + if (upgraded) { + this.tree.fork = fork + this.tree.setRoots(roots, signature) + } + if (dependency) this.storage.updateDependencies(dependency.length) return tree @@ -509,8 +515,9 @@ module.exports = class SessionState { try { const origLength = this.tree.length + const fork = treeLength < origLength ? this.tree.fork + 1 : this.tree.fork - const tree = await this._overwrite(state, length, treeLength, null, state === this.core.state, atom) + const tree = await this._overwrite(state, fork, length, treeLength, null, state === this.core.state, atom) const bitfield = { start: treeLength, length: tree.length - treeLength, drop: false }