Skip to content

Commit

Permalink
chore: Remove backup get_node fetching node in merkle_trie (#1965)
Browse files Browse the repository at this point in the history
## Motivation

Remove the fallback for getting the node from the trie instead of DB,
because a node will always be in the DB


## Merge Checklist

_Choose all relevant options below by adding an `x` now or at any time
before submitting for review_

- [X] PR title adheres to the [conventional
commits](https://www.conventionalcommits.org/en/v1.0.0/) standard
- [X] PR has a
[changeset](https://github.com/farcasterxyz/hub-monorepo/blob/main/CONTRIBUTING.md#35-adding-changesets)
- [ ] PR has been tagged with a change label(s) (i.e. documentation,
feature, bugfix, or chore)
- [ ] PR includes
[documentation](https://github.com/farcasterxyz/hub-monorepo/blob/main/CONTRIBUTING.md#32-writing-docs)
if necessary.
- [X] All [commits have been
signed](https://github.com/farcasterxyz/hub-monorepo/blob/main/CONTRIBUTING.md#22-signing-commits)

<!-- start pr-codex -->

---

## PR-Codex overview
This PR removes backup fetching for `get_node`, refactors `serialize` to
public, updates imports, and refactors node initialization in the Merkle
trie.

### Detailed summary
- Removed backup fetching for `get_node`
- Refactored `serialize` to public in `trie_node.rs`
- Updated imports in `watchContractEvent.ts`
- Refactored node initialization in `merkle_trie.rs`

> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your
question}`

<!-- end pr-codex -->
  • Loading branch information
adityapk00 authored Apr 30, 2024
1 parent f0bee81 commit 1642e61
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/late-feet-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@farcaster/hubble": patch
---

fix: Remove backup fetching for get_node
26 changes: 17 additions & 9 deletions apps/hubble/src/addon/src/trie/merkle_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,25 @@ impl MerkleTrie {
})
}

fn create_empty_root(&self) {
let root_key = TrieNode::make_primary_key(&[], None);
let empty = TrieNode::new();
let serialized = TrieNode::serialize(&empty);

// Write the empty root node to the DB
self.txn_batch.lock().unwrap().put(root_key, serialized);
self.root.write().unwrap().replace(empty);
}

pub fn initialize(&self) -> Result<(), HubError> {
// First open the DB
if self.db_owned.load(std::sync::atomic::Ordering::Relaxed) {
self.db.open()?;
}

// Then load the root node
if let Some(root_bytes) = self.db.get(&TrieNode::make_primary_key(&[], None))? {
let root_key = TrieNode::make_primary_key(&[], None);
if let Some(root_bytes) = self.db.get(&root_key)? {
let root_node = TrieNode::deserialize(&root_bytes.as_slice())?;

info!(self.logger, "Merkle Trie loaded from DB";
Expand All @@ -103,7 +114,7 @@ impl MerkleTrie {
self.root.write().unwrap().replace(root_node);
} else {
info!(self.logger, "Merkle Trie initialized with empty root node");
self.root.write().unwrap().replace(TrieNode::new());
self.create_empty_root();
}

Ok(())
Expand All @@ -116,7 +127,8 @@ impl MerkleTrie {
pub fn clear(&self) -> Result<(), HubError> {
self.txn_batch.lock().unwrap().batch.clear();
self.db.clear()?;
self.root.write().unwrap().replace(TrieNode::new());

self.create_empty_root();

Ok(())
}
Expand Down Expand Up @@ -239,12 +251,8 @@ impl MerkleTrie {
return Some(node);
}
}
// If not found, get it the normal way from the trie root
self.root
.write()
.unwrap()
.as_mut()
.and_then(|root| root.get_node_from_trie(&self.db, prefix, 0).cloned())

None
}

pub fn root_hash(&self) -> Result<Vec<u8>, HubError> {
Expand Down
2 changes: 1 addition & 1 deletion apps/hubble/src/addon/src/trie/trie_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl TrieNode {
key
}

fn serialize(node: &TrieNode) -> Vec<u8> {
pub fn serialize(node: &TrieNode) -> Vec<u8> {
let db_trie_node = DbTrieNode {
key: node.key.as_ref().unwrap_or(&vec![]).clone(),
child_chars: node.children.keys().map(|c| *c as u32).collect(),
Expand Down
7 changes: 4 additions & 3 deletions apps/hubble/src/network/sync/multiPeerSyncEngine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,14 +383,15 @@ describe("Multi peer sync engine", () => {
expect(await syncEngine1.trie.rootHash()).toEqual(await syncEngine2.trie.rootHash());

// Now, delete the messages from engine 1
await engine1.getDb().clear();
engine1.getDb().clear();
const allValues = await syncEngine1.trie.getAllValues(new Uint8Array());
for (const value of allValues) {
await syncEngine1.trie.deleteByBytes(value);
}

// Now, engine 1 should have no messages
expect((await syncEngine1.trie.getTrieNodeMetadata(new Uint8Array()))?.numMessages).toEqual(0);
// Now, engine 1 should have no messages. Getting the metadata for the root should return
// undefined since the root node doesn't exist any more
expect(await syncEngine1.trie.getTrieNodeMetadata(new Uint8Array())).toBeUndefined();

const startScore = syncEngine2.getPeerScore("engine1")?.score ?? 0;

Expand Down

0 comments on commit 1642e61

Please sign in to comment.