github.com/ethereum/go-ethereum@v1.14.3/common/bitutil/compress_test.go (about)

     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  	"fmt"
    22  	"math/rand"
    23  	"testing"
    24  
    25  	"github.com/ethereum/go-ethereum/common/hexutil"
    26  )
    27  
    28  // Tests that data bitset encoding and decoding works and is bijective.
    29  func TestEncodingCycle(t *testing.T) {
    30  	tests := []string{
    31  		// Tests generated by go-fuzz to maximize code coverage
    32  		"0x000000000000000000",
    33  		"0xef0400",
    34  		"0xdf7070533534333636313639343638373532313536346c1bc33339343837313070706336343035336336346c65fefb3930393233383838ac2f65fefb",
    35  		"0x7b64000000",
    36  		"0x000034000000000000",
    37  		"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000",
    38  		"0x4912385c0e7b64000000",
    39  		"0x000034000000000000000000000000000000",
    40  		"0x00",
    41  		"0x000003e834ff7f0000",
    42  		"0x0000",
    43  		"0x0000000000000000000000000000000000000000000000000000000000ff00",
    44  		"0x895f0c6a020f850c6a020f85f88df88d",
    45  		"0xdf7070533534333636313639343638373432313536346c1bc3315aac2f65fefb",
    46  		"0x0000000000",
    47  		"0xdf70706336346c65fefb",
    48  		"0x00006d643634000000",
    49  		"0xdf7070533534333636313639343638373532313536346c1bc333393438373130707063363430353639343638373532313536346c1bc333393438336336346c65fe",
    50  	}
    51  	for i, tt := range tests {
    52  		if err := testEncodingCycle(hexutil.MustDecode(tt)); err != nil {
    53  			t.Errorf("test %d: %v", i, err)
    54  		}
    55  	}
    56  }
    57  
    58  func testEncodingCycle(data []byte) error {
    59  	proc, err := bitsetDecodeBytes(bitsetEncodeBytes(data), len(data))
    60  	if err != nil {
    61  		return fmt.Errorf("failed to decompress compressed data: %v", err)
    62  	}
    63  	if !bytes.Equal(data, proc) {
    64  		return fmt.Errorf("compress/decompress mismatch: have %x, want %x", proc, data)
    65  	}
    66  	return nil
    67  }
    68  
    69  // Tests that data bitset decoding and rencoding works and is bijective.
    70  func TestDecodingCycle(t *testing.T) {
    71  	tests := []struct {
    72  		size  int
    73  		input string
    74  		fail  error
    75  	}{
    76  		{size: 0, input: "0x"},
    77  
    78  		// Crashers generated by go-fuzz
    79  		{size: 0, input: "0x0020", fail: errUnreferencedData},
    80  		{size: 0, input: "0x30", fail: errUnreferencedData},
    81  		{size: 1, input: "0x00", fail: errUnreferencedData},
    82  		{size: 2, input: "0x07", fail: errMissingData},
    83  		{size: 1024, input: "0x8000", fail: errZeroContent},
    84  
    85  		// Tests generated by go-fuzz to maximize code coverage
    86  		{size: 29490, input: "0x343137343733323134333839373334323073333930783e3078333930783e70706336346c65303e", fail: errMissingData},
    87  		{size: 59395, input: "0x00", fail: errUnreferencedData},
    88  		{size: 52574, input: "0x70706336346c65c0de", fail: errExceededTarget},
    89  		{size: 42264, input: "0x07", fail: errMissingData},
    90  		{size: 52, input: "0xa5045bad48f4", fail: errExceededTarget},
    91  		{size: 52574, input: "0xc0de", fail: errMissingData},
    92  		{size: 52574, input: "0x"},
    93  		{size: 29490, input: "0x34313734373332313433383937333432307333393078073034333839373334323073333930783e3078333937333432307333393078073061333930783e70706336346c65303e", fail: errMissingData},
    94  		{size: 29491, input: "0x3973333930783e30783e", fail: errMissingData},
    95  
    96  		{size: 1024, input: "0x808080608080"},
    97  		{size: 1024, input: "0x808470705e3632383337363033313434303137393130306c6580ef46806380635a80"},
    98  		{size: 1024, input: "0x8080808070"},
    99  		{size: 1024, input: "0x808070705e36346c6580ef46806380635a80"},
   100  		{size: 1024, input: "0x80808046802680"},
   101  		{size: 1024, input: "0x4040404035"},
   102  		{size: 1024, input: "0x4040bf3ba2b3f684402d353234373438373934409fe5b1e7ada94ebfd7d0505e27be4035"},
   103  		{size: 1024, input: "0x404040bf3ba2b3f6844035"},
   104  		{size: 1024, input: "0x40402d35323437343837393440bfd7d0505e27be4035"},
   105  	}
   106  	for i, tt := range tests {
   107  		data := hexutil.MustDecode(tt.input)
   108  
   109  		orig, err := bitsetDecodeBytes(data, tt.size)
   110  		if err != tt.fail {
   111  			t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.fail)
   112  		}
   113  		if err != nil {
   114  			continue
   115  		}
   116  		if comp := bitsetEncodeBytes(orig); !bytes.Equal(comp, data) {
   117  			t.Errorf("test %d: decompress/compress mismatch: have %x, want %x", i, comp, data)
   118  		}
   119  	}
   120  }
   121  
   122  // TestCompression tests that compression works by returning either the bitset
   123  // encoded input, or the actual input if the bitset version is longer.
   124  func TestCompression(t *testing.T) {
   125  	// Check the compression returns the bitset encoding is shorter
   126  	in := hexutil.MustDecode("0x4912385c0e7b64000000")
   127  	out := hexutil.MustDecode("0x80fe4912385c0e7b64")
   128  
   129  	if data := CompressBytes(in); !bytes.Equal(data, out) {
   130  		t.Errorf("encoding mismatch for sparse data: have %x, want %x", data, out)
   131  	}
   132  	if data, err := DecompressBytes(out, len(in)); err != nil || !bytes.Equal(data, in) {
   133  		t.Errorf("decoding mismatch for sparse data: have %x, want %x, error %v", data, in, err)
   134  	}
   135  	// Check the compression returns the input if the bitset encoding is longer
   136  	in = hexutil.MustDecode("0xdf7070533534333636313639343638373532313536346c1bc33339343837313070706336343035336336346c65fefb3930393233383838ac2f65fefb")
   137  	out = hexutil.MustDecode("0xdf7070533534333636313639343638373532313536346c1bc33339343837313070706336343035336336346c65fefb3930393233383838ac2f65fefb")
   138  
   139  	if data := CompressBytes(in); !bytes.Equal(data, out) {
   140  		t.Errorf("encoding mismatch for dense data: have %x, want %x", data, out)
   141  	}
   142  	if data, err := DecompressBytes(out, len(in)); err != nil || !bytes.Equal(data, in) {
   143  		t.Errorf("decoding mismatch for dense data: have %x, want %x, error %v", data, in, err)
   144  	}
   145  	// Check that decompressing a longer input than the target fails
   146  	if _, err := DecompressBytes([]byte{0xc0, 0x01, 0x01}, 2); err != errExceededTarget {
   147  		t.Errorf("decoding error mismatch for long data: have %v, want %v", err, errExceededTarget)
   148  	}
   149  }
   150  
   151  // Crude benchmark for compressing random slices of bytes.
   152  func BenchmarkEncoding1KBVerySparse(b *testing.B) { benchmarkEncoding(b, 1024, 0.0001) }
   153  func BenchmarkEncoding2KBVerySparse(b *testing.B) { benchmarkEncoding(b, 2048, 0.0001) }
   154  func BenchmarkEncoding4KBVerySparse(b *testing.B) { benchmarkEncoding(b, 4096, 0.0001) }
   155  
   156  func BenchmarkEncoding1KBSparse(b *testing.B) { benchmarkEncoding(b, 1024, 0.001) }
   157  func BenchmarkEncoding2KBSparse(b *testing.B) { benchmarkEncoding(b, 2048, 0.001) }
   158  func BenchmarkEncoding4KBSparse(b *testing.B) { benchmarkEncoding(b, 4096, 0.001) }
   159  
   160  func BenchmarkEncoding1KBDense(b *testing.B) { benchmarkEncoding(b, 1024, 0.1) }
   161  func BenchmarkEncoding2KBDense(b *testing.B) { benchmarkEncoding(b, 2048, 0.1) }
   162  func BenchmarkEncoding4KBDense(b *testing.B) { benchmarkEncoding(b, 4096, 0.1) }
   163  
   164  func BenchmarkEncoding1KBSaturated(b *testing.B) { benchmarkEncoding(b, 1024, 0.5) }
   165  func BenchmarkEncoding2KBSaturated(b *testing.B) { benchmarkEncoding(b, 2048, 0.5) }
   166  func BenchmarkEncoding4KBSaturated(b *testing.B) { benchmarkEncoding(b, 4096, 0.5) }
   167  
   168  func benchmarkEncoding(b *testing.B, bytes int, fill float64) {
   169  	// Generate a random slice of bytes to compress
   170  	random := rand.NewSource(0) // reproducible and comparable
   171  
   172  	data := make([]byte, bytes)
   173  	bits := int(float64(bytes) * 8 * fill)
   174  
   175  	for i := 0; i < bits; i++ {
   176  		idx := random.Int63() % int64(len(data))
   177  		bit := uint(random.Int63() % 8)
   178  		data[idx] |= 1 << bit
   179  	}
   180  	// Reset the benchmark and measure encoding/decoding
   181  	b.ResetTimer()
   182  	b.ReportAllocs()
   183  	for i := 0; i < b.N; i++ {
   184  		bitsetDecodeBytes(bitsetEncodeBytes(data), len(data))
   185  	}
   186  }
   187  
   188  func FuzzEncoder(f *testing.F) {
   189  	f.Fuzz(func(t *testing.T, data []byte) {
   190  		if err := testEncodingCycle(data); err != nil {
   191  			t.Fatal(err)
   192  		}
   193  	})
   194  }
   195  func FuzzDecoder(f *testing.F) {
   196  	f.Fuzz(func(t *testing.T, data []byte) {
   197  		fuzzDecode(data)
   198  	})
   199  }
   200  
   201  // fuzzDecode implements a go-fuzz fuzzer method to test the bit decoding and
   202  // reencoding algorithm.
   203  func fuzzDecode(data []byte) {
   204  	blob, err := DecompressBytes(data, 1024)
   205  	if err != nil {
   206  		return
   207  	}
   208  	// re-compress it (it's OK if the re-compressed differs from the
   209  	// original - the first input may not have been compressed at all)
   210  	comp := CompressBytes(blob)
   211  	if len(comp) > len(blob) {
   212  		// After compression, it must be smaller or equal
   213  		panic("bad compression")
   214  	}
   215  	// But decompressing it once again should work
   216  	decomp, err := DecompressBytes(data, 1024)
   217  	if err != nil {
   218  		panic(err)
   219  	}
   220  	if !bytes.Equal(decomp, blob) {
   221  		panic("content mismatch")
   222  	}
   223  }