Merge pull request #2398 from nspcc-dev/trim-micro

block/dao: simplify trimming, avoid allocations
This commit is contained in:
Roman Khimov 2022-03-18 12:39:53 +03:00 committed by GitHub
commit 4869049965
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 24 deletions

View file

@ -100,26 +100,16 @@ func New(stateRootEnabled bool) *Block {
} }
} }
// Trim returns a subset of the block data to save up space // EncodeTrimmed writes trimmed representation of the block data into w. Trimmed blocks
// in storage. // do not store complete transactions, instead they only store their hashes.
// Notice that only the hashes of the transactions are stored. func (b *Block) EncodeTrimmed(w *io.BinWriter) {
func (b *Block) Trim() ([]byte, error) { b.Header.EncodeBinary(w)
buf := io.NewBufBinWriter()
numTx := len(b.Transactions)
buf.Grow(b.GetExpectedBlockSizeWithoutTransactions(numTx) + util.Uint256Size*numTx)
b.Header.EncodeBinary(buf.BinWriter)
buf.WriteVarUint(uint64(numTx)) w.WriteVarUint(uint64(len(b.Transactions)))
for _, tx := range b.Transactions { for _, tx := range b.Transactions {
h := tx.Hash() h := tx.Hash()
h.EncodeBinary(buf.BinWriter) h.EncodeBinary(w)
} }
if buf.Err != nil {
return nil, buf.Err
}
return buf.Bytes(), nil
} }
// DecodeBinary decodes the block from the given BinReader, implementing // DecodeBinary decodes the block from the given BinReader, implementing

View file

@ -55,10 +55,11 @@ func TestDecodeBlock1(t *testing.T) {
func TestTrimmedBlock(t *testing.T) { func TestTrimmedBlock(t *testing.T) {
block := getDecodedBlock(t, 1) block := getDecodedBlock(t, 1)
b, err := block.Trim() buf := io.NewBufBinWriter()
require.NoError(t, err) block.EncodeTrimmed(buf.BinWriter)
require.NoError(t, buf.Err)
r := io.NewBinReaderFromBuf(b) r := io.NewBinReaderFromBuf(buf.Bytes())
trimmedBlock, err := NewTrimmedFromReader(false, r) trimmedBlock, err := NewTrimmedFromReader(false, r)
require.NoError(t, err) require.NoError(t, err)

View file

@ -648,11 +648,7 @@ func (dao *Simple) StoreAsBlock(block *block.Block, aer1 *state.AppExecResult, a
buf = dao.getDataBuf() buf = dao.getDataBuf()
) )
buf.WriteB(storage.ExecBlock) buf.WriteB(storage.ExecBlock)
b, err := block.Trim() block.EncodeTrimmed(buf.BinWriter)
if err != nil {
return err
}
buf.WriteBytes(b)
if aer1 != nil { if aer1 != nil {
aer1.EncodeBinary(buf.BinWriter) aer1.EncodeBinary(buf.BinWriter)
} }