github.com/decred/dcrlnd@v0.7.6/fuzz/lnwire/fuzz_utils.go (about) 1 //go:build gofuzz 2 // +build gofuzz 3 4 package lnwirefuzz 5 6 import ( 7 "bytes" 8 "encoding/binary" 9 "reflect" 10 11 "github.com/decred/dcrlnd/lnwire" 12 ) 13 14 // prefixWithMsgType takes []byte and adds a wire protocol prefix 15 // to make the []byte into an actual message to be used in fuzzing. 16 func prefixWithMsgType(data []byte, prefix lnwire.MessageType) []byte { 17 var prefixBytes [2]byte 18 binary.BigEndian.PutUint16(prefixBytes[:], uint16(prefix)) 19 data = append(prefixBytes[:], data...) 20 return data 21 } 22 23 // harness performs the actual fuzz testing of the appropriate wire message. 24 // This function will check that the passed-in message passes wire length checks, 25 // is a valid message once deserialized, and passes a sequence of serialization 26 // and deserialization checks. Returns an int that determines whether the input 27 // is unique or not. 28 func harness(data []byte) int { 29 // Create a reader with the byte array. 30 r := bytes.NewReader(data) 31 32 // Check that the created message is not greater than the maximum 33 // message size. 34 if len(data) > lnwire.MaxSliceLength { 35 return 1 36 } 37 38 msg, err := lnwire.ReadMessage(r, 0) 39 if err != nil { 40 return 1 41 } 42 43 // We will serialize the message into a new bytes buffer. 44 var b bytes.Buffer 45 if _, err := lnwire.WriteMessage(&b, msg, 0); err != nil { 46 // Could not serialize message into bytes buffer, panic 47 panic(err) 48 } 49 50 // Deserialize the message from the serialized bytes buffer, and then 51 // assert that the original message is equal to the newly deserialized 52 // message. 53 newMsg, err := lnwire.ReadMessage(&b, 0) 54 if err != nil { 55 // Could not deserialize message from bytes buffer, panic 56 panic(err) 57 } 58 59 if !reflect.DeepEqual(msg, newMsg) { 60 // Deserialized message and original message are not deeply equal. 61 panic("original message and deserialized message are not deeply equal") 62 } 63 64 return 1 65 }