From b60d4ff19177bf0c8137dab50ce3d43090431ccc Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 18 Feb 2022 11:55:06 +0300 Subject: [PATCH] dao: deduplicate header->KV conversion --- pkg/core/blockchain.go | 16 +++++----------- pkg/core/dao/dao.go | 27 ++++++++++++++++++++------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index b629a0373..9d127721f 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -932,7 +932,6 @@ func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) error { } } - buf := io.NewBufBinWriter() bc.headerHashesLock.Lock() defer bc.headerHashesLock.Unlock() oldlen := len(bc.headerHashes) @@ -941,21 +940,16 @@ func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) error { if int(h.Index) != len(bc.headerHashes) { continue } - bc.headerHashes = append(bc.headerHashes, h.Hash()) - buf.WriteB(storage.ExecBlock) - h.EncodeBinary(buf.BinWriter) - buf.BinWriter.WriteB(0) - if buf.Err != nil { - return buf.Err + err = batch.StoreHeader(h) + if err != nil { + return err } - - key := storage.AppendPrefix(storage.DataExecutable, h.Hash().BytesBE()) - batch.Store.Put(key, buf.Bytes()) - buf.Reset() + bc.headerHashes = append(bc.headerHashes, h.Hash()) lastHeader = h } if oldlen != len(bc.headerHashes) { + buf := io.NewBufBinWriter() for int(lastHeader.Index)-headerBatchCount >= int(bc.storedHeaderCount) { buf.WriteArray(bc.headerHashes[bc.storedHeaderCount : bc.storedHeaderCount+headerBatchCount]) if buf.Err != nil { diff --git a/pkg/core/dao/dao.go b/pkg/core/dao/dao.go index cd4221e1b..a69ac0355 100644 --- a/pkg/core/dao/dao.go +++ b/pkg/core/dao/dao.go @@ -668,14 +668,10 @@ func (dao *Simple) DeleteBlock(h util.Uint256) error { return err } - w := dao.getDataBuf() - w.WriteB(storage.ExecBlock) - b.Header.EncodeBinary(w.BinWriter) - w.BinWriter.WriteB(0) - if w.Err != nil { - return w.Err + err = dao.storeHeader(key, &b.Header) + if err != nil { + return err } - dao.Store.Put(key, w.Bytes()) for _, tx := range b.Transactions { copy(key[1:], tx.Hash().BytesBE()) @@ -692,6 +688,23 @@ func (dao *Simple) DeleteBlock(h util.Uint256) error { return nil } +// StoreHeader saves block header into the store. +func (dao *Simple) StoreHeader(h *block.Header) error { + return dao.storeHeader(dao.makeExecutableKey(h.Hash()), h) +} + +func (dao *Simple) storeHeader(key []byte, h *block.Header) error { + buf := dao.getDataBuf() + buf.WriteB(storage.ExecBlock) + h.EncodeBinary(buf.BinWriter) + buf.BinWriter.WriteB(0) + if buf.Err != nil { + return buf.Err + } + dao.Store.Put(key, buf.Bytes()) + return nil +} + // StoreAsCurrentBlock stores a hash of the given block with prefix // SYSCurrentBlock. It can reuse given buffer for the purpose of value // serialization.