diff --git a/nodedb.go b/nodedb.go index 7ad69af28..99323c122 100644 --- a/nodedb.go +++ b/nodedb.go @@ -416,10 +416,32 @@ func (ndb *nodeDB) saveNodeFromPruning(node *Node) error { return ndb.batch.Set(ndb.nodeKey(node.GetKey()), buf.Bytes()) } +type rootkeyCache struct { + version int64 + rootKey []byte +} + +func (rkc *rootkeyCache) getRootKey(ndb *nodeDB, version int64) ([]byte, error) { + if rkc.version == version { + return rkc.rootKey, nil + } + rootKey, err := ndb.GetRoot(version) + if err != nil { + return nil, err + } + rkc.setRootKey(version, rootKey) + return rootKey, nil +} + +func (rkc *rootkeyCache) setRootKey(version int64, rootKey []byte) { + rkc.version = version + rkc.rootKey = rootKey +} + // deleteVersion deletes a tree version from disk. // deletes orphans -func (ndb *nodeDB) deleteVersion(version int64) error { - rootKey, err := ndb.GetRoot(version) +func (ndb *nodeDB) deleteVersion(version int64, cache *rootkeyCache) error { + rootKey, err := cache.getRootKey(ndb, version) if err != nil { return err } @@ -457,7 +479,7 @@ func (ndb *nodeDB) deleteVersion(version int64) error { } // check if the version is referred by the next version - nextRootKey, err := ndb.GetRoot(version + 1) + nextRootKey, err := cache.getRootKey(ndb, version+1) if err != nil { return err } @@ -684,8 +706,9 @@ func (ndb *nodeDB) deleteVersionsTo(toVersion int64) error { ndb.resetLegacyLatestVersion(-1) } + rootkeyCache := &rootkeyCache{} for version := first; version <= toVersion; version++ { - if err := ndb.deleteVersion(version); err != nil { + if err := ndb.deleteVersion(version, rootkeyCache); err != nil { return err } ndb.resetFirstVersion(version + 1)