]> Sergey Matveev's repositories - btrtrc.git/blob - peer_protocol/ut-holepunch/ut-holepunch_test.go
Add holepunch message fuzzing
[btrtrc.git] / peer_protocol / ut-holepunch / ut-holepunch_test.go
1 package utHolepunch
2
3 import (
4         "bytes"
5         "net/netip"
6         "testing"
7
8         qt "github.com/frankban/quicktest"
9 )
10
11 var exampleMsgs = []Msg{
12         {
13                 MsgType:  Rendezvous,
14                 AddrPort: netip.MustParseAddrPort("[1234::1]:42069"),
15                 ErrCode:  16777216,
16         },
17         {
18                 MsgType:  Connect,
19                 AddrPort: netip.MustParseAddrPort("1.2.3.4:42069"),
20                 ErrCode:  16777216,
21         },
22 }
23
24 func TestUnmarshalMsg(t *testing.T) {
25         c := qt.New(t)
26         for _, m := range exampleMsgs {
27                 b, err := m.MarshalBinary()
28                 c.Assert(err, qt.IsNil)
29                 expectedLen := 24
30                 if m.AddrPort.Addr().Is4() {
31                         expectedLen = 12
32                 }
33                 c.Check(b, qt.HasLen, expectedLen)
34                 var um Msg
35                 err = um.UnmarshalBinary(b)
36                 c.Assert(err, qt.IsNil)
37                 c.Check(um, qt.Equals, m)
38         }
39 }
40
41 func FuzzMsg(f *testing.F) {
42         for _, m := range exampleMsgs {
43                 emb, err := m.MarshalBinary()
44                 if err != nil {
45                         f.Fatal(err)
46                 }
47                 f.Add(emb)
48         }
49         f.Fuzz(func(t *testing.T, b []byte) {
50                 var m Msg
51                 err := m.UnmarshalBinary(b)
52                 if err != nil {
53                         t.SkipNow()
54                 }
55                 mb, err := m.MarshalBinary()
56                 if err != nil {
57                         t.Fatal(err)
58                 }
59                 if !bytes.Equal(b, mb) {
60                         t.FailNow()
61                 }
62         })
63 }