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