disco_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package key
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "testing"
  8. )
  9. func TestDiscoKey(t *testing.T) {
  10. k := NewDisco()
  11. if k.IsZero() {
  12. t.Fatal("DiscoPrivate should not be zero")
  13. }
  14. p := k.Public()
  15. if p.IsZero() {
  16. t.Fatal("DiscoPublic should not be zero")
  17. }
  18. bs, err := p.MarshalText()
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. if !bytes.HasPrefix(bs, []byte("discokey:")) {
  23. t.Fatalf("serialization of public discokey %s has wrong prefix", p)
  24. }
  25. z := DiscoPublic{}
  26. if !z.IsZero() {
  27. t.Fatal("IsZero(DiscoPublic{}) is false")
  28. }
  29. if s := z.ShortString(); s != "" {
  30. t.Fatalf("DiscoPublic{}.ShortString() is %q, want \"\"", s)
  31. }
  32. }
  33. func TestDiscoSerialization(t *testing.T) {
  34. serialized := `{
  35. "Pub":"discokey:50d20b455ecf12bc453f83c2cfdb2a24925d06cf2598dcaa54e91af82ce9f765"
  36. }`
  37. pub := DiscoPublic{
  38. k: [32]uint8{
  39. 0x50, 0xd2, 0xb, 0x45, 0x5e, 0xcf, 0x12, 0xbc, 0x45, 0x3f, 0x83,
  40. 0xc2, 0xcf, 0xdb, 0x2a, 0x24, 0x92, 0x5d, 0x6, 0xcf, 0x25, 0x98,
  41. 0xdc, 0xaa, 0x54, 0xe9, 0x1a, 0xf8, 0x2c, 0xe9, 0xf7, 0x65,
  42. },
  43. }
  44. type key struct {
  45. Pub DiscoPublic
  46. }
  47. var a key
  48. if err := json.Unmarshal([]byte(serialized), &a); err != nil {
  49. t.Fatal(err)
  50. }
  51. if a.Pub != pub {
  52. t.Errorf("wrong deserialization of public key, got %#v want %#v", a.Pub, pub)
  53. }
  54. bs, err := json.MarshalIndent(a, "", " ")
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. var b bytes.Buffer
  59. json.Indent(&b, []byte(serialized), "", " ")
  60. if got, want := string(bs), b.String(); got != want {
  61. t.Error("json serialization doesn't roundtrip")
  62. }
  63. }
  64. func TestDiscoShared(t *testing.T) {
  65. k1, k2 := NewDisco(), NewDisco()
  66. s1, s2 := k1.Shared(k2.Public()), k2.Shared(k1.Public())
  67. if !s1.Equal(s2) {
  68. t.Error("k1.Shared(k2) != k2.Shared(k1)")
  69. }
  70. }
  71. func TestSortedPairOfDiscoPublic(t *testing.T) {
  72. pubA := DiscoPublic{}
  73. pubA.k[0] = 0x01
  74. pubB := DiscoPublic{}
  75. pubB.k[0] = 0x02
  76. sortedInput := NewSortedPairOfDiscoPublic(pubA, pubB)
  77. unsortedInput := NewSortedPairOfDiscoPublic(pubB, pubA)
  78. if sortedInput.Get() != unsortedInput.Get() {
  79. t.Fatal("sortedInput.Get() != unsortedInput.Get()")
  80. }
  81. if unsortedInput.Get()[0] != pubA {
  82. t.Fatal("unsortedInput.Get()[0] != pubA")
  83. }
  84. if unsortedInput.Get()[1] != pubB {
  85. t.Fatal("unsortedInput.Get()[1] != pubB")
  86. }
  87. }