Skip to content

Commit cf19586

Browse files
committed
common/bitutil: fix decompression corner cases; fuzz, test & bench
1 parent fd5d51c commit cf19586

3 files changed

Lines changed: 302 additions & 43 deletions

File tree

‎common/bitutil/compress.go‎

Lines changed: 94 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -16,78 +16,129 @@
1616

1717
package bitutil
1818

19-
/*
20-
The compression algorithm implemented by CompressBytes and DecompressBytes is
21-
optimized for "sparse" input data which contains a lot of zero bytes. Decompression
22-
requires knowledge of the decompressed data length. Compression works as follows:
19+
import "errors"
2320

24-
if data only contains zeroes,
25-
CompressBytes(data) == nil
26-
otherwise if len(data) <= 1,
27-
CompressBytes(data) == data
28-
otherwise:
29-
CompressBytes(data) == append(CompressBytes(nonZeroBits(data)), nonZeroBytes(data)...)
30-
where
31-
nonZeroBits(data) is a bit vector with len(data) bits (MSB first):
32-
nonZeroBits(data)[i/8] && (1 << (7-i%8)) != 0 if data[i] != 0
33-
len(nonZeroBits(data)) == (len(data)+7)/8
34-
nonZeroBytes(data) contains the non-zero bytes of data in the same order
35-
*/
21+
var (
22+
// ErrMissingData is returned from decompression if the byte referenced by
23+
// the bitset header overflows the input data.
24+
ErrMissingData = errors.New("missing bytes on input")
3625

37-
// CompressBytes compresses the input byte slice
26+
// ErrUnreferencedData is returned from decompression if not all bytes were used
27+
// up from the input data after decompressing it.
28+
ErrUnreferencedData = errors.New("extra bytes on input")
29+
30+
// ErrExceededTarget is returned from decompression if the bitset header has
31+
// more bits defined than the number of target buffer space available.
32+
ErrExceededTarget = errors.New("target data size exceeded")
33+
34+
// ErrZeroContent is returned from decompression if a data byte referenced in
35+
// the bitset header is actually a zero byte.
36+
ErrZeroContent = errors.New("zero byte in input content")
37+
)
38+
39+
// The compression algorithm implemented by CompressBytes and DecompressBytes is
40+
// optimized for sparse input data which contains a lot of zero bytes. Decompression
41+
// requires knowledge of the decompressed data length.
42+
//
43+
// Compression works as follows:
44+
//
45+
// if data only contains zeroes,
46+
// CompressBytes(data) == nil
47+
// otherwise if len(data) <= 1,
48+
// CompressBytes(data) == data
49+
// otherwise:
50+
// CompressBytes(data) == append(CompressBytes(nonZeroBitset(data)), nonZeroBytes(data)...)
51+
// where
52+
// nonZeroBitset(data) is a bit vector with len(data) bits (MSB first):
53+
// nonZeroBitset(data)[i/8] && (1 << (7-i%8)) != 0 if data[i] != 0
54+
// len(nonZeroBitset(data)) == (len(data)+7)/8
55+
// nonZeroBytes(data) contains the non-zero bytes of data in the same order
56+
57+
// CompressBytes compresses the input byte slice according to the sparse bitset
58+
// representation algorithm.
3859
func CompressBytes(data []byte) []byte {
60+
// Empty slices get compressed to nil
3961
if len(data) == 0 {
4062
return nil
4163
}
64+
// One byte slices compress to nil or retain the single byte
4265
if len(data) == 1 {
4366
if data[0] == 0 {
4467
return nil
45-
} else {
46-
return data
4768
}
69+
return data
4870
}
49-
50-
bitsLen := (len(data) + 7) / 8
51-
nonZeroBits := make([]byte, bitsLen)
71+
// Calculate the bitset of set bytes, and gather the non-zero bytes
72+
nonZeroBitset := make([]byte, (len(data)+7)/8)
5273
nonZeroBytes := make([]byte, 0, len(data))
74+
5375
for i, b := range data {
5476
if b != 0 {
5577
nonZeroBytes = append(nonZeroBytes, b)
56-
nonZeroBits[i/8] |= 1 << byte(7-i%8)
78+
nonZeroBitset[i/8] |= 1 << byte(7-i%8)
5779
}
5880
}
5981
if len(nonZeroBytes) == 0 {
6082
return nil
6183
}
62-
return append(CompressBytes(nonZeroBits), nonZeroBytes...)
84+
return append(CompressBytes(nonZeroBitset), nonZeroBytes...)
6385
}
6486

65-
// DecompressBytes decompresses data with a known target size.
66-
// In addition to the decompressed output, the function returns the length of
67-
// compressed input data corresponding to the output. The input slice may be longer.
68-
// If the input slice is too short, (nil, -1) is returned.
69-
func DecompressBytes(data []byte, targetLen int) ([]byte, int) {
70-
decomp := make([]byte, targetLen)
71-
if len(data) == 0 {
72-
return decomp, 0
87+
// DecompressBytes decompresses data with a known target size. In addition to the
88+
// decompressed output, the function returns the length of compressed input data
89+
// corresponding to the output as the input slice may be longer.
90+
func DecompressBytes(data []byte, target int) ([]byte, error) {
91+
out, size, err := decompressBytes(data, target)
92+
if err != nil {
93+
return nil, err
7394
}
74-
if targetLen == 1 {
75-
return data[0:1], 1
95+
if size != len(data) {
96+
return nil, ErrUnreferencedData
7697
}
98+
return out, nil
99+
}
77100

78-
bitsLen := (targetLen + 7) / 8
79-
nonZeroBits, ptr := DecompressBytes(data, bitsLen)
80-
if ptr < 0 {
81-
return nil, -1
101+
// decompressBytes decompresses data with a known target size. In addition to the
102+
// decompressed output, the function returns the length of compressed input data
103+
// corresponding to the output as the input slice may be longer.
104+
func decompressBytes(data []byte, target int) ([]byte, int, error) {
105+
// Sanity check 0 targets to avoid infinite recursion
106+
if target == 0 {
107+
return nil, 0, nil
108+
}
109+
// Handle the zero and single byte corner cases
110+
decomp := make([]byte, target)
111+
if len(data) == 0 {
112+
return decomp, 0, nil
113+
}
114+
if target == 1 {
115+
decomp[0] = data[0] // copy to avoid referencing the input slice
116+
if data[0] != 0 {
117+
return decomp, 1, nil
118+
}
119+
return decomp, 0, nil
120+
}
121+
// Decompress the bitset of set bytes and distribute the non zero bytes
122+
nonZeroBitset, ptr, err := decompressBytes(data, (target+7)/8)
123+
if err != nil {
124+
return nil, ptr, err
82125
}
83-
for i, _ := range decomp {
84-
if nonZeroBits[i/8]&(1<<byte(7-i%8)) != 0 {
85-
if ptr == len(data) {
86-
return nil, -1
126+
for i := 0; i < 8*len(nonZeroBitset); i++ {
127+
if nonZeroBitset[i/8]&(1<<byte(7-i%8)) != 0 {
128+
// Make sure we have enough data to push into the correct slot
129+
if ptr >= len(data) {
130+
return nil, 0, ErrMissingData
131+
}
132+
if i >= len(decomp) {
133+
return nil, 0, ErrExceededTarget
134+
}
135+
// Make sure the data is valid and push into the slot
136+
if data[ptr] == 0 {
137+
return nil, 0, ErrZeroContent
87138
}
88139
decomp[i] = data[ptr]
89140
ptr++
90141
}
91142
}
92-
return decomp, ptr
143+
return decomp, ptr, nil
93144
}

‎common/bitutil/compress_fuzz.go‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
// +build gofuzz
18+
19+
package bitutil
20+
21+
import "bytes"
22+
23+
// Fuzz implements a go-fuzz fuzzer method to test various compression method
24+
// invocations.
25+
func Fuzz(data []byte) int {
26+
if len(data) == 0 {
27+
return -1
28+
}
29+
if data[0]%2 == 0 {
30+
return fuzzCompress(data[1:])
31+
}
32+
return fuzzDecompress(data[1:])
33+
}
34+
35+
// fuzzCompress implements a go-fuzz fuzzer method to test the bit compression and
36+
// decompression algorithm.
37+
func fuzzCompress(data []byte) int {
38+
proc, _ := DecompressBytes(CompressBytes(data), len(data))
39+
if !bytes.Equal(data, proc) {
40+
panic("content mismatch")
41+
}
42+
return 0
43+
}
44+
45+
// fuzzDecompress implements a go-fuzz fuzzer method to test the bit decompression
46+
// and recompression algorithm.
47+
func fuzzDecompress(data []byte) int {
48+
blob, err := DecompressBytes(data, 1024)
49+
if err != nil {
50+
return 0
51+
}
52+
if comp := CompressBytes(blob); !bytes.Equal(comp, data) {
53+
panic("content mismatch")
54+
}
55+
return 0
56+
}

‎common/bitutil/compress_test.go‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package bitutil
18+
19+
import (
20+
"bytes"
21+
"math/rand"
22+
"testing"
23+
24+
"github.com/ethereum/go-ethereum/common/hexutil"
25+
)
26+
27+
// Tests that data compression and decompression works correctly.
28+
func TestCompressCycle(t *testing.T) {
29+
tests := []string{
30+
// Tests generated by go-fuzz to maximize code coverage
31+
"0x000000000000000000",
32+
"0xef0400",
33+
"0xdf7070533534333636313639343638373532313536346c1bc33339343837313070706336343035336336346c65fefb3930393233383838ac2f65fefb",
34+
"0x7b64000000",
35+
"0x000034000000000000",
36+
"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000",
37+
"0x4912385c0e7b64000000",
38+
"0x000034000000000000000000000000000000",
39+
"0x00",
40+
"0x000003e834ff7f0000",
41+
"0x0000",
42+
"0x0000000000000000000000000000000000000000000000000000000000ff00",
43+
"0x895f0c6a020f850c6a020f85f88df88d",
44+
"0xdf7070533534333636313639343638373432313536346c1bc3315aac2f65fefb",
45+
"0x0000000000",
46+
"0xdf70706336346c65fefb",
47+
"0x00006d643634000000",
48+
"0xdf7070533534333636313639343638373532313536346c1bc333393438373130707063363430353639343638373532313536346c1bc333393438336336346c65fe",
49+
}
50+
for i, tt := range tests {
51+
data := hexutil.MustDecode(tt)
52+
53+
proc, err := DecompressBytes(CompressBytes(data), len(data))
54+
if err != nil {
55+
t.Errorf("test %d: failed to decompress compressed data: %v", i, err)
56+
continue
57+
}
58+
if !bytes.Equal(data, proc) {
59+
t.Errorf("test %d: compress/decompress mismatch: have %x, want %x", i, proc, data)
60+
}
61+
}
62+
}
63+
64+
// Tests that data decompression works
65+
func TestDecompress(t *testing.T) {
66+
tests := []struct {
67+
size int
68+
input string
69+
fail error
70+
}{
71+
{size: 0, input: "0x"},
72+
73+
// Crashers generated by go-fuzz
74+
{size: 0, input: "0x0020", fail: ErrUnreferencedData},
75+
{size: 0, input: "0x30", fail: ErrUnreferencedData},
76+
{size: 1, input: "0x00", fail: ErrUnreferencedData},
77+
{size: 2, input: "0x07", fail: ErrMissingData},
78+
{size: 1024, input: "0x8000", fail: ErrZeroContent},
79+
80+
// Tests generated by go-fuzz to maximize code coverage
81+
{size: 29490, input: "0x343137343733323134333839373334323073333930783e3078333930783e70706336346c65303e", fail: ErrMissingData},
82+
{size: 59395, input: "0x00", fail: ErrUnreferencedData},
83+
{size: 52574, input: "0x70706336346c65c0de", fail: ErrExceededTarget},
84+
{size: 42264, input: "0x07", fail: ErrMissingData},
85+
{size: 52, input: "0xa5045bad48f4", fail: ErrExceededTarget},
86+
{size: 52574, input: "0xc0de", fail: ErrMissingData},
87+
{size: 52574, input: "0x"},
88+
{size: 29490, input: "0x34313734373332313433383937333432307333393078073034333839373334323073333930783e3078333937333432307333393078073061333930783e70706336346c65303e", fail: ErrMissingData},
89+
{size: 29491, input: "0x3973333930783e30783e", fail: ErrMissingData},
90+
91+
{size: 1024, input: "0x808080608080"},
92+
{size: 1024, input: "0x808470705e3632383337363033313434303137393130306c6580ef46806380635a80"},
93+
{size: 1024, input: "0x8080808070"},
94+
{size: 1024, input: "0x808070705e36346c6580ef46806380635a80"},
95+
{size: 1024, input: "0x80808046802680"},
96+
{size: 1024, input: "0x4040404035"},
97+
{size: 1024, input: "0x4040bf3ba2b3f684402d353234373438373934409fe5b1e7ada94ebfd7d0505e27be4035"},
98+
{size: 1024, input: "0x404040bf3ba2b3f6844035"},
99+
{size: 1024, input: "0x40402d35323437343837393440bfd7d0505e27be4035"},
100+
}
101+
for i, tt := range tests {
102+
data := hexutil.MustDecode(tt.input)
103+
104+
orig, err := DecompressBytes(data, tt.size)
105+
if err != tt.fail {
106+
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.fail)
107+
}
108+
if err != nil {
109+
continue
110+
}
111+
if comp := CompressBytes(orig); !bytes.Equal(comp, data) {
112+
t.Errorf("test %d: decompress/compress mismatch: have %x, want %x", i, comp, data)
113+
}
114+
}
115+
}
116+
117+
// Crude benchmark for compressing random slices of bytes.
118+
func BenchmarkCompress1KBVerySparse(b *testing.B) { benchmarkCompress(b, 1024, 0.0001) }
119+
func BenchmarkCompress2KBVerySparse(b *testing.B) { benchmarkCompress(b, 2048, 0.0001) }
120+
func BenchmarkCompress4KBVerySparse(b *testing.B) { benchmarkCompress(b, 4096, 0.0001) }
121+
122+
func BenchmarkCompress1KBSparse(b *testing.B) { benchmarkCompress(b, 1024, 0.001) }
123+
func BenchmarkCompress2KBSparse(b *testing.B) { benchmarkCompress(b, 2048, 0.001) }
124+
func BenchmarkCompress4KBSparse(b *testing.B) { benchmarkCompress(b, 4096, 0.001) }
125+
126+
func BenchmarkCompress1KBDense(b *testing.B) { benchmarkCompress(b, 1024, 0.1) }
127+
func BenchmarkCompress2KBDense(b *testing.B) { benchmarkCompress(b, 2048, 0.1) }
128+
func BenchmarkCompress4KBDense(b *testing.B) { benchmarkCompress(b, 4096, 0.1) }
129+
130+
func BenchmarkCompress1KBSaturated(b *testing.B) { benchmarkCompress(b, 1024, 0.5) }
131+
func BenchmarkCompress2KBSaturated(b *testing.B) { benchmarkCompress(b, 2048, 0.5) }
132+
func BenchmarkCompress4KBSaturated(b *testing.B) { benchmarkCompress(b, 4096, 0.5) }
133+
134+
func benchmarkCompress(b *testing.B, bytes int, fill float64) {
135+
// Generate a random slice of bytes to compress
136+
random := rand.NewSource(0) // reproducible and comparable
137+
138+
data := make([]byte, bytes)
139+
bits := int(float64(bytes) * 8 * fill)
140+
141+
for i := 0; i < bits; i++ {
142+
idx := random.Int63() % int64(len(data))
143+
bit := uint(random.Int63() % 8)
144+
data[idx] |= 1 << bit
145+
}
146+
// Reset the benchmark and measure compression/decompression
147+
b.ResetTimer()
148+
b.ReportAllocs()
149+
for i := 0; i < b.N; i++ {
150+
DecompressBytes(CompressBytes(data), len(data))
151+
}
152+
}

0 commit comments

Comments
 (0)