network: add uncompressed payload size

Closes #1212
This commit is contained in:
Anna Shaleva 2020-07-29 17:09:59 +03:00
parent f24e707ea1
commit 2574b65b74

View file

@ -1,28 +1,32 @@
package network package network
import ( import (
"encoding/binary"
"errors"
"github.com/nspcc-dev/neo-go/pkg/network/payload" "github.com/nspcc-dev/neo-go/pkg/network/payload"
"github.com/pierrec/lz4" "github.com/pierrec/lz4"
) )
// compress compresses bytes using lz4. // compress compresses bytes using lz4.
func compress(source []byte) ([]byte, error) { func compress(source []byte) ([]byte, error) {
dest := make([]byte, lz4.CompressBlockBound(len(source))) dest := make([]byte, 4+lz4.CompressBlockBound(len(source)))
size, err := lz4.CompressBlock(source, dest, nil) size, err := lz4.CompressBlock(source, dest[4:], nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return dest[:size], nil binary.LittleEndian.PutUint32(dest[:4], uint32(len(source)))
return dest[:size+4], nil
} }
// decompress decompresses bytes using lz4. // decompress decompresses bytes using lz4.
func decompress(source []byte) ([]byte, error) { func decompress(source []byte) ([]byte, error) {
maxSize := len(source) * 255 length := binary.LittleEndian.Uint32(source[:4])
if maxSize > payload.MaxSize { if length > payload.MaxSize {
maxSize = payload.MaxSize return nil, errors.New("invalid uncompressed payload length")
} }
dest := make([]byte, maxSize) dest := make([]byte, length)
size, err := lz4.UncompressBlock(source, dest) size, err := lz4.UncompressBlock(source[4:], dest)
if err != nil { if err != nil {
return nil, err return nil, err
} }