From 9586553f5eab6f4e8b5d43d519b606aeeb37e5c6 Mon Sep 17 00:00:00 2001 From: Diego Nava Date: Mon, 25 Sep 2023 13:15:17 +0200 Subject: [PATCH] add verify preimages rpc method --- core/preimages.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ rpc/preimages.go | 6 ++++++ 2 files changed, 53 insertions(+) diff --git a/core/preimages.go b/core/preimages.go index ee3af8129..2ca1545a4 100644 --- a/core/preimages.go +++ b/core/preimages.go @@ -7,13 +7,16 @@ import ( "os" "strconv" + "github.com/ethereum/go-ethereum/common" ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/harmony-one/harmony/api/service/prometheus" + "github.com/harmony-one/harmony/block" "github.com/harmony-one/harmony/core/rawdb" "github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/internal/utils" + "github.com/pkg/errors" prom "github.com/prometheus/client_golang/prometheus" ) @@ -316,3 +319,47 @@ func FindMissingRange( } return 0, 0 } + +func VerifyPreimages(header *block.Header, chain BlockChain) (uint64, error) { + var existingPreimages uint64 + parentRoot := chain.GetBlockByHash( + header.ParentHash(), + ).Root() // for examining MPT at this root, should exist + + db, err := chain.StateAt(parentRoot) + if err != nil { + return 0, err + } + + trie, err := db.Database().OpenTrie(parentRoot) + if err != nil { + return 0, err + } + diskDB := db.Database().DiskDB() + // start the iteration + accountIterator := trie.NodeIterator(nil) + for accountIterator.Next(true) { + // leaf means leaf node of the MPT, which is an account + // the leaf key is the address + if accountIterator.Leaf() { + key := accountIterator.LeafKey() + preimage := rawdb.ReadPreimage(diskDB, common.BytesToHash(key)) + if len(preimage) == 0 { + return 0, errors.New( + fmt.Sprintf( + "cannot find preimage for %x", key, + ), + ) + } + address := common.BytesToAddress(preimage) + // skip blank address + if address == (common.Address{}) { + continue + } + + existingPreimages++ + } + } + + return existingPreimages, nil +} diff --git a/rpc/preimages.go b/rpc/preimages.go index d0ab56f38..cd5b8d527 100644 --- a/rpc/preimages.go +++ b/rpc/preimages.go @@ -27,3 +27,9 @@ func (s *PreimagesService) Export(ctx context.Context, path string) error { // these are by default not blocking return core.ExportPreimages(s.hmy.BlockChain, path) } + +func (s *PreimagesService) Verify(ctx context.Context) (uint64, error) { + currentBlock := s.hmy.CurrentBlock() + // these are by default not blocking + return core.VerifyPreimages(currentBlock.Header(), s.hmy.BlockChain) +}