compress_fuzz.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. package bitutil
  17. import (
  18. "bytes"
  19. "github.com/ethereum/go-ethereum/common/bitutil"
  20. )
  21. // Fuzz implements a go-fuzz fuzzer method to test various encoding method
  22. // invocations.
  23. func Fuzz(data []byte) int {
  24. if len(data) == 0 {
  25. return 0
  26. }
  27. if data[0]%2 == 0 {
  28. return fuzzEncode(data[1:])
  29. }
  30. return fuzzDecode(data[1:])
  31. }
  32. // fuzzEncode implements a go-fuzz fuzzer method to test the bitset encoding and
  33. // decoding algorithm.
  34. func fuzzEncode(data []byte) int {
  35. proc, _ := bitutil.DecompressBytes(bitutil.CompressBytes(data), len(data))
  36. if !bytes.Equal(data, proc) {
  37. panic("content mismatch")
  38. }
  39. return 1
  40. }
  41. // fuzzDecode implements a go-fuzz fuzzer method to test the bit decoding and
  42. // reencoding algorithm.
  43. func fuzzDecode(data []byte) int {
  44. blob, err := bitutil.DecompressBytes(data, 1024)
  45. if err != nil {
  46. return 0
  47. }
  48. // re-compress it (it's OK if the re-compressed differs from the
  49. // original - the first input may not have been compressed at all)
  50. comp := bitutil.CompressBytes(blob)
  51. if len(comp) > len(blob) {
  52. // After compression, it must be smaller or equal
  53. panic("bad compression")
  54. }
  55. // But decompressing it once again should work
  56. decomp, err := bitutil.DecompressBytes(data, 1024)
  57. if err != nil {
  58. panic(err)
  59. }
  60. if !bytes.Equal(decomp, blob) {
  61. panic("content mismatch")
  62. }
  63. return 1
  64. }