bench_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package brontide
  2. import (
  3. "bytes"
  4. "math"
  5. "math/rand"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func BenchmarkReadHeaderAndBody(t *testing.B) {
  11. // Create a test connection, grabbing either side of the connection
  12. // into local variables. If the initial crypto handshake fails, then
  13. // we'll get a non-nil error here.
  14. localConn, remoteConn, err := establishTestConnection(t)
  15. require.NoError(t, err, "unable to establish test connection: %v", err)
  16. rand.Seed(time.Now().Unix())
  17. noiseRemoteConn := remoteConn.(*Conn)
  18. noiseLocalConn := localConn.(*Conn)
  19. // Now that we have a local and remote side (to set up the initial
  20. // handshake state, we'll have the remote side write out something
  21. // similar to a large message in the protocol.
  22. const pktSize = 60_000
  23. msg := bytes.Repeat([]byte("a"), pktSize)
  24. err = noiseRemoteConn.WriteMessage(msg)
  25. require.NoError(t, err, "unable to write encrypted message: %v", err)
  26. cipherHeader := noiseRemoteConn.noise.nextHeaderSend
  27. cipherMsg := noiseRemoteConn.noise.nextBodySend
  28. var (
  29. benchErr error
  30. msgBuf [math.MaxUint16]byte
  31. )
  32. t.ReportAllocs()
  33. t.ResetTimer()
  34. nonceValue := noiseLocalConn.noise.recvCipher.nonce
  35. for i := 0; i < t.N; i++ {
  36. pktLen, benchErr := noiseLocalConn.noise.ReadHeader(
  37. bytes.NewReader(cipherHeader),
  38. )
  39. require.NoError(
  40. t, benchErr, "#%v: failed decryption: %v", i, benchErr,
  41. )
  42. _, benchErr = noiseLocalConn.noise.ReadBody(
  43. bytes.NewReader(cipherMsg), msgBuf[:pktLen],
  44. )
  45. require.NoError(
  46. t, benchErr, "#%v: failed decryption: %v", i, benchErr,
  47. )
  48. // We reset the internal nonce each time as otherwise, we'd
  49. // continue to increment it which would cause a decryption
  50. // failure.
  51. noiseLocalConn.noise.recvCipher.nonce = nonceValue
  52. }
  53. require.NoError(t, benchErr)
  54. }