Moving copy changes back into root #1885
-
Hey, I'm wondering if there's any easy way of moving changes from any copies back into the root trie. My use-case would be that I have a root trie which will contain the finalised state but until that finalised state is known I'm working on a copy of the root. Something like the below pseudo-code would be what I would need. const root = new CheckpointTrie(database);
const temp = root.copy();
// This block gets executed hundreds of times but we
// cannot modify the root state until we are done here
await temp.checkpoint();
try {
// some action that mutates the temp store but we do not
// want to modify the root store until we are sure that
// everything is working as intended and was verified
} catch {
await temp.revert();
}
// We are done so we can merge all changes into the root
root.merge(temp);
// Reset temp to the latest state of the root
temp = root.trie(); Would there be any way to achieve this out of the box? The root trie holds the whole application state and a copy of it is used until finality is reached because until then it could still happen that the changes to the temp trie will be discarded. Note: I've considered to use checkpoints on the root trie but this won't work in my case because there are 2 copies of the root trie. One of them is used for testing state changes but not persisting them and the other is for preparing state changes to be applied to the root trie. The root trie is basically the primary database where data gets dumped after it has been deemed appropriate. The copies are always branched off of the root trie after a cycle finishes and those cycles consist of a lot of actions that are happening and modifying the root trie during that is more risky than working on a copy and discarding it if the changes are deemed as unfit for a merge into the root. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Definitely! The trie has a const root = new CheckpointTrie(database)
const temp = root.copy()
const key = Buffer.from('01','hex')
const value = Buffer.from('02','hex')
async function test() {
temp.checkpoint()
try {
await temp.put(key, value)
await temp.commit()
} catch {
await temp.revert();
}
console.log(await root.get(key)) // null
root.root = temp.root
console.log(await root.get(key)) // <Buffer 02>
}
test() What is important is that you NOTE: the |
Beta Was this translation helpful? Give feedback.
Definitely! The trie has a
root
property. Without going in the technical details, you can think of this as a hash of the entire database, which is deterministic (order of entries does not matter, only the end state, the key/value pairs matter). You can use this to move the changes of any copied trie into your root trie.