deephash_test.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package deephash
  4. import (
  5. "archive/tar"
  6. "crypto/sha256"
  7. "encoding/binary"
  8. "fmt"
  9. "hash"
  10. "math"
  11. "math/bits"
  12. "math/rand"
  13. "net/netip"
  14. "reflect"
  15. "runtime"
  16. "testing"
  17. "testing/quick"
  18. "time"
  19. qt "github.com/frankban/quicktest"
  20. "go4.org/mem"
  21. "go4.org/netipx"
  22. "tailscale.com/tailcfg"
  23. "tailscale.com/types/dnstype"
  24. "tailscale.com/types/ipproto"
  25. "tailscale.com/types/key"
  26. "tailscale.com/types/ptr"
  27. "tailscale.com/util/deephash/testtype"
  28. "tailscale.com/util/dnsname"
  29. "tailscale.com/version"
  30. "tailscale.com/wgengine/filter"
  31. "tailscale.com/wgengine/router"
  32. "tailscale.com/wgengine/wgcfg"
  33. )
  34. type appendBytes []byte
  35. func (p appendBytes) AppendTo(b []byte) []byte {
  36. return append(b, p...)
  37. }
  38. func TestHash(t *testing.T) {
  39. type tuple [2]any
  40. type iface struct{ X any }
  41. type scalars struct {
  42. I8 int8
  43. I16 int16
  44. I32 int32
  45. I64 int64
  46. I int
  47. U8 uint8
  48. U16 uint16
  49. U32 uint32
  50. U64 uint64
  51. U uint
  52. UP uintptr
  53. F32 float32
  54. F64 float64
  55. C64 complex64
  56. C128 complex128
  57. }
  58. type MyBool bool
  59. type MyHeader tar.Header
  60. var zeroFloat64 float64
  61. tests := []struct {
  62. in tuple
  63. wantEq bool
  64. }{
  65. {in: tuple{false, true}, wantEq: false},
  66. {in: tuple{true, true}, wantEq: true},
  67. {in: tuple{false, false}, wantEq: true},
  68. {
  69. in: tuple{
  70. scalars{-8, -16, -32, -64, -1234, 8, 16, 32, 64, 1234, 5678, 32.32, 64.64, 32 + 32i, 64 + 64i},
  71. scalars{-8, -16, -32, -64, -1234, 8, 16, 32, 64, 1234, 5678, 32.32, 64.64, 32 + 32i, 64 + 64i},
  72. },
  73. wantEq: true,
  74. },
  75. {in: tuple{scalars{I8: math.MinInt8}, scalars{I8: math.MinInt8 / 2}}, wantEq: false},
  76. {in: tuple{scalars{I16: math.MinInt16}, scalars{I16: math.MinInt16 / 2}}, wantEq: false},
  77. {in: tuple{scalars{I32: math.MinInt32}, scalars{I32: math.MinInt32 / 2}}, wantEq: false},
  78. {in: tuple{scalars{I64: math.MinInt64}, scalars{I64: math.MinInt64 / 2}}, wantEq: false},
  79. {in: tuple{scalars{I: -1234}, scalars{I: -1234 / 2}}, wantEq: false},
  80. {in: tuple{scalars{U8: math.MaxUint8}, scalars{U8: math.MaxUint8 / 2}}, wantEq: false},
  81. {in: tuple{scalars{U16: math.MaxUint16}, scalars{U16: math.MaxUint16 / 2}}, wantEq: false},
  82. {in: tuple{scalars{U32: math.MaxUint32}, scalars{U32: math.MaxUint32 / 2}}, wantEq: false},
  83. {in: tuple{scalars{U64: math.MaxUint64}, scalars{U64: math.MaxUint64 / 2}}, wantEq: false},
  84. {in: tuple{scalars{U: 1234}, scalars{U: 1234 / 2}}, wantEq: false},
  85. {in: tuple{scalars{UP: 5678}, scalars{UP: 5678 / 2}}, wantEq: false},
  86. {in: tuple{scalars{F32: 32.32}, scalars{F32: math.Nextafter32(32.32, 0)}}, wantEq: false},
  87. {in: tuple{scalars{F64: 64.64}, scalars{F64: math.Nextafter(64.64, 0)}}, wantEq: false},
  88. {in: tuple{scalars{F32: float32(math.NaN())}, scalars{F32: float32(math.NaN())}}, wantEq: true},
  89. {in: tuple{scalars{F64: float64(math.NaN())}, scalars{F64: float64(math.NaN())}}, wantEq: true},
  90. {in: tuple{scalars{C64: 32 + 32i}, scalars{C64: complex(math.Nextafter32(32, 0), 32)}}, wantEq: false},
  91. {in: tuple{scalars{C128: 64 + 64i}, scalars{C128: complex(math.Nextafter(64, 0), 64)}}, wantEq: false},
  92. {in: tuple{[]int(nil), []int(nil)}, wantEq: true},
  93. {in: tuple{[]int{}, []int(nil)}, wantEq: false},
  94. {in: tuple{[]int{}, []int{}}, wantEq: true},
  95. {in: tuple{[]string(nil), []string(nil)}, wantEq: true},
  96. {in: tuple{[]string{}, []string(nil)}, wantEq: false},
  97. {in: tuple{[]string{}, []string{}}, wantEq: true},
  98. {in: tuple{[]appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}, []appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}}, wantEq: true},
  99. {in: tuple{[]appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}, []appendBytes{{0, 0, 0, 0, 0, 0, 0, 1}, {}}}, wantEq: false},
  100. {in: tuple{iface{MyBool(true)}, iface{MyBool(true)}}, wantEq: true},
  101. {in: tuple{iface{true}, iface{MyBool(true)}}, wantEq: false},
  102. {in: tuple{iface{MyHeader{}}, iface{MyHeader{}}}, wantEq: true},
  103. {in: tuple{iface{MyHeader{}}, iface{tar.Header{}}}, wantEq: false},
  104. {in: tuple{iface{&MyHeader{}}, iface{&MyHeader{}}}, wantEq: true},
  105. {in: tuple{iface{&MyHeader{}}, iface{&tar.Header{}}}, wantEq: false},
  106. {in: tuple{iface{[]map[string]MyBool{}}, iface{[]map[string]MyBool{}}}, wantEq: true},
  107. {in: tuple{iface{[]map[string]bool{}}, iface{[]map[string]MyBool{}}}, wantEq: false},
  108. {in: tuple{zeroFloat64, -zeroFloat64}, wantEq: false}, // Issue 4883 (false alarm)
  109. {in: tuple{[]any(nil), 0.0}, wantEq: false}, // Issue 4883
  110. {in: tuple{[]any(nil), uint8(0)}, wantEq: false}, // Issue 4883
  111. {in: tuple{nil, nil}, wantEq: true}, // Issue 4883
  112. {
  113. in: func() tuple {
  114. i1 := 1
  115. i2 := 2
  116. v1 := [3]*int{&i1, &i2, &i1}
  117. v2 := [3]*int{&i1, &i2, &i2}
  118. return tuple{v1, v2}
  119. }(),
  120. wantEq: false,
  121. },
  122. {in: tuple{netip.Addr{}, netip.Addr{}}, wantEq: true},
  123. {in: tuple{netip.Addr{}, netip.AddrFrom4([4]byte{})}, wantEq: false},
  124. {in: tuple{netip.AddrFrom4([4]byte{}), netip.AddrFrom4([4]byte{})}, wantEq: true},
  125. {in: tuple{netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 1})}, wantEq: true},
  126. {in: tuple{netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 2})}, wantEq: false},
  127. {in: tuple{netip.AddrFrom4([4]byte{}), netip.AddrFrom16([16]byte{})}, wantEq: false},
  128. {in: tuple{netip.AddrFrom16([16]byte{}), netip.AddrFrom16([16]byte{})}, wantEq: true},
  129. {in: tuple{netip.AddrPort{}, netip.AddrPort{}}, wantEq: true},
  130. {in: tuple{netip.AddrPort{}, netip.AddrPortFrom(netip.AddrFrom4([4]byte{}), 0)}, wantEq: false},
  131. {in: tuple{netip.AddrPortFrom(netip.AddrFrom4([4]byte{}), 0), netip.AddrPortFrom(netip.AddrFrom4([4]byte{}), 0)}, wantEq: true},
  132. {in: tuple{netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1234), netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1234)}, wantEq: true},
  133. {in: tuple{netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1234), netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1235)}, wantEq: false},
  134. {in: tuple{netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1234), netip.AddrPortFrom(netip.AddrFrom4([4]byte{192, 168, 0, 2}), 1234)}, wantEq: false},
  135. {in: tuple{netip.Prefix{}, netip.Prefix{}}, wantEq: true},
  136. // In go1.21 PrefixFrom will now return a zero value Prefix if the
  137. // provided Addr is unspecified. This is a change from previous
  138. // behavior, so we disable this test for now.
  139. // TODO(#8419): renable after go1.21 is released.
  140. // {in: tuple{netip.Prefix{}, netip.PrefixFrom(netip.Addr{}, 1)}, wantEq: true},
  141. {in: tuple{netip.Prefix{}, netip.PrefixFrom(netip.AddrFrom4([4]byte{}), 0)}, wantEq: false},
  142. {in: tuple{netip.PrefixFrom(netip.AddrFrom4([4]byte{}), 1), netip.PrefixFrom(netip.AddrFrom4([4]byte{}), 1)}, wantEq: true},
  143. {in: tuple{netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1), netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1)}, wantEq: true},
  144. {in: tuple{netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1), netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 0)}, wantEq: false},
  145. {in: tuple{netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), 1), netip.PrefixFrom(netip.AddrFrom4([4]byte{192, 168, 0, 2}), 1)}, wantEq: false},
  146. {in: tuple{netipx.IPRange{}, netipx.IPRange{}}, wantEq: true},
  147. {in: tuple{netipx.IPRange{}, netipx.IPRangeFrom(netip.AddrFrom4([4]byte{}), netip.AddrFrom16([16]byte{}))}, wantEq: false},
  148. {in: tuple{netipx.IPRangeFrom(netip.AddrFrom4([4]byte{}), netip.AddrFrom16([16]byte{})), netipx.IPRangeFrom(netip.AddrFrom4([4]byte{}), netip.AddrFrom16([16]byte{}))}, wantEq: true},
  149. {in: tuple{netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 100})), netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 100}))}, wantEq: true},
  150. {in: tuple{netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 100})), netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 101}))}, wantEq: false},
  151. {in: tuple{netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 1}), netip.AddrFrom4([4]byte{192, 168, 0, 100})), netipx.IPRangeFrom(netip.AddrFrom4([4]byte{192, 168, 0, 2}), netip.AddrFrom4([4]byte{192, 168, 0, 100}))}, wantEq: false},
  152. {in: tuple{key.DiscoPublic{}, key.DiscoPublic{}}, wantEq: true},
  153. {in: tuple{key.DiscoPublic{}, key.DiscoPublicFromRaw32(mem.B(func() []byte {
  154. b := make([]byte, 32)
  155. b[0] = 1
  156. return b
  157. }()))}, wantEq: false},
  158. {in: tuple{key.NodePublic{}, key.NodePublic{}}, wantEq: true},
  159. {in: tuple{key.NodePublic{}, key.NodePublicFromRaw32(mem.B(func() []byte {
  160. b := make([]byte, 32)
  161. b[0] = 1
  162. return b
  163. }()))}, wantEq: false},
  164. }
  165. for _, tt := range tests {
  166. gotEq := Hash(&tt.in[0]) == Hash(&tt.in[1])
  167. if gotEq != tt.wantEq {
  168. t.Errorf("(Hash(%T %v) == Hash(%T %v)) = %v, want %v", tt.in[0], tt.in[0], tt.in[1], tt.in[1], gotEq, tt.wantEq)
  169. }
  170. }
  171. }
  172. func TestDeepHash(t *testing.T) {
  173. // v contains the types of values we care about for our current callers.
  174. // Mostly we're just testing that we don't panic on handled types.
  175. v := getVal()
  176. hash1 := Hash(v)
  177. t.Logf("hash: %v", hash1)
  178. for i := 0; i < 20; i++ {
  179. v := getVal()
  180. hash2 := Hash(v)
  181. if hash1 != hash2 {
  182. t.Error("second hash didn't match")
  183. }
  184. }
  185. }
  186. // Tests that we actually hash map elements. Whoops.
  187. func TestIssue4868(t *testing.T) {
  188. m1 := map[int]string{1: "foo"}
  189. m2 := map[int]string{1: "bar"}
  190. if Hash(&m1) == Hash(&m2) {
  191. t.Error("bogus")
  192. }
  193. }
  194. func TestIssue4871(t *testing.T) {
  195. m1 := map[string]string{"": "", "x": "foo"}
  196. m2 := map[string]string{}
  197. if h1, h2 := Hash(&m1), Hash(&m2); h1 == h2 {
  198. t.Errorf("bogus: h1=%x, h2=%x", h1, h2)
  199. }
  200. }
  201. func TestNilVsEmptymap(t *testing.T) {
  202. m1 := map[string]string(nil)
  203. m2 := map[string]string{}
  204. if h1, h2 := Hash(&m1), Hash(&m2); h1 == h2 {
  205. t.Errorf("bogus: h1=%x, h2=%x", h1, h2)
  206. }
  207. }
  208. func TestMapFraming(t *testing.T) {
  209. m1 := map[string]string{"foo": "", "fo": "o"}
  210. m2 := map[string]string{}
  211. if h1, h2 := Hash(&m1), Hash(&m2); h1 == h2 {
  212. t.Errorf("bogus: h1=%x, h2=%x", h1, h2)
  213. }
  214. }
  215. func TestQuick(t *testing.T) {
  216. initSeed()
  217. err := quick.Check(func(v, w map[string]string) bool {
  218. return (Hash(&v) == Hash(&w)) == reflect.DeepEqual(v, w)
  219. }, &quick.Config{MaxCount: 1000, Rand: rand.New(rand.NewSource(int64(seed)))})
  220. if err != nil {
  221. t.Fatalf("seed=%v, err=%v", seed, err)
  222. }
  223. }
  224. type tailscaleTypes struct {
  225. WGConfig *wgcfg.Config
  226. RouterConfig *router.Config
  227. MapFQDNAddrs map[dnsname.FQDN][]netip.Addr
  228. MapFQDNAddrPorts map[dnsname.FQDN][]netip.AddrPort
  229. MapDiscoPublics map[key.DiscoPublic]bool
  230. MapResponse *tailcfg.MapResponse
  231. FilterMatch filter.Match
  232. }
  233. func getVal() *tailscaleTypes {
  234. return &tailscaleTypes{
  235. &wgcfg.Config{
  236. Name: "foo",
  237. Addresses: []netip.Prefix{netip.PrefixFrom(netip.AddrFrom16([16]byte{3: 3}).Unmap(), 5)},
  238. Peers: []wgcfg.Peer{
  239. {
  240. PublicKey: key.NodePublic{},
  241. },
  242. },
  243. },
  244. &router.Config{
  245. Routes: []netip.Prefix{
  246. netip.MustParsePrefix("1.2.3.0/24"),
  247. netip.MustParsePrefix("1234::/64"),
  248. },
  249. },
  250. map[dnsname.FQDN][]netip.Addr{
  251. dnsname.FQDN("a."): {netip.MustParseAddr("1.2.3.4"), netip.MustParseAddr("4.3.2.1")},
  252. dnsname.FQDN("b."): {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("9.9.9.9")},
  253. dnsname.FQDN("c."): {netip.MustParseAddr("6.6.6.6"), netip.MustParseAddr("7.7.7.7")},
  254. dnsname.FQDN("d."): {netip.MustParseAddr("6.7.6.6"), netip.MustParseAddr("7.7.7.8")},
  255. dnsname.FQDN("e."): {netip.MustParseAddr("6.8.6.6"), netip.MustParseAddr("7.7.7.9")},
  256. dnsname.FQDN("f."): {netip.MustParseAddr("6.9.6.6"), netip.MustParseAddr("7.7.7.0")},
  257. },
  258. map[dnsname.FQDN][]netip.AddrPort{
  259. dnsname.FQDN("a."): {netip.MustParseAddrPort("1.2.3.4:11"), netip.MustParseAddrPort("4.3.2.1:22")},
  260. dnsname.FQDN("b."): {netip.MustParseAddrPort("8.8.8.8:11"), netip.MustParseAddrPort("9.9.9.9:22")},
  261. dnsname.FQDN("c."): {netip.MustParseAddrPort("8.8.8.8:12"), netip.MustParseAddrPort("9.9.9.9:23")},
  262. dnsname.FQDN("d."): {netip.MustParseAddrPort("8.8.8.8:13"), netip.MustParseAddrPort("9.9.9.9:24")},
  263. dnsname.FQDN("e."): {netip.MustParseAddrPort("8.8.8.8:14"), netip.MustParseAddrPort("9.9.9.9:25")},
  264. },
  265. map[key.DiscoPublic]bool{
  266. key.DiscoPublicFromRaw32(mem.B([]byte{1: 1, 31: 0})): true,
  267. key.DiscoPublicFromRaw32(mem.B([]byte{1: 2, 31: 0})): false,
  268. key.DiscoPublicFromRaw32(mem.B([]byte{1: 3, 31: 0})): true,
  269. key.DiscoPublicFromRaw32(mem.B([]byte{1: 4, 31: 0})): false,
  270. },
  271. &tailcfg.MapResponse{
  272. DERPMap: &tailcfg.DERPMap{
  273. Regions: map[int]*tailcfg.DERPRegion{
  274. 1: {
  275. RegionID: 1,
  276. RegionCode: "foo",
  277. Nodes: []*tailcfg.DERPNode{
  278. {
  279. Name: "n1",
  280. RegionID: 1,
  281. HostName: "foo.com",
  282. },
  283. {
  284. Name: "n2",
  285. RegionID: 1,
  286. HostName: "bar.com",
  287. },
  288. },
  289. },
  290. },
  291. },
  292. DNSConfig: &tailcfg.DNSConfig{
  293. Resolvers: []*dnstype.Resolver{
  294. {Addr: "10.0.0.1"},
  295. },
  296. },
  297. PacketFilter: []tailcfg.FilterRule{
  298. {
  299. SrcIPs: []string{"1.2.3.4"},
  300. DstPorts: []tailcfg.NetPortRange{
  301. {
  302. IP: "1.2.3.4/32",
  303. Ports: tailcfg.PortRange{First: 1, Last: 2},
  304. },
  305. },
  306. },
  307. },
  308. Peers: []*tailcfg.Node{
  309. {
  310. ID: 1,
  311. },
  312. {
  313. ID: 2,
  314. },
  315. },
  316. UserProfiles: []tailcfg.UserProfile{
  317. {ID: 1, LoginName: "[email protected]"},
  318. {ID: 2, LoginName: "[email protected]"},
  319. },
  320. },
  321. filter.Match{
  322. IPProto: []ipproto.Proto{1, 2, 3},
  323. },
  324. }
  325. }
  326. type IntThenByte struct {
  327. i int
  328. b byte
  329. }
  330. type TwoInts struct{ a, b int }
  331. type IntIntByteInt struct {
  332. i1, i2 int32
  333. b byte // padding after
  334. i3 int32
  335. }
  336. func u8(n uint8) string { return string([]byte{n}) }
  337. func u16(n uint16) string { return string(binary.LittleEndian.AppendUint16(nil, n)) }
  338. func u32(n uint32) string { return string(binary.LittleEndian.AppendUint32(nil, n)) }
  339. func u64(n uint64) string { return string(binary.LittleEndian.AppendUint64(nil, n)) }
  340. func ux(n uint) string {
  341. if bits.UintSize == 32 {
  342. return u32(uint32(n))
  343. } else {
  344. return u64(uint64(n))
  345. }
  346. }
  347. func TestGetTypeHasher(t *testing.T) {
  348. switch runtime.GOARCH {
  349. case "amd64", "arm64", "arm", "386", "riscv64":
  350. default:
  351. // Test outputs below are specifically for little-endian machines.
  352. // Just skip everything else for now. Feel free to add more above if
  353. // you have the hardware to test and it's little-endian.
  354. t.Skipf("skipping on %v", runtime.GOARCH)
  355. }
  356. type typedString string
  357. var (
  358. someInt = int('A')
  359. someComplex128 = complex128(1 + 2i)
  360. someIP = netip.MustParseAddr("1.2.3.4")
  361. )
  362. tests := []struct {
  363. name string
  364. val any
  365. out string
  366. out32 string // overwrites out if 32-bit
  367. }{
  368. {
  369. name: "int",
  370. val: int(1),
  371. out: ux(1),
  372. },
  373. {
  374. name: "int_negative",
  375. val: int(-1),
  376. out: ux(math.MaxUint),
  377. },
  378. {
  379. name: "int8",
  380. val: int8(1),
  381. out: "\x01",
  382. },
  383. {
  384. name: "float64",
  385. val: float64(1.0),
  386. out: "\x00\x00\x00\x00\x00\x00\xf0?",
  387. },
  388. {
  389. name: "float32",
  390. val: float32(1.0),
  391. out: "\x00\x00\x80?",
  392. },
  393. {
  394. name: "string",
  395. val: "foo",
  396. out: "\x03\x00\x00\x00\x00\x00\x00\x00foo",
  397. },
  398. {
  399. name: "typedString",
  400. val: typedString("foo"),
  401. out: "\x03\x00\x00\x00\x00\x00\x00\x00foo",
  402. },
  403. {
  404. name: "string_slice",
  405. val: []string{"foo", "bar"},
  406. out: "\x01\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00foo\x03\x00\x00\x00\x00\x00\x00\x00bar",
  407. },
  408. {
  409. name: "int_slice",
  410. val: []int{1, 0, -1},
  411. out: "\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff",
  412. out32: "\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff",
  413. },
  414. {
  415. name: "struct",
  416. val: struct {
  417. a, b int
  418. c uint16
  419. }{1, -1, 2},
  420. out: "\x01\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\x02\x00",
  421. out32: "\x01\x00\x00\x00\xff\xff\xff\xff\x02\x00",
  422. },
  423. {
  424. name: "nil_int_ptr",
  425. val: (*int)(nil),
  426. out: "\x00",
  427. },
  428. {
  429. name: "int_ptr",
  430. val: &someInt,
  431. out: "\x01A\x00\x00\x00\x00\x00\x00\x00",
  432. out32: "\x01A\x00\x00\x00",
  433. },
  434. {
  435. name: "nil_uint32_ptr",
  436. val: (*uint32)(nil),
  437. out: "\x00",
  438. },
  439. {
  440. name: "complex128_ptr",
  441. val: &someComplex128,
  442. out: "\x01\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@",
  443. },
  444. {
  445. name: "packet_filter",
  446. val: filterRules,
  447. out: "\x01\x04\x00\x00\x00\x00\x00\x00\x00\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00*\v\x00\x00\x00\x00\x00\x00\x0010.1.3.4/32\v\x00\x00\x00\x00\x00\x00\x0010.0.0.0/24\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\n\x00\x00\x00\x00\x00\x00\x001.2.3.4/32\x01 \x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x01\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04!\x01\x01\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00foo\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00",
  448. out32: "\x01\x04\x00\x00\x00\x00\x00\x00\x00\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00*\v\x00\x00\x00\x00\x00\x00\x0010.1.3.4/32\v\x00\x00\x00\x00\x00\x00\x0010.0.0.0/24\x01\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\n\x00\x00\x00\x00\x00\x00\x001.2.3.4/32\x01 \x00\x00\x00\x01\x00\x02\x00\x01\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04!\x01\x01\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00foo\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00foooooooooo\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\f\x00\x00\x00\x00\x00\x00\x00baaaaaarrrrr\x00\x01\x00\x02\x00\x00\x00",
  449. },
  450. {
  451. name: "netip.Addr",
  452. val: netip.MustParseAddr("fe80::123%foo"),
  453. out: u64(16+3) + u64(0x80fe) + u64(0x2301<<48) + "foo",
  454. },
  455. {
  456. name: "ptr-netip.Addr",
  457. val: &someIP,
  458. out: u8(1) + u64(4) + u32(0x04030201),
  459. },
  460. {
  461. name: "ptr-nil-netip.Addr",
  462. val: (*netip.Addr)(nil),
  463. out: "\x00",
  464. },
  465. {
  466. name: "time",
  467. val: time.Unix(1234, 5678).In(time.UTC),
  468. out: u64(1234) + u32(5678) + u32(0),
  469. },
  470. {
  471. name: "time_ptr", // addressable, as opposed to "time" test above
  472. val: ptr.To(time.Unix(1234, 5678).In(time.UTC)),
  473. out: u8(1) + u64(1234) + u32(5678) + u32(0),
  474. },
  475. {
  476. name: "time_ptr_via_unexported",
  477. val: testtype.NewUnexportedAddressableTime(time.Unix(1234, 5678).In(time.UTC)),
  478. out: u8(1) + u64(1234) + u32(5678) + u32(0),
  479. },
  480. {
  481. name: "time_ptr_via_unexported_value",
  482. val: *testtype.NewUnexportedAddressableTime(time.Unix(1234, 5678).In(time.UTC)),
  483. out: u64(1234) + u32(5678) + u32(0),
  484. },
  485. {
  486. name: "time_custom_zone",
  487. val: time.Unix(1655311822, 0).In(time.FixedZone("FOO", -60*60)),
  488. out: u64(1655311822) + u32(0) + u32(math.MaxUint32-60*60+1),
  489. },
  490. {
  491. name: "time_nil",
  492. val: (*time.Time)(nil),
  493. out: "\x00",
  494. },
  495. {
  496. name: "array_memhash",
  497. val: [4]byte{1, 2, 3, 4},
  498. out: "\x01\x02\x03\x04",
  499. },
  500. {
  501. name: "array_ptr_memhash",
  502. val: ptr.To([4]byte{1, 2, 3, 4}),
  503. out: "\x01\x01\x02\x03\x04",
  504. },
  505. {
  506. name: "ptr_to_struct_partially_memhashable",
  507. val: &struct {
  508. A int16
  509. B int16
  510. C *int
  511. }{5, 6, nil},
  512. out: "\x01\x05\x00\x06\x00\x00",
  513. },
  514. {
  515. name: "struct_partially_memhashable_but_cant_addr",
  516. val: struct {
  517. A int16
  518. B int16
  519. C *int
  520. }{5, 6, nil},
  521. out: "\x05\x00\x06\x00\x00",
  522. },
  523. {
  524. name: "array_elements",
  525. val: [4]byte{1, 2, 3, 4},
  526. out: "\x01\x02\x03\x04",
  527. },
  528. {
  529. name: "bool",
  530. val: true,
  531. out: "\x01",
  532. },
  533. {
  534. name: "IntIntByteInt",
  535. val: IntIntByteInt{1, 2, 3, 4},
  536. out: "\x01\x00\x00\x00\x02\x00\x00\x00\x03\x04\x00\x00\x00",
  537. },
  538. {
  539. name: "IntIntByteInt-canaddr",
  540. val: &IntIntByteInt{1, 2, 3, 4},
  541. out: "\x01\x01\x00\x00\x00\x02\x00\x00\x00\x03\x04\x00\x00\x00",
  542. },
  543. {
  544. name: "array-IntIntByteInt",
  545. val: [2]IntIntByteInt{
  546. {1, 2, 3, 4},
  547. {5, 6, 7, 8},
  548. },
  549. out: "\x01\x00\x00\x00\x02\x00\x00\x00\x03\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\b\x00\x00\x00",
  550. },
  551. {
  552. name: "array-IntIntByteInt-canaddr",
  553. val: &[2]IntIntByteInt{
  554. {1, 2, 3, 4},
  555. {5, 6, 7, 8},
  556. },
  557. out: "\x01\x01\x00\x00\x00\x02\x00\x00\x00\x03\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\b\x00\x00\x00",
  558. },
  559. {
  560. name: "tailcfg.Node",
  561. val: &tailcfg.Node{},
  562. out: "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\tn\x88\xf1\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\tn\x88\xf1\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
  563. out32: "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\tn\x88\xf1\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\tn\x88\xf1\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
  564. },
  565. }
  566. for _, tt := range tests {
  567. t.Run(tt.name, func(t *testing.T) {
  568. if tt.name == "packet_filter" {
  569. // TODO(#8419): Re-enable when we move to Go 1.21.
  570. t.Skip("this has a different output between Go 1.20 and Go 1.21, so skip it for now")
  571. }
  572. rv := reflect.ValueOf(tt.val)
  573. va := reflect.New(rv.Type()).Elem()
  574. va.Set(rv)
  575. fn := lookupTypeHasher(va.Type())
  576. hb := &hashBuffer{Hash: sha256.New()}
  577. h := new(hasher)
  578. h.Block512.Hash = hb
  579. fn(h, pointerOf(va.Addr()))
  580. const ptrSize = 32 << uintptr(^uintptr(0)>>63)
  581. if tt.out32 != "" && ptrSize == 32 {
  582. tt.out = tt.out32
  583. }
  584. h.sum()
  585. if got := string(hb.B); got != tt.out {
  586. t.Fatalf("got %q; want %q", got, tt.out)
  587. }
  588. })
  589. }
  590. }
  591. func TestSliceCycle(t *testing.T) {
  592. type S []S
  593. c := qt.New(t)
  594. a := make(S, 1) // cyclic graph of 1 node
  595. a[0] = a
  596. b := make(S, 1) // cyclic graph of 1 node
  597. b[0] = b
  598. ha := Hash(&a)
  599. hb := Hash(&b)
  600. c.Assert(ha, qt.Equals, hb)
  601. c1 := make(S, 1) // cyclic graph of 2 nodes
  602. c2 := make(S, 1) // cyclic graph of 2 nodes
  603. c1[0] = c2
  604. c2[0] = c1
  605. hc1 := Hash(&c1)
  606. hc2 := Hash(&c2)
  607. c.Assert(hc1, qt.Equals, hc2)
  608. c.Assert(ha, qt.Not(qt.Equals), hc1)
  609. c.Assert(hb, qt.Not(qt.Equals), hc2)
  610. c3 := make(S, 1) // graph of 1 node pointing to cyclic graph of 2 nodes
  611. c3[0] = c1
  612. hc3 := Hash(&c3)
  613. c.Assert(hc1, qt.Not(qt.Equals), hc3)
  614. c4 := make(S, 2) // cyclic graph of 3 nodes
  615. c5 := make(S, 2) // cyclic graph of 3 nodes
  616. c4[0] = nil
  617. c4[1] = c4
  618. c5[0] = c5
  619. c5[1] = nil
  620. hc4 := Hash(&c4)
  621. hc5 := Hash(&c5)
  622. c.Assert(hc4, qt.Not(qt.Equals), hc5) // cycle occurs through different indexes
  623. }
  624. func TestMapCycle(t *testing.T) {
  625. type M map[string]M
  626. c := qt.New(t)
  627. a := make(M) // cyclic graph of 1 node
  628. a["self"] = a
  629. b := make(M) // cyclic graph of 1 node
  630. b["self"] = b
  631. ha := Hash(&a)
  632. hb := Hash(&b)
  633. c.Assert(ha, qt.Equals, hb)
  634. c1 := make(M) // cyclic graph of 2 nodes
  635. c2 := make(M) // cyclic graph of 2 nodes
  636. c1["peer"] = c2
  637. c2["peer"] = c1
  638. hc1 := Hash(&c1)
  639. hc2 := Hash(&c2)
  640. c.Assert(hc1, qt.Equals, hc2)
  641. c.Assert(ha, qt.Not(qt.Equals), hc1)
  642. c.Assert(hb, qt.Not(qt.Equals), hc2)
  643. c3 := make(M) // graph of 1 node pointing to cyclic graph of 2 nodes
  644. c3["child"] = c1
  645. hc3 := Hash(&c3)
  646. c.Assert(hc1, qt.Not(qt.Equals), hc3)
  647. c4 := make(M) // cyclic graph of 3 nodes
  648. c5 := make(M) // cyclic graph of 3 nodes
  649. c4["0"] = nil
  650. c4["1"] = c4
  651. c5["0"] = c5
  652. c5["1"] = nil
  653. hc4 := Hash(&c4)
  654. hc5 := Hash(&c5)
  655. c.Assert(hc4, qt.Not(qt.Equals), hc5) // cycle occurs through different keys
  656. }
  657. func TestPointerCycle(t *testing.T) {
  658. type P *P
  659. c := qt.New(t)
  660. a := new(P) // cyclic graph of 1 node
  661. *a = a
  662. b := new(P) // cyclic graph of 1 node
  663. *b = b
  664. ha := Hash(&a)
  665. hb := Hash(&b)
  666. c.Assert(ha, qt.Equals, hb)
  667. c1 := new(P) // cyclic graph of 2 nodes
  668. c2 := new(P) // cyclic graph of 2 nodes
  669. *c1 = c2
  670. *c2 = c1
  671. hc1 := Hash(&c1)
  672. hc2 := Hash(&c2)
  673. c.Assert(hc1, qt.Equals, hc2)
  674. c.Assert(ha, qt.Not(qt.Equals), hc1)
  675. c.Assert(hb, qt.Not(qt.Equals), hc2)
  676. c3 := new(P) // graph of 1 node pointing to cyclic graph of 2 nodes
  677. *c3 = c1
  678. hc3 := Hash(&c3)
  679. c.Assert(hc1, qt.Not(qt.Equals), hc3)
  680. }
  681. func TestInterfaceCycle(t *testing.T) {
  682. type I struct{ v any }
  683. c := qt.New(t)
  684. a := new(I) // cyclic graph of 1 node
  685. a.v = a
  686. b := new(I) // cyclic graph of 1 node
  687. b.v = b
  688. ha := Hash(&a)
  689. hb := Hash(&b)
  690. c.Assert(ha, qt.Equals, hb)
  691. c1 := new(I) // cyclic graph of 2 nodes
  692. c2 := new(I) // cyclic graph of 2 nodes
  693. c1.v = c2
  694. c2.v = c1
  695. hc1 := Hash(&c1)
  696. hc2 := Hash(&c2)
  697. c.Assert(hc1, qt.Equals, hc2)
  698. c.Assert(ha, qt.Not(qt.Equals), hc1)
  699. c.Assert(hb, qt.Not(qt.Equals), hc2)
  700. c3 := new(I) // graph of 1 node pointing to cyclic graph of 2 nodes
  701. c3.v = c1
  702. hc3 := Hash(&c3)
  703. c.Assert(hc1, qt.Not(qt.Equals), hc3)
  704. }
  705. var sink Sum
  706. func BenchmarkHash(b *testing.B) {
  707. b.ReportAllocs()
  708. v := getVal()
  709. for i := 0; i < b.N; i++ {
  710. sink = Hash(v)
  711. }
  712. }
  713. // filterRules is a packet filter that has both everything populated (in its
  714. // first element) and also a few entries that are the typical shape for regular
  715. // packet filters as sent to clients.
  716. var filterRules = []tailcfg.FilterRule{
  717. {
  718. SrcIPs: []string{"*", "10.1.3.4/32", "10.0.0.0/24"},
  719. SrcBits: []int{1, 2, 3},
  720. DstPorts: []tailcfg.NetPortRange{{
  721. IP: "1.2.3.4/32",
  722. Bits: ptr.To(32),
  723. Ports: tailcfg.PortRange{First: 1, Last: 2},
  724. }},
  725. IPProto: []int{1, 2, 3, 4},
  726. CapGrant: []tailcfg.CapGrant{{
  727. Dsts: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/32")},
  728. Caps: []string{"foo"},
  729. }},
  730. },
  731. {
  732. SrcIPs: []string{"foooooooooo"},
  733. DstPorts: []tailcfg.NetPortRange{{
  734. IP: "baaaaaarrrrr",
  735. Ports: tailcfg.PortRange{First: 1, Last: 2},
  736. }},
  737. },
  738. {
  739. SrcIPs: []string{"foooooooooo"},
  740. DstPorts: []tailcfg.NetPortRange{{
  741. IP: "baaaaaarrrrr",
  742. Ports: tailcfg.PortRange{First: 1, Last: 2},
  743. }},
  744. },
  745. {
  746. SrcIPs: []string{"foooooooooo"},
  747. DstPorts: []tailcfg.NetPortRange{{
  748. IP: "baaaaaarrrrr",
  749. Ports: tailcfg.PortRange{First: 1, Last: 2},
  750. }},
  751. },
  752. }
  753. func BenchmarkHashPacketFilter(b *testing.B) {
  754. b.ReportAllocs()
  755. for i := 0; i < b.N; i++ {
  756. sink = Hash(&filterRules)
  757. }
  758. }
  759. func TestHashMapAcyclic(t *testing.T) {
  760. m := map[int]string{}
  761. for i := 0; i < 100; i++ {
  762. m[i] = fmt.Sprint(i)
  763. }
  764. got := map[string]bool{}
  765. hb := &hashBuffer{Hash: sha256.New()}
  766. hash := lookupTypeHasher(reflect.TypeOf(m))
  767. for i := 0; i < 20; i++ {
  768. va := reflect.ValueOf(&m).Elem()
  769. hb.Reset()
  770. h := new(hasher)
  771. h.Block512.Hash = hb
  772. hash(h, pointerOf(va.Addr()))
  773. h.sum()
  774. if got[string(hb.B)] {
  775. continue
  776. }
  777. got[string(hb.B)] = true
  778. }
  779. if len(got) != 1 {
  780. t.Errorf("got %d results; want 1", len(got))
  781. }
  782. }
  783. func TestPrintArray(t *testing.T) {
  784. type T struct {
  785. X [32]byte
  786. }
  787. x := T{X: [32]byte{1: 1, 31: 31}}
  788. hb := &hashBuffer{Hash: sha256.New()}
  789. h := new(hasher)
  790. h.Block512.Hash = hb
  791. va := reflect.ValueOf(&x).Elem()
  792. hash := lookupTypeHasher(va.Type())
  793. hash(h, pointerOf(va.Addr()))
  794. h.sum()
  795. const want = "\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f"
  796. if got := hb.B; string(got) != want {
  797. t.Errorf("wrong:\n got: %q\nwant: %q\n", got, want)
  798. }
  799. }
  800. func BenchmarkHashMapAcyclic(b *testing.B) {
  801. b.ReportAllocs()
  802. m := map[int]string{}
  803. for i := 0; i < 100; i++ {
  804. m[i] = fmt.Sprint(i)
  805. }
  806. hb := &hashBuffer{Hash: sha256.New()}
  807. va := reflect.ValueOf(&m).Elem()
  808. hash := lookupTypeHasher(va.Type())
  809. h := new(hasher)
  810. h.Block512.Hash = hb
  811. for i := 0; i < b.N; i++ {
  812. h.Reset()
  813. hash(h, pointerOf(va.Addr()))
  814. }
  815. }
  816. func BenchmarkTailcfgNode(b *testing.B) {
  817. b.ReportAllocs()
  818. node := new(tailcfg.Node)
  819. for i := 0; i < b.N; i++ {
  820. sink = Hash(node)
  821. }
  822. }
  823. func TestExhaustive(t *testing.T) {
  824. seen := make(map[Sum]bool)
  825. for i := 0; i < 100000; i++ {
  826. s := Hash(&i)
  827. if seen[s] {
  828. t.Fatalf("hash collision %v", i)
  829. }
  830. seen[s] = true
  831. }
  832. }
  833. // verify this doesn't loop forever, as it used to (Issue 2340)
  834. func TestMapCyclicFallback(t *testing.T) {
  835. type T struct {
  836. M map[string]any
  837. }
  838. v := &T{
  839. M: map[string]any{},
  840. }
  841. v.M["m"] = v.M
  842. Hash(v)
  843. }
  844. func TestArrayAllocs(t *testing.T) {
  845. if version.IsRace() {
  846. t.Skip("skipping test under race detector")
  847. }
  848. // In theory, there should be no allocations. However, escape analysis on
  849. // certain architectures fails to detect that certain cases do not escape.
  850. // This discrepancy currently affects sha256.digest.Sum.
  851. // Measure the number of allocations in sha256 to ensure that Hash does
  852. // not allocate on top of its usage of sha256.
  853. // See https://golang.org/issue/48055.
  854. var b []byte
  855. h := sha256.New()
  856. want := int(testing.AllocsPerRun(1000, func() {
  857. b = h.Sum(b[:0])
  858. }))
  859. switch runtime.GOARCH {
  860. case "amd64", "arm64":
  861. want = 0 // ensure no allocations on popular architectures
  862. }
  863. type T struct {
  864. X [32]byte
  865. }
  866. x := &T{X: [32]byte{1: 1, 2: 2, 3: 3, 4: 4}}
  867. got := int(testing.AllocsPerRun(1000, func() {
  868. sink = Hash(x)
  869. }))
  870. if got > want {
  871. t.Errorf("allocs = %v; want %v", got, want)
  872. }
  873. }
  874. // Test for http://go/corp/6311 issue.
  875. func TestHashThroughView(t *testing.T) {
  876. type sshPolicyOut struct {
  877. Rules []tailcfg.SSHRuleView
  878. }
  879. type mapResponseOut struct {
  880. SSHPolicy *sshPolicyOut
  881. }
  882. // Just test we don't panic:
  883. _ = Hash(&mapResponseOut{
  884. SSHPolicy: &sshPolicyOut{
  885. Rules: []tailcfg.SSHRuleView{
  886. (&tailcfg.SSHRule{
  887. RuleExpires: ptr.To(time.Unix(123, 0)),
  888. }).View(),
  889. },
  890. },
  891. })
  892. }
  893. func BenchmarkHashArray(b *testing.B) {
  894. b.ReportAllocs()
  895. type T struct {
  896. X [32]byte
  897. }
  898. x := &T{X: [32]byte{1: 1, 2: 2, 3: 3, 4: 4}}
  899. for i := 0; i < b.N; i++ {
  900. sink = Hash(x)
  901. }
  902. }
  903. // hashBuffer is a hash.Hash that buffers all written data.
  904. type hashBuffer struct {
  905. hash.Hash
  906. B []byte
  907. }
  908. func (h *hashBuffer) Write(b []byte) (int, error) {
  909. n, err := h.Hash.Write(b)
  910. h.B = append(h.B, b[:n]...)
  911. return n, err
  912. }
  913. func (h *hashBuffer) Reset() {
  914. h.Hash.Reset()
  915. h.B = h.B[:0]
  916. }
  917. func FuzzTime(f *testing.F) {
  918. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(0), false, "", 0)
  919. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(0), true, "", 0)
  920. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(0), true, "hello", 0)
  921. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(0), true, "", 1234)
  922. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(0), true, "hello", 1234)
  923. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(1), false, "", 0)
  924. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(1), true, "", 0)
  925. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(1), true, "hello", 0)
  926. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(1), true, "", 1234)
  927. f.Add(int64(0), int64(0), false, "", 0, int64(0), int64(1), true, "hello", 1234)
  928. f.Add(int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0, int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0)
  929. f.Add(int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0, int64(math.MaxInt64), int64(math.MaxInt64), true, "", 0)
  930. f.Add(int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0, int64(math.MaxInt64), int64(math.MaxInt64), true, "hello", 0)
  931. f.Add(int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0, int64(math.MaxInt64), int64(math.MaxInt64), true, "", 1234)
  932. f.Add(int64(math.MaxInt64), int64(math.MaxInt64), false, "", 0, int64(math.MaxInt64), int64(math.MaxInt64), true, "hello", 1234)
  933. f.Add(int64(math.MinInt64), int64(math.MinInt64), false, "", 0, int64(math.MinInt64), int64(math.MinInt64), false, "", 0)
  934. f.Add(int64(math.MinInt64), int64(math.MinInt64), false, "", 0, int64(math.MinInt64), int64(math.MinInt64), true, "", 0)
  935. f.Add(int64(math.MinInt64), int64(math.MinInt64), false, "", 0, int64(math.MinInt64), int64(math.MinInt64), true, "hello", 0)
  936. f.Add(int64(math.MinInt64), int64(math.MinInt64), false, "", 0, int64(math.MinInt64), int64(math.MinInt64), true, "", 1234)
  937. f.Add(int64(math.MinInt64), int64(math.MinInt64), false, "", 0, int64(math.MinInt64), int64(math.MinInt64), true, "hello", 1234)
  938. f.Fuzz(func(t *testing.T,
  939. s1, ns1 int64, loc1 bool, name1 string, off1 int,
  940. s2, ns2 int64, loc2 bool, name2 string, off2 int,
  941. ) {
  942. t1 := time.Unix(s1, ns1)
  943. if loc1 {
  944. _ = t1.In(time.FixedZone(name1, off1))
  945. }
  946. t2 := time.Unix(s2, ns2)
  947. if loc2 {
  948. _ = t2.In(time.FixedZone(name2, off2))
  949. }
  950. got := Hash(&t1) == Hash(&t2)
  951. want := t1.Format(time.RFC3339Nano) == t2.Format(time.RFC3339Nano)
  952. if got != want {
  953. t.Errorf("time.Time(%s) == time.Time(%s) mismatches hash equivalent", t1.Format(time.RFC3339Nano), t2.Format(time.RFC3339Nano))
  954. }
  955. })
  956. }
  957. func FuzzAddr(f *testing.F) {
  958. f.Fuzz(func(t *testing.T,
  959. u1a, u1b uint64, zone1 string,
  960. u2a, u2b uint64, zone2 string,
  961. ) {
  962. var b1, b2 [16]byte
  963. binary.LittleEndian.PutUint64(b1[:8], u1a)
  964. binary.LittleEndian.PutUint64(b1[8:], u1b)
  965. binary.LittleEndian.PutUint64(b2[:8], u2a)
  966. binary.LittleEndian.PutUint64(b2[8:], u2b)
  967. var ips [4]netip.Addr
  968. ips[0] = netip.AddrFrom4(*(*[4]byte)(b1[:]))
  969. ips[1] = netip.AddrFrom4(*(*[4]byte)(b2[:]))
  970. ips[2] = netip.AddrFrom16(b1)
  971. if zone1 != "" {
  972. ips[2] = ips[2].WithZone(zone1)
  973. }
  974. ips[3] = netip.AddrFrom16(b2)
  975. if zone2 != "" {
  976. ips[3] = ips[2].WithZone(zone2)
  977. }
  978. for _, ip1 := range ips[:] {
  979. for _, ip2 := range ips[:] {
  980. got := Hash(&ip1) == Hash(&ip2)
  981. want := ip1 == ip2
  982. if got != want {
  983. t.Errorf("netip.Addr(%s) == netip.Addr(%s) mismatches hash equivalent", ip1.String(), ip2.String())
  984. }
  985. }
  986. }
  987. })
  988. }
  989. func TestAppendTo(t *testing.T) {
  990. v := getVal()
  991. h := Hash(v)
  992. sum := h.AppendTo(nil)
  993. if s := h.String(); s != string(sum) {
  994. t.Errorf("hash sum mismatch; h.String()=%q h.AppendTo()=%q", s, string(sum))
  995. }
  996. }
  997. func BenchmarkAppendTo(b *testing.B) {
  998. b.ReportAllocs()
  999. v := getVal()
  1000. h := Hash(v)
  1001. hashBuf := make([]byte, 0, 100)
  1002. b.ResetTimer()
  1003. for i := 0; i < b.N; i++ {
  1004. hashBuf = h.AppendTo(hashBuf[:0])
  1005. }
  1006. }