github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/bft/store/store.go (about)

     1  package store
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/gnolang/gno/tm2/pkg/amino"
     8  	"github.com/gnolang/gno/tm2/pkg/bft/types"
     9  	dbm "github.com/gnolang/gno/tm2/pkg/db"
    10  	"github.com/gnolang/gno/tm2/pkg/errors"
    11  )
    12  
    13  /*
    14  BlockStore is a simple low level store for blocks.
    15  
    16  There are three types of information stored:
    17    - BlockMeta:   Meta information about each block
    18    - Block part:  Parts of each block, aggregated w/ PartSet
    19    - Commit:      The commit part of each block, for gossiping precommit votes
    20  
    21  Currently the precommit signatures are duplicated in the Block parts as
    22  well as the Commit.  In the future this may change, perhaps by moving
    23  the Commit data outside the Block. (TODO)
    24  
    25  // NOTE: BlockStore methods will panic if they encounter errors
    26  // deserializing loaded data, indicating probable corruption on disk.
    27  */
    28  type BlockStore struct {
    29  	db dbm.DB
    30  
    31  	mtx    sync.RWMutex
    32  	height int64
    33  }
    34  
    35  // NewBlockStore returns a new BlockStore with the given DB,
    36  // initialized to the last height that was committed to the DB.
    37  func NewBlockStore(db dbm.DB) *BlockStore {
    38  	bsjson := LoadBlockStoreStateJSON(db)
    39  	return &BlockStore{
    40  		height: bsjson.Height,
    41  		db:     db,
    42  	}
    43  }
    44  
    45  // Height returns the last known contiguous block height.
    46  func (bs *BlockStore) Height() int64 {
    47  	bs.mtx.RLock()
    48  	defer bs.mtx.RUnlock()
    49  	return bs.height
    50  }
    51  
    52  // LoadBlock returns the block with the given height.
    53  // If no block is found for that height, it returns nil.
    54  func (bs *BlockStore) LoadBlock(height int64) *types.Block {
    55  	blockMeta := bs.LoadBlockMeta(height)
    56  	if blockMeta == nil {
    57  		return nil
    58  	}
    59  
    60  	block := new(types.Block)
    61  	buf := []byte{}
    62  	for i := 0; i < blockMeta.BlockID.PartsHeader.Total; i++ {
    63  		part := bs.LoadBlockPart(height, i)
    64  		buf = append(buf, part.Bytes...)
    65  	}
    66  	err := amino.UnmarshalSized(buf, block)
    67  	if err != nil {
    68  		// NOTE: The existence of meta should imply the existence of the
    69  		// block. So, make sure meta is only saved after blocks are saved.
    70  		panic(errors.Wrap(err, "Error reading block"))
    71  	}
    72  	return block
    73  }
    74  
    75  // LoadBlockPart returns the Part at the given index
    76  // from the block at the given height.
    77  // If no part is found for the given height and index, it returns nil.
    78  func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
    79  	part := new(types.Part)
    80  	bz := bs.db.Get(calcBlockPartKey(height, index))
    81  	if len(bz) == 0 {
    82  		return nil
    83  	}
    84  	err := amino.Unmarshal(bz, part)
    85  	if err != nil {
    86  		panic(errors.Wrap(err, "Error reading block part"))
    87  	}
    88  	return part
    89  }
    90  
    91  // LoadBlockMeta returns the BlockMeta for the given height.
    92  // If no block is found for the given height, it returns nil.
    93  func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
    94  	blockMeta := new(types.BlockMeta)
    95  	bz := bs.db.Get(calcBlockMetaKey(height))
    96  	if len(bz) == 0 {
    97  		return nil
    98  	}
    99  	err := amino.Unmarshal(bz, blockMeta)
   100  	if err != nil {
   101  		panic(errors.Wrap(err, "Error reading block meta"))
   102  	}
   103  	return blockMeta
   104  }
   105  
   106  // LoadBlockCommit returns the Commit for the given height.
   107  // This commit consists of the +2/3 and other Precommit-votes for block at `height`,
   108  // and it comes from the block.LastCommit for `height+1`.
   109  // If no commit is found for the given height, it returns nil.
   110  func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
   111  	commit := new(types.Commit)
   112  	bz := bs.db.Get(calcBlockCommitKey(height))
   113  	if len(bz) == 0 {
   114  		return nil
   115  	}
   116  	err := amino.Unmarshal(bz, commit)
   117  	if err != nil {
   118  		panic(errors.Wrap(err, "Error reading block commit"))
   119  	}
   120  	return commit
   121  }
   122  
   123  // LoadSeenCommit returns the locally seen Commit for the given height.
   124  // This is useful when we've seen a commit, but there has not yet been
   125  // a new block at `height + 1` that includes this commit in its block.LastCommit.
   126  func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
   127  	commit := new(types.Commit)
   128  	bz := bs.db.Get(calcSeenCommitKey(height))
   129  	if len(bz) == 0 {
   130  		return nil
   131  	}
   132  	err := amino.Unmarshal(bz, commit)
   133  	if err != nil {
   134  		panic(errors.Wrap(err, "Error reading block seen commit"))
   135  	}
   136  	return commit
   137  }
   138  
   139  // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
   140  // blockParts: Must be parts of the block
   141  // seenCommit: The +2/3 precommits that were seen which committed at height.
   142  //
   143  //	If all the nodes restart after committing a block,
   144  //	we need this to reload the precommits to catch-up nodes to the
   145  //	most recent height.  Otherwise they'd stall at H-1.
   146  func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
   147  	if block == nil {
   148  		panic("BlockStore can only save a non-nil block")
   149  	}
   150  	height := block.Height
   151  	if g, w := height, bs.Height()+1; g != w {
   152  		panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
   153  	}
   154  	if !blockParts.IsComplete() {
   155  		panic(fmt.Sprintf("BlockStore can only save complete block part sets"))
   156  	}
   157  
   158  	// Save block meta
   159  	blockMeta := types.NewBlockMeta(block, blockParts)
   160  	metaBytes := amino.MustMarshal(blockMeta)
   161  	bs.db.Set(calcBlockMetaKey(height), metaBytes)
   162  
   163  	// Save block parts
   164  	for i := 0; i < blockParts.Total(); i++ {
   165  		part := blockParts.GetPart(i)
   166  		bs.saveBlockPart(height, i, part)
   167  	}
   168  
   169  	// Save block commit (duplicate and separate from the Block)
   170  	blockCommitBytes := amino.MustMarshal(block.LastCommit)
   171  	bs.db.Set(calcBlockCommitKey(height-1), blockCommitBytes)
   172  
   173  	// Save seen commit (seen +2/3 precommits for block)
   174  	// NOTE: we can delete this at a later height
   175  	seenCommitBytes := amino.MustMarshal(seenCommit)
   176  	bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
   177  
   178  	// Save new BlockStoreStateJSON descriptor
   179  	BlockStoreStateJSON{Height: height}.Save(bs.db)
   180  
   181  	// Done!
   182  	bs.mtx.Lock()
   183  	bs.height = height
   184  	bs.mtx.Unlock()
   185  
   186  	// Flush
   187  	bs.db.SetSync(nil, nil)
   188  }
   189  
   190  func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) {
   191  	if height != bs.Height()+1 {
   192  		panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", bs.Height()+1, height))
   193  	}
   194  	partBytes := amino.MustMarshal(part)
   195  	bs.db.Set(calcBlockPartKey(height, index), partBytes)
   196  }
   197  
   198  //-----------------------------------------------------------------------------
   199  
   200  func calcBlockMetaKey(height int64) []byte {
   201  	return []byte(fmt.Sprintf("H:%v", height))
   202  }
   203  
   204  func calcBlockPartKey(height int64, partIndex int) []byte {
   205  	return []byte(fmt.Sprintf("P:%v:%v", height, partIndex))
   206  }
   207  
   208  func calcBlockCommitKey(height int64) []byte {
   209  	return []byte(fmt.Sprintf("C:%v", height))
   210  }
   211  
   212  func calcSeenCommitKey(height int64) []byte {
   213  	return []byte(fmt.Sprintf("SC:%v", height))
   214  }
   215  
   216  //-----------------------------------------------------------------------------
   217  
   218  var blockStoreKey = []byte("blockStore")
   219  
   220  // BlockStoreStateJSON is the block store state JSON structure.
   221  type BlockStoreStateJSON struct {
   222  	Height int64 `json:"height"`
   223  }
   224  
   225  // Save persists the blockStore state to the database as JSON.
   226  func (bsj BlockStoreStateJSON) Save(db dbm.DB) {
   227  	bytes, err := amino.MarshalJSON(bsj)
   228  	if err != nil {
   229  		panic(fmt.Sprintf("Could not marshal state bytes: %v", err))
   230  	}
   231  	db.SetSync(blockStoreKey, bytes)
   232  }
   233  
   234  // LoadBlockStoreStateJSON returns the BlockStoreStateJSON as loaded from disk.
   235  // If no BlockStoreStateJSON was previously persisted, it returns the zero value.
   236  func LoadBlockStoreStateJSON(db dbm.DB) BlockStoreStateJSON {
   237  	bytes := db.Get(blockStoreKey)
   238  	if len(bytes) == 0 {
   239  		return BlockStoreStateJSON{
   240  			Height: 0,
   241  		}
   242  	}
   243  	bsj := BlockStoreStateJSON{}
   244  	err := amino.UnmarshalJSON(bytes, &bsj)
   245  	if err != nil {
   246  		panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes))
   247  	}
   248  	return bsj
   249  }