improve Tangle logic for unknown root msg

This commit is contained in:
Andre Staltz 2023-04-18 13:54:15 +03:00
parent 188d37fefc
commit 837a78cbfc
1 changed files with 27 additions and 3 deletions

View File

@ -85,13 +85,16 @@ class Tangle {
} }
add(msgHash, msg) { add(msgHash, msg) {
const tangles = msg.metadata.tangles if (msgHash === this.#rootHash && !this.#rootMsg) {
if (msgHash === this.#rootHash) {
this.#tips.add(msgHash) this.#tips.add(msgHash)
this.#perDepth.set(0, [msgHash]) this.#perDepth.set(0, [msgHash])
this.#depth.set(msgHash, 0) this.#depth.set(msgHash, 0)
this.#rootMsg = msg this.#rootMsg = msg
} else if (tangles[this.#rootHash]) { return
}
const tangles = msg.metadata.tangles
if (msgHash !== this.#rootHash && tangles[this.#rootHash]) {
this.#tips.add(msgHash) this.#tips.add(msgHash)
const prev = tangles[this.#rootHash].prev const prev = tangles[this.#rootHash].prev
for (const p of prev) { for (const p of prev) {
@ -105,6 +108,7 @@ class Tangle {
atDepth.push(msgHash) atDepth.push(msgHash)
atDepth.sort(compareMsgHashes) atDepth.sort(compareMsgHashes)
this.#perDepth.set(depth, atDepth) this.#perDepth.set(depth, atDepth)
return
} }
} }
@ -120,6 +124,10 @@ class Tangle {
* @returns {Array<string>} * @returns {Array<string>}
*/ */
topoSort() { topoSort() {
if (!this.#rootMsg) {
console.warn('Tangle is missing root message')
return []
}
const sorted = [] const sorted = []
const max = this.#maxDepth const max = this.#maxDepth
for (let i = 0; i <= max; i++) { for (let i = 0; i <= max; i++) {
@ -136,6 +144,10 @@ class Tangle {
* @returns {Set<string>} * @returns {Set<string>}
*/ */
getTips() { getTips() {
if (!this.#rootMsg) {
console.warn('Tangle is missing root message')
return new Set()
}
return this.#tips return this.#tips
} }
@ -144,6 +156,10 @@ class Tangle {
* @returns {Set<string>} * @returns {Set<string>}
*/ */
getLipmaaSet(depth) { getLipmaaSet(depth) {
if (!this.#rootMsg) {
console.warn('Tangle is missing root message')
return new Set()
}
const lipmaaDepth = lipmaa(depth + 1) - 1 const lipmaaDepth = lipmaa(depth + 1) - 1
return new Set(this.#getAllAtDepth(lipmaaDepth)) return new Set(this.#getAllAtDepth(lipmaaDepth))
} }
@ -165,6 +181,10 @@ class Tangle {
} }
isFeed() { isFeed() {
if (!this.#rootMsg) {
console.warn('Tangle is missing root message')
return false
}
if (this.#rootMsg.content) return false if (this.#rootMsg.content) return false
const metadata = this.#rootMsg.metadata const metadata = this.#rootMsg.metadata
return metadata.size === 0 && metadata.hash === null return metadata.size === 0 && metadata.hash === null
@ -177,6 +197,10 @@ class Tangle {
} }
shortestPathToRoot(msgHash) { shortestPathToRoot(msgHash) {
if (!this.#rootMsg) {
console.warn('Tangle is missing root message')
return []
}
const path = [] const path = []
let current = msgHash let current = msgHash
while (true) { while (true) {