]> Sergey Matveev's repositories - btrtrc.git/commitdiff
mse: Optimize allocations receiving handshakes
authorMatt Joiner <anacrolix@gmail.com>
Mon, 4 Jan 2021 00:34:04 +0000 (11:34 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Mon, 4 Jan 2021 00:34:04 +0000 (11:34 +1100)
mse/mse.go

index 85d55a7d0a50e5f35d7635c0536e47f97a3b18ae..d4a0368e11c9bc718844fc214447f2a7b3e49b29 100644 (file)
@@ -19,7 +19,6 @@ import (
        "sync"
 
        "github.com/anacrolix/missinggo/perf"
-       "github.com/bradfitz/iter"
 )
 
 const (
@@ -286,18 +285,22 @@ func (h *handshake) postWrite(b []byte) error {
        return nil
 }
 
-func xor(dst, src []byte) (ret []byte) {
-       max := len(dst)
-       if max > len(src) {
-               max = len(src)
-       }
-       ret = make([]byte, 0, max)
-       for i := range iter.N(max) {
-               ret = append(ret, dst[i]^src[i])
+func xor(a, b []byte) (ret []byte) {
+       max := len(a)
+       if max > len(b) {
+               max = len(b)
        }
+       ret = make([]byte, max)
+       xorInPlace(ret, a, b)
        return
 }
 
+func xorInPlace(dst, a, b []byte) {
+       for i := range dst {
+               dst[i] = a[i] ^ b[i]
+       }
+}
+
 func marshal(w io.Writer, data ...interface{}) (err error) {
        for _, data := range data {
                err = binary.Write(w, binary.BigEndian, data)
@@ -438,9 +441,17 @@ func (h *handshake) receiverSteps() (ret io.ReadWriter, chosen CryptoMethod, err
        if err != nil {
                return
        }
+       expectedHash := hash(req3, h.s[:])
+       eachHash := sha1.New()
+       var sum, xored [sha1.Size]byte
        err = ErrNoSecretKeyMatch
        h.skeys(func(skey []byte) bool {
-               if bytes.Equal(xor(hash(req2, skey), hash(req3, h.s[:])), b[:]) {
+               eachHash.Reset()
+               eachHash.Write(req2)
+               eachHash.Write(skey)
+               eachHash.Sum(sum[:0])
+               xorInPlace(xored[:], sum[:], expectedHash)
+               if bytes.Equal(xored[:], b[:]) {
                        h.skey = skey
                        err = nil
                        return false