Repository: libp2p/go-libp2p
Pull request #1462 (2022-04-26 17:59:43)

move go-libp2p-noise here
Part of #1187.


Patch:
diff --git a/defaults.go b/defaults.go
index 7def06f5..759955a9 100644
--- a/defaults.go
+++ b/defaults.go
@@ -7,13 +7,13 @@ import (
 
 	"github.com/libp2p/go-libp2p/p2p/muxer/yamux"
 	"github.com/libp2p/go-libp2p/p2p/net/connmgr"
+	"github.com/libp2p/go-libp2p/p2p/security/noise"
 	quic "github.com/libp2p/go-libp2p/p2p/transport/quic"
 	"github.com/libp2p/go-libp2p/p2p/transport/tcp"
 	ws "github.com/libp2p/go-libp2p/p2p/transport/websocket"
 
 	"github.com/libp2p/go-libp2p-core/crypto"
 
-	noise "github.com/libp2p/go-libp2p-noise"
 	"github.com/libp2p/go-libp2p-peerstore/pstoremem"
 	rcmgr "github.com/libp2p/go-libp2p-resource-manager"
 	tls "github.com/libp2p/go-libp2p-tls"
diff --git a/go.mod b/go.mod
index 52444149..364e1c4a 100644
--- a/go.mod
+++ b/go.mod
@@ -4,6 +4,7 @@ go 1.17
 
 require (
 	github.com/benbjohnson/clock v1.3.0
+	github.com/flynn/noise v1.0.0
 	github.com/gogo/protobuf v1.3.2
 	github.com/golang/mock v1.6.0
 	github.com/google/gopacket v1.1.19
@@ -20,7 +21,6 @@ require (
 	github.com/libp2p/go-libp2p-circuit v0.6.0
 	github.com/libp2p/go-libp2p-core v0.15.1
 	github.com/libp2p/go-libp2p-nat v0.1.0
-	github.com/libp2p/go-libp2p-noise v0.4.0
 	github.com/libp2p/go-libp2p-peerstore v0.6.0
 	github.com/libp2p/go-libp2p-resource-manager v0.2.1
 	github.com/libp2p/go-libp2p-testing v0.9.2
@@ -65,7 +65,6 @@ require (
 	github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect
 	github.com/docker/go-units v0.4.0 // indirect
 	github.com/elastic/gosigar v0.14.2 // indirect
-	github.com/flynn/noise v1.0.0 // indirect
 	github.com/francoispqt/gojay v1.2.13 // indirect
 	github.com/fsnotify/fsnotify v1.5.1 // indirect
 	github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
diff --git a/go.sum b/go.sum
index 3de3c758..41128c35 100644
--- a/go.sum
+++ b/go.sum
@@ -76,12 +76,10 @@ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kB
 github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
 github.com/btcsuite/btcd v0.0.0-20190523000118-16327141da8c/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
 github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
-github.com/btcsuite/btcd v0.21.0-beta/go.mod h1:ZSWyehm27aAuS9bvkATT+Xte3hjHZ+MRgMY/8NJ7K94=
 github.com/btcsuite/btcd v0.22.0-beta h1:LTDpDKUM5EeOFBPM8IXpinEcmZ6FWfNZbE3lfrfdnWo=
 github.com/btcsuite/btcd v0.22.0-beta/go.mod h1:9n5ntfhhHQBIhUvlhDvD3Qg6fRUj4jkN0VB8L8svzOA=
 github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
 github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
-github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts=
 github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce/go.mod h1:0DVlHczLPewLcPGEIeUEzfOJhqGPQ0mJJRDBtD307+o=
 github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
 github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
@@ -447,8 +445,6 @@ github.com/libp2p/go-libp2p-mplex v0.5.0 h1:vt3k4E4HSND9XH4Z8rUpacPJFSAgLOv6HDvG
 github.com/libp2p/go-libp2p-mplex v0.5.0/go.mod h1:eLImPJLkj3iG5t5lq68w3Vm5NAQ5BcKwrrb2VmOYb3M=
 github.com/libp2p/go-libp2p-nat v0.1.0 h1:vigUi2MEN+fwghe5ijpScxtbbDz+L/6y8XwlzYOJgSY=
 github.com/libp2p/go-libp2p-nat v0.1.0/go.mod h1:DQzAG+QbDYjN1/C3B6vXucLtz3u9rEonLVPtZVzQqks=
-github.com/libp2p/go-libp2p-noise v0.4.0 h1:khcMsGhHNdGqKE5LDLrnHwZvdGVMsrnD4GTkTWkwmLU=
-github.com/libp2p/go-libp2p-noise v0.4.0/go.mod h1:BzzY5pyzCYSyJbQy9oD8z5oP2idsafjt4/X42h9DjZU=
 github.com/libp2p/go-libp2p-peerstore v0.4.0/go.mod h1:rDJUFyzEWPpXpEwywkcTYYzDHlwza8riYMaUzaN6hX0=
 github.com/libp2p/go-libp2p-peerstore v0.6.0 h1:HJminhQSGISBIRb93N6WK3t6Fa8OOTnHd/VBjL4mY5A=
 github.com/libp2p/go-libp2p-peerstore v0.6.0/go.mod h1:DGEmKdXrcYpK9Jha3sS7MhqYdInxJy84bIPtSu65bKc=
diff --git a/p2p/security/noise/LICENSE.md b/p2p/security/noise/LICENSE.md
new file mode 100644
index 00000000..15601cba
--- /dev/null
+++ b/p2p/security/noise/LICENSE.md
@@ -0,0 +1,229 @@
+The contents of this repository are Copyright (c) corresponding authors and
+contributors, licensed under the `Permissive License Stack` meaning either of:
+
+- Apache-2.0 Software License: https://www.apache.org/licenses/LICENSE-2.0
+  ([...4tr2kfsq](https://gateway.ipfs.io/ipfs/bafkreiankqxazcae4onkp436wag2lj3ccso4nawxqkkfckd6cg4tr2kfsq))
+
+- MIT Software License: https://opensource.org/licenses/MIT
+  ([...vljevcba](https://gateway.ipfs.io/ipfs/bafkreiepofszg4gfe2gzuhojmksgemsub2h4uy2gewdnr35kswvljevcba))
+
+You may not use the contents of this repository except in compliance
+with one of the listed Licenses. For an extended clarification of the
+intent behind the choice of Licensing please refer to
+https://protocol.ai/blog/announcing-the-permissive-license-stack/
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the terms listed in this notice is distributed on
+an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+either express or implied. See each License for the specific language
+governing permissions and limitations under that License.
+
+<!--- SPDX-License-Identifier: Apache-2.0 OR MIT -->
+`SPDX-License-Identifier: Apache-2.0 OR MIT`
+
+Verbatim copies of both licenses are included below:
+
+<details><summary>Apache-2.0 Software License</summary>
+
+```
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+```
+</details>
+
+<details><summary>MIT Software License</summary>
+
+```
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+```
+</details>
diff --git a/p2p/security/noise/crypto.go b/p2p/security/noise/crypto.go
new file mode 100644
index 00000000..2b1c5afe
--- /dev/null
+++ b/p2p/security/noise/crypto.go
@@ -0,0 +1,46 @@
+package noise
+
+import (
+	"errors"
+)
+
+// encrypt calls the cipher's encryption. It encrypts the provided plaintext,
+// slice-appending the ciphertext on out.
+//
+// Usually you want to pass a 0-len slice to this method, with enough capacity
+// to accommodate the ciphertext in order to spare allocs.
+//
+// encrypt returns a new slice header, whose len is the length of the resulting
+// ciphertext, including the authentication tag.
+//
+// This method will not allocate if the supplied slice is large enough to
+// accommodate the encrypted data + authentication tag. If so, the returned
+// slice header should be a view of the original slice.
+//
+// With the poly1305 MAC function that noise-libp2p uses, the authentication tag
+// adds an overhead of 16 bytes.
+func (s *secureSession) encrypt(out, plaintext []byte) ([]byte, error) {
+	if s.enc == nil {
+		return nil, errors.New("cannot encrypt, handshake incomplete")
+	}
+	return s.enc.Encrypt(out, nil, plaintext)
+}
+
+// decrypt calls the cipher's decryption. It decrypts the provided ciphertext,
+// slice-appending the plaintext on out.
+//
+// Usually you want to pass a 0-len slice to this method, with enough capacity
+// to accommodate the plaintext in order to spare allocs.
+//
+// decrypt returns a new slice header, whose len is the length of the resulting
+// plaintext, without the authentication tag.
+//
+// This method will not allocate if the supplied slice is large enough to
+// accommodate the plaintext. If so, the returned slice header should be a view
+// of the original slice.
+func (s *secureSession) decrypt(out, ciphertext []byte) ([]byte, error) {
+	if s.dec == nil {
+		return nil, errors.New("cannot decrypt, handshake incomplete")
+	}
+	return s.dec.Decrypt(out, nil, ciphertext)
+}
diff --git a/p2p/security/noise/handshake.go b/p2p/security/noise/handshake.go
new file mode 100644
index 00000000..59d1eebe
--- /dev/null
+++ b/p2p/security/noise/handshake.go
@@ -0,0 +1,276 @@
+package noise
+
+import (
+	"context"
+	"crypto/rand"
+	"encoding/binary"
+	"fmt"
+	"os"
+	"runtime/debug"
+	"time"
+
+	"golang.org/x/crypto/chacha20poly1305"
+
+	"github.com/libp2p/go-libp2p/p2p/security/noise/pb"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+	"github.com/libp2p/go-libp2p-core/peer"
+
+	"github.com/flynn/noise"
+	"github.com/gogo/protobuf/proto"
+	pool "github.com/libp2p/go-buffer-pool"
+)
+
+// payloadSigPrefix is prepended to our Noise static key before signing with
+// our libp2p identity key.
+const payloadSigPrefix = "noise-libp2p-static-key:"
+
+// All noise session share a fixed cipher suite
+var cipherSuite = noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
+
+// runHandshake exchanges handshake messages with the remote peer to establish
+// a noise-libp2p session. It blocks until the handshake completes or fails.
+func (s *secureSession) runHandshake(ctx context.Context) (err error) {
+	defer func() {
+		if rerr := recover(); rerr != nil {
+			fmt.Fprintf(os.Stderr, "caught panic: %s\n%s\n", rerr, debug.Stack())
+			err = fmt.Errorf("panic in Noise handshake: %s", rerr)
+		}
+	}()
+
+	kp, err := noise.DH25519.GenerateKeypair(rand.Reader)
+	if err != nil {
+		return fmt.Errorf("error generating static keypair: %w", err)
+	}
+
+	cfg := noise.Config{
+		CipherSuite:   cipherSuite,
+		Pattern:       noise.HandshakeXX,
+		Initiator:     s.initiator,
+		StaticKeypair: kp,
+	}
+
+	hs, err := noise.NewHandshakeState(cfg)
+	if err != nil {
+		return fmt.Errorf("error initializing handshake state: %w", err)
+	}
+
+	payload, err := s.generateHandshakePayload(kp)
+	if err != nil {
+		return err
+	}
+
+	// set a deadline to complete the handshake, if one has been supplied.
+	// clear it after we're done.
+	if deadline, ok := ctx.Deadline(); ok {
+		if err := s.SetDeadline(deadline); err == nil {
+			// schedule the deadline removal once we're done handshaking.
+			defer s.SetDeadline(time.Time{})
+		}
+	}
+
+	// We can re-use this buffer for all handshake messages as its size
+	// will be the size of the maximum handshake message for the Noise XX pattern.
+	// Also, since we prefix every noise handshake message with its length, we need to account for
+	// it when we fetch the buffer from the pool
+	maxMsgSize := 2*noise.DH25519.DHLen() + len(payload) + 2*chacha20poly1305.Overhead
+	hbuf := pool.Get(maxMsgSize + LengthPrefixLength)
+	defer pool.Put(hbuf)
+
+	if s.initiator {
+		// stage 0 //
+		// do not send the payload just yet, as it would be plaintext; not secret.
+		// Handshake Msg Len = len(DH ephemeral key)
+		err = s.sendHandshakeMessage(hs, nil, hbuf)
+		if err != nil {
+			return fmt.Errorf("error sending handshake message: %w", err)
+		}
+
+		// stage 1 //
+		plaintext, err := s.readHandshakeMessage(hs)
+		if err != nil {
+			return fmt.Errorf("error reading handshake message: %w", err)
+		}
+		err = s.handleRemoteHandshakePayload(plaintext, hs.PeerStatic())
+		if err != nil {
+			return err
+		}
+
+		// stage 2 //
+		// Handshake Msg Len = len(DHT static key) +  MAC(static key is encrypted) + len(Payload) + MAC(payload is encrypted)
+		err = s.sendHandshakeMessage(hs, payload, hbuf)
+		if err != nil {
+			return fmt.Errorf("error sending handshake message: %w", err)
+		}
+	} else {
+		// stage 0 //
+		// We don't expect any payload on the first message.
+		if _, err := s.readHandshakeMessage(hs); err != nil {
+			return fmt.Errorf("error reading handshake message: %w", err)
+		}
+
+		// stage 1 //
+		// Handshake Msg Len = len(DH ephemeral key) + len(DHT static key) +  MAC(static key is encrypted) + len(Payload) +
+		// MAC(payload is encrypted)
+		err = s.sendHandshakeMessage(hs, payload, hbuf)
+		if err != nil {
+			return fmt.Errorf("error sending handshake message: %w", err)
+		}
+
+		// stage 2 //
+		plaintext, err := s.readHandshakeMessage(hs)
+		if err != nil {
+			return fmt.Errorf("error reading handshake message: %w", err)
+		}
+		err = s.handleRemoteHandshakePayload(plaintext, hs.PeerStatic())
+		if err != nil {
+			return err
+		}
+	}
+
+	return nil
+}
+
+// setCipherStates sets the initial cipher states that will be used to protect
+// traffic after the handshake.
+//
+// It is called when the final handshake message is processed by
+// either sendHandshakeMessage or readHandshakeMessage.
+func (s *secureSession) setCipherStates(cs1, cs2 *noise.CipherState) {
+	if s.initiator {
+		s.enc = cs1
+		s.dec = cs2
+	} else {
+		s.enc = cs2
+		s.dec = cs1
+	}
+}
+
+// sendHandshakeMessage sends the next handshake message in the sequence.
+//
+// If payload is non-empty, it will be included in the handshake message.
+// If this is the final message in the sequence, calls setCipherStates
+// to initialize cipher states.
+func (s *secureSession) sendHandshakeMessage(hs *noise.HandshakeState, payload []byte, hbuf []byte) error {
+	// the first two bytes will be the length of the noise handshake message.
+	bz, cs1, cs2, err := hs.WriteMessage(hbuf[:LengthPrefixLength], payload)
+	if err != nil {
+		return err
+	}
+
+	// bz will also include the length prefix as we passed a slice of LengthPrefixLength length
+	// to hs.Write().
+	binary.BigEndian.PutUint16(bz, uint16(len(bz)-LengthPrefixLength))
+
+	_, err = s.writeMsgInsecure(bz)
+	if err != nil {
+		return err
+	}
+
+	if cs1 != nil && cs2 != nil {
+		s.setCipherStates(cs1, cs2)
+	}
+	return nil
+}
+
+// readHandshakeMessage reads a message from the insecure conn and tries to
+// process it as the expected next message in the handshake sequence.
+//
+// If the message contains a payload, it will be decrypted and returned.
+//
+// If this is the final message in the sequence, it calls setCipherStates
+// to initialize cipher states.
+func (s *secureSession) readHandshakeMessage(hs *noise.HandshakeState) ([]byte, error) {
+	l, err := s.readNextInsecureMsgLen()
+	if err != nil {
+		return nil, err
+	}
+
+	buf := pool.Get(l)
+	defer pool.Put(buf)
+
+	if err := s.readNextMsgInsecure(buf); err != nil {
+		return nil, err
+	}
+
+	msg, cs1, cs2, err := hs.ReadMessage(nil, buf)
+	if err != nil {
+		return nil, err
+	}
+	if cs1 != nil && cs2 != nil {
+		s.setCipherStates(cs1, cs2)
+	}
+	return msg, nil
+}
+
+// generateHandshakePayload creates a libp2p handshake payload with a
+// signature of our static noise key.
+func (s *secureSession) generateHandshakePayload(localStatic noise.DHKey) ([]byte, error) {
+	// obtain the public key from the handshake session so we can sign it with
+	// our libp2p secret key.
+	localKeyRaw, err := crypto.MarshalPublicKey(s.LocalPublicKey())
+	if err != nil {
+		return nil, fmt.Errorf("error serializing libp2p identity key: %w", err)
+	}
+
+	// prepare payload to sign; perform signature.
+	toSign := append([]byte(payloadSigPrefix), localStatic.Public...)
+	signedPayload, err := s.localKey.Sign(toSign)
+	if err != nil {
+		return nil, fmt.Errorf("error sigining handshake payload: %w", err)
+	}
+
+	// create payload
+	payload := new(pb.NoiseHandshakePayload)
+	payload.IdentityKey = localKeyRaw
+	payload.IdentitySig = signedPayload
+	payloadEnc, err := proto.Marshal(payload)
+	if err != nil {
+		return nil, fmt.Errorf("error marshaling handshake payload: %w", err)
+	}
+	return payloadEnc, nil
+}
+
+// handleRemoteHandshakePayload unmarshals the handshake payload object sent
+// by the remote peer and validates the signature against the peer's static Noise key.
+func (s *secureSession) handleRemoteHandshakePayload(payload []byte, remoteStatic []byte) error {
+	// unmarshal payload
+	nhp := new(pb.NoiseHandshakePayload)
+	err := proto.Unmarshal(payload, nhp)
+	if err != nil {
+		return fmt.Errorf("error unmarshaling remote handshake payload: %w", err)
+	}
+
+	// unpack remote peer's public libp2p key
+	remotePubKey, err := crypto.UnmarshalPublicKey(nhp.GetIdentityKey())
+	if err != nil {
+		return err
+	}
+	id, err := peer.IDFromPublicKey(remotePubKey)
+	if err != nil {
+		return err
+	}
+
+	// check the peer ID for:
+	// * all outbound connection
+	// * inbound connections, if we know which peer we want to connect to (SecureInbound called with a peer ID)
+	if (s.initiator && s.remoteID != id) || (!s.initiator && s.remoteID != "" && s.remoteID != id) {
+		// use Pretty() as it produces the full b58-encoded string, rather than abbreviated forms.
+		return fmt.Errorf("peer id mismatch: expected %s, but remote key matches %s", s.remoteID.Pretty(), id.Pretty())
+	}
+
+	// verify payload is signed by asserted remote libp2p key.
+	sig := nhp.GetIdentitySig()
+	msg := append([]byte(payloadSigPrefix), remoteStatic...)
+	ok, err := remotePubKey.Verify(msg, sig)
+	if err != nil {
+		return fmt.Errorf("error verifying signature: %w", err)
+	} else if !ok {
+		return fmt.Errorf("handshake signature invalid")
+	}
+
+	// set remote peer key and id
+	s.remoteID = id
+	s.remoteKey = remotePubKey
+	return nil
+}
diff --git a/p2p/security/noise/pb/Makefile b/p2p/security/noise/pb/Makefile
new file mode 100644
index 00000000..7cf8222f
--- /dev/null
+++ b/p2p/security/noise/pb/Makefile
@@ -0,0 +1,11 @@
+PB = $(wildcard *.proto)
+GO = $(PB:.proto=.pb.go)
+
+all: $(GO)
+
+%.pb.go: %.proto
+		protoc --proto_path=$(PWD):$(PWD)/../.. --gogofaster_out=. $<
+
+clean:
+		rm -f *.pb.go
+		rm -f *.go
diff --git a/p2p/security/noise/pb/payload.pb.go b/p2p/security/noise/pb/payload.pb.go
new file mode 100644
index 00000000..ffb29c3c
--- /dev/null
+++ b/p2p/security/noise/pb/payload.pb.go
@@ -0,0 +1,422 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: payload.proto
+
+package pb
+
+import (
+	fmt "fmt"
+	proto "github.com/gogo/protobuf/proto"
+	io "io"
+	math "math"
+	math_bits "math/bits"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+type NoiseHandshakePayload struct {
+	IdentityKey []byte `protobuf:"bytes,1,opt,name=identity_key,json=identityKey,proto3" json:"identity_key,omitempty"`
+	IdentitySig []byte `protobuf:"bytes,2,opt,name=identity_sig,json=identitySig,proto3" json:"identity_sig,omitempty"`
+	Data        []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
+}
+
+func (m *NoiseHandshakePayload) Reset()         { *m = NoiseHandshakePayload{} }
+func (m *NoiseHandshakePayload) String() string { return proto.CompactTextString(m) }
+func (*NoiseHandshakePayload) ProtoMessage()    {}
+func (*NoiseHandshakePayload) Descriptor() ([]byte, []int) {
+	return fileDescriptor_678c914f1bee6d56, []int{0}
+}
+func (m *NoiseHandshakePayload) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *NoiseHandshakePayload) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	if deterministic {
+		return xxx_messageInfo_NoiseHandshakePayload.Marshal(b, m, deterministic)
+	} else {
+		b = b[:cap(b)]
+		n, err := m.MarshalToSizedBuffer(b)
+		if err != nil {
+			return nil, err
+		}
+		return b[:n], nil
+	}
+}
+func (m *NoiseHandshakePayload) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_NoiseHandshakePayload.Merge(m, src)
+}
+func (m *NoiseHandshakePayload) XXX_Size() int {
+	return m.Size()
+}
+func (m *NoiseHandshakePayload) XXX_DiscardUnknown() {
+	xxx_messageInfo_NoiseHandshakePayload.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_NoiseHandshakePayload proto.InternalMessageInfo
+
+func (m *NoiseHandshakePayload) GetIdentityKey() []byte {
+	if m != nil {
+		return m.IdentityKey
+	}
+	return nil
+}
+
+func (m *NoiseHandshakePayload) GetIdentitySig() []byte {
+	if m != nil {
+		return m.IdentitySig
+	}
+	return nil
+}
+
+func (m *NoiseHandshakePayload) GetData() []byte {
+	if m != nil {
+		return m.Data
+	}
+	return nil
+}
+
+func init() {
+	proto.RegisterType((*NoiseHandshakePayload)(nil), "pb.NoiseHandshakePayload")
+}
+
+func init() { proto.RegisterFile("payload.proto", fileDescriptor_678c914f1bee6d56) }
+
+var fileDescriptor_678c914f1bee6d56 = []byte{
+	// 152 bytes of a gzipped FileDescriptorProto
+	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2d, 0x48, 0xac, 0xcc,
+	0xc9, 0x4f, 0x4c, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x48, 0x52, 0x2a, 0xe4,
+	0x12, 0xf5, 0xcb, 0xcf, 0x2c, 0x4e, 0xf5, 0x48, 0xcc, 0x4b, 0x29, 0xce, 0x48, 0xcc, 0x4e, 0x0d,
+	0x80, 0x28, 0x11, 0x52, 0xe4, 0xe2, 0xc9, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xa9, 0x8c, 0xcf,
+	0x4e, 0xad, 0x94, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0xe2, 0x86, 0x89, 0x79, 0xa7, 0x56, 0xa2,
+	0x28, 0x29, 0xce, 0x4c, 0x97, 0x60, 0x42, 0x55, 0x12, 0x9c, 0x99, 0x2e, 0x24, 0xc4, 0xc5, 0x92,
+	0x92, 0x58, 0x92, 0x28, 0xc1, 0x0c, 0x96, 0x02, 0xb3, 0x9d, 0x24, 0x4e, 0x3c, 0x92, 0x63, 0xbc,
+	0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63,
+	0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x89, 0x0d, 0xec, 0x2e, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff,
+	0x51, 0x37, 0xd7, 0x40, 0xa8, 0x00, 0x00, 0x00,
+}
+
+func (m *NoiseHandshakePayload) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *NoiseHandshakePayload) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *NoiseHandshakePayload) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.Data) > 0 {
+		i -= len(m.Data)
+		copy(dAtA[i:], m.Data)
+		i = encodeVarintPayload(dAtA, i, uint64(len(m.Data)))
+		i--
+		dAtA[i] = 0x1a
+	}
+	if len(m.IdentitySig) > 0 {
+		i -= len(m.IdentitySig)
+		copy(dAtA[i:], m.IdentitySig)
+		i = encodeVarintPayload(dAtA, i, uint64(len(m.IdentitySig)))
+		i--
+		dAtA[i] = 0x12
+	}
+	if len(m.IdentityKey) > 0 {
+		i -= len(m.IdentityKey)
+		copy(dAtA[i:], m.IdentityKey)
+		i = encodeVarintPayload(dAtA, i, uint64(len(m.IdentityKey)))
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func encodeVarintPayload(dAtA []byte, offset int, v uint64) int {
+	offset -= sovPayload(v)
+	base := offset
+	for v >= 1<<7 {
+		dAtA[offset] = uint8(v&0x7f | 0x80)
+		v >>= 7
+		offset++
+	}
+	dAtA[offset] = uint8(v)
+	return base
+}
+func (m *NoiseHandshakePayload) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.IdentityKey)
+	if l > 0 {
+		n += 1 + l + sovPayload(uint64(l))
+	}
+	l = len(m.IdentitySig)
+	if l > 0 {
+		n += 1 + l + sovPayload(uint64(l))
+	}
+	l = len(m.Data)
+	if l > 0 {
+		n += 1 + l + sovPayload(uint64(l))
+	}
+	return n
+}
+
+func sovPayload(x uint64) (n int) {
+	return (math_bits.Len64(x|1) + 6) / 7
+}
+func sozPayload(x uint64) (n int) {
+	return sovPayload(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *NoiseHandshakePayload) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowPayload
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: NoiseHandshakePayload: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: NoiseHandshakePayload: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field IdentityKey", wireType)
+			}
+			var byteLen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowPayload
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				byteLen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if byteLen < 0 {
+				return ErrInvalidLengthPayload
+			}
+			postIndex := iNdEx + byteLen
+			if postIndex < 0 {
+				return ErrInvalidLengthPayload
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.IdentityKey = append(m.IdentityKey[:0], dAtA[iNdEx:postIndex]...)
+			if m.IdentityKey == nil {
+				m.IdentityKey = []byte{}
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field IdentitySig", wireType)
+			}
+			var byteLen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowPayload
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				byteLen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if byteLen < 0 {
+				return ErrInvalidLengthPayload
+			}
+			postIndex := iNdEx + byteLen
+			if postIndex < 0 {
+				return ErrInvalidLengthPayload
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.IdentitySig = append(m.IdentitySig[:0], dAtA[iNdEx:postIndex]...)
+			if m.IdentitySig == nil {
+				m.IdentitySig = []byte{}
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+			}
+			var byteLen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowPayload
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				byteLen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if byteLen < 0 {
+				return ErrInvalidLengthPayload
+			}
+			postIndex := iNdEx + byteLen
+			if postIndex < 0 {
+				return ErrInvalidLengthPayload
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+			if m.Data == nil {
+				m.Data = []byte{}
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipPayload(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthPayload
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func skipPayload(dAtA []byte) (n int, err error) {
+	l := len(dAtA)
+	iNdEx := 0
+	depth := 0
+	for iNdEx < l {
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return 0, ErrIntOverflowPayload
+			}
+			if iNdEx >= l {
+				return 0, io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= (uint64(b) & 0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		wireType := int(wire & 0x7)
+		switch wireType {
+		case 0:
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowPayload
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				iNdEx++
+				if dAtA[iNdEx-1] < 0x80 {
+					break
+				}
+			}
+		case 1:
+			iNdEx += 8
+		case 2:
+			var length int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowPayload
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				length |= (int(b) & 0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if length < 0 {
+				return 0, ErrInvalidLengthPayload
+			}
+			iNdEx += length
+		case 3:
+			depth++
+		case 4:
+			if depth == 0 {
+				return 0, ErrUnexpectedEndOfGroupPayload
+			}
+			depth--
+		case 5:
+			iNdEx += 4
+		default:
+			return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+		}
+		if iNdEx < 0 {
+			return 0, ErrInvalidLengthPayload
+		}
+		if depth == 0 {
+			return iNdEx, nil
+		}
+	}
+	return 0, io.ErrUnexpectedEOF
+}
+
+var (
+	ErrInvalidLengthPayload        = fmt.Errorf("proto: negative length found during unmarshaling")
+	ErrIntOverflowPayload          = fmt.Errorf("proto: integer overflow")
+	ErrUnexpectedEndOfGroupPayload = fmt.Errorf("proto: unexpected end of group")
+)
diff --git a/p2p/security/noise/pb/payload.proto b/p2p/security/noise/pb/payload.proto
new file mode 100644
index 00000000..05a78c6f
--- /dev/null
+++ b/p2p/security/noise/pb/payload.proto
@@ -0,0 +1,8 @@
+syntax = "proto3";
+package pb;
+
+message NoiseHandshakePayload {
+	bytes identity_key = 1;
+	bytes identity_sig = 2;
+	bytes data = 3;
+}
diff --git a/p2p/security/noise/rw.go b/p2p/security/noise/rw.go
new file mode 100644
index 00000000..d52768f4
--- /dev/null
+++ b/p2p/security/noise/rw.go
@@ -0,0 +1,155 @@
+package noise
+
+import (
+	"encoding/binary"
+	"io"
+
+	pool "github.com/libp2p/go-buffer-pool"
+	"golang.org/x/crypto/chacha20poly1305"
+)
+
+// MaxTransportMsgLength is the Noise-imposed maximum transport message length,
+// inclusive of the MAC size (16 bytes, Poly1305 for noise-libp2p).
+const MaxTransportMsgLength = 0xffff
+
+// MaxPlaintextLength is the maximum payload size. It is MaxTransportMsgLength
+// minus the MAC size. Payloads over this size will be automatically chunked.
+const MaxPlaintextLength = MaxTransportMsgLength - chacha20poly1305.Overhead
+
+// LengthPrefixLength is the length of the length prefix itself, which precedes
+// all transport messages in order to delimit them. In bytes.
+const LengthPrefixLength = 2
+
+// Read reads from the secure connection, returning plaintext data in `buf`.
+//
+// Honours io.Reader in terms of behaviour.
+func (s *secureSession) Read(buf []byte) (int, error) {
+	s.readLock.Lock()
+	defer s.readLock.Unlock()
+
+	// 1. If we have queued received bytes:
+	//   1a. If len(buf) < len(queued), saturate buf, update seek pointer, return.
+	//   1b. If len(buf) >= len(queued), copy remaining to buf, release queued buffer back into pool, return.
+	//
+	// 2. Else, read the next message off the wire; next_len is length prefix.
+	//   2a. If len(buf) >= next_len, copy the message to input buffer (zero-alloc path), and return.
+	//   2b. If len(buf) >= (next_len - length of Authentication Tag), get buffer from pool, read encrypted message into it.
+	//       decrypt message directly into the input buffer and return the buffer obtained from the pool.
+	//   2c. If len(buf) < next_len, obtain buffer from pool, copy entire message into it, saturate buf, update seek pointer.
+	if s.qbuf != nil {
+		// we have queued bytes; copy as much as we can.
+		copied := copy(buf, s.qbuf[s.qseek:])
+		s.qseek += copied
+		if s.qseek == len(s.qbuf) {
+			// queued buffer is now empty, reset and release.
+			pool.Put(s.qbuf)
+			s.qseek, s.qbuf = 0, nil
+		}
+		return copied, nil
+	}
+
+	// length of the next encrypted message.
+	nextMsgLen, err := s.readNextInsecureMsgLen()
+	if err != nil {
+		return 0, err
+	}
+
+	// If the buffer is atleast as big as the encrypted message size,
+	// we can read AND decrypt in place.
+	if len(buf) >= nextMsgLen {
+		if err := s.readNextMsgInsecure(buf[:nextMsgLen]); err != nil {
+			return 0, err
+		}
+
+		dbuf, err := s.decrypt(buf[:0], buf[:nextMsgLen])
+		if err != nil {
+			return 0, err
+		}
+
+		return len(dbuf), nil
+	}
+
+	// otherwise, we get a buffer from the pool so we can read the message into it
+	// and then decrypt in place, since we're retaining the buffer (or a view thereof).
+	cbuf := pool.Get(nextMsgLen)
+	if err := s.readNextMsgInsecure(cbuf); err != nil {
+		return 0, err
+	}
+
+	if s.qbuf, err = s.decrypt(cbuf[:0], cbuf); err != nil {
+		return 0, err
+	}
+
+	// copy as many bytes as we can; update seek pointer.
+	s.qseek = copy(buf, s.qbuf)
+
+	return s.qseek, nil
+}
+
+// Write encrypts the plaintext `in` data and sends it on the
+// secure connection.
+func (s *secureSession) Write(data []byte) (int, error) {
+	s.writeLock.Lock()
+	defer s.writeLock.Unlock()
+
+	var (
+		written int
+		cbuf    []byte
+		total   = len(data)
+	)
+
+	if total < MaxPlaintextLength {
+		cbuf = pool.Get(total + chacha20poly1305.Overhead + LengthPrefixLength)
+	} else {
+		cbuf = pool.Get(MaxTransportMsgLength + LengthPrefixLength)
+	}
+
+	defer pool.Put(cbuf)
+
+	for written < total {
+		end := written + MaxPlaintextLength
+		if end > total {
+			end = total
+		}
+
+		b, err := s.encrypt(cbuf[:LengthPrefixLength], data[written:end])
+		if err != nil {
+			return 0, err
+		}
+
+		binary.BigEndian.PutUint16(b, uint16(len(b)-LengthPrefixLength))
+
+		_, err = s.writeMsgInsecure(b)
+		if err != nil {
+			return written, err
+		}
+		written = end
+	}
+	return written, nil
+}
+
+// readNextInsecureMsgLen reads the length of the next message on the insecureConn channel.
+func (s *secureSession) readNextInsecureMsgLen() (int, error) {
+	_, err := io.ReadFull(s.insecureReader, s.rlen[:])
+	if err != nil {
+		return 0, err
+	}
+
+	return int(binary.BigEndian.Uint16(s.rlen[:])), err
+}
+
+// readNextMsgInsecure tries to read exactly len(buf) bytes into buf from
+// the insecureConn channel and returns the error, if any.
+// Ideally, for reading a message, you'd first want to call `readNextInsecureMsgLen`
+// to determine the size of the next message to be read from the insecureConn channel and then call
+// this function with a buffer of exactly that size.
+func (s *secureSession) readNextMsgInsecure(buf []byte) error {
+	_, err := io.ReadFull(s.insecureReader, buf)
+	return err
+}
+
+// writeMsgInsecure writes to the insecureConn conn.
+// data will be prefixed with its length in bytes, written as a 16-bit uint in network order.
+func (s *secureSession) writeMsgInsecure(data []byte) (int, error) {
+	return s.insecureConn.Write(data)
+}
diff --git a/p2p/security/noise/session.go b/p2p/security/noise/session.go
new file mode 100644
index 00000000..9675cc03
--- /dev/null
+++ b/p2p/security/noise/session.go
@@ -0,0 +1,117 @@
+package noise
+
+import (
+	"bufio"
+	"context"
+	"net"
+	"sync"
+	"time"
+
+	"github.com/flynn/noise"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+	"github.com/libp2p/go-libp2p-core/peer"
+)
+
+type secureSession struct {
+	initiator bool
+
+	localID   peer.ID
+	localKey  crypto.PrivKey
+	remoteID  peer.ID
+	remoteKey crypto.PubKey
+
+	readLock  sync.Mutex
+	writeLock sync.Mutex
+
+	insecureConn   net.Conn
+	insecureReader *bufio.Reader // to cushion io read syscalls
+	// we don't buffer writes to avoid introducing latency; optimisation possible. // TODO revisit
+
+	qseek int     // queued bytes seek value.
+	qbuf  []byte  // queued bytes buffer.
+	rlen  [2]byte // work buffer to read in the incoming message length.
+
+	enc *noise.CipherState
+	dec *noise.CipherState
+}
+
+// newSecureSession creates a Noise session over the given insecureConn Conn, using
+// the libp2p identity keypair from the given Transport.
+func newSecureSession(tpt *Transport, ctx context.Context, insecure net.Conn, remote peer.ID, initiator bool) (*secureSession, error) {
+	s := &secureSession{
+		insecureConn:   insecure,
+		insecureReader: bufio.NewReader(insecure),
+		initiator:      initiator,
+		localID:        tpt.localID,
+		localKey:       tpt.privateKey,
+		remoteID:       remote,
+	}
+
+	// the go-routine we create to run the handshake will
+	// write the result of the handshake to the respCh.
+	respCh := make(chan error, 1)
+	go func() {
+		respCh <- s.runHandshake(ctx)
+	}()
+
+	select {
+	case err := <-respCh:
+		if err != nil {
+			_ = s.insecureConn.Close()
+		}
+		return s, err
+
+	case <-ctx.Done():
+		// If the context has been cancelled, we close the underlying connection.
+		// We then wait for the handshake to return because of the first error it encounters
+		// so we don't return without cleaning up the go-routine.
+		_ = s.insecureConn.Close()
+		<-respCh
+		return nil, ctx.Err()
+	}
+}
+
+func (s *secureSession) LocalAddr() net.Addr {
+	return s.insecureConn.LocalAddr()
+}
+
+func (s *secureSession) LocalPeer() peer.ID {
+	return s.localID
+}
+
+func (s *secureSession) LocalPrivateKey() crypto.PrivKey {
+	return s.localKey
+}
+
+func (s *secureSession) LocalPublicKey() crypto.PubKey {
+	return s.localKey.GetPublic()
+}
+
+func (s *secureSession) RemoteAddr() net.Addr {
+	return s.insecureConn.RemoteAddr()
+}
+
+func (s *secureSession) RemotePeer() peer.ID {
+	return s.remoteID
+}
+
+func (s *secureSession) RemotePublicKey() crypto.PubKey {
+	return s.remoteKey
+}
+
+func (s *secureSession) SetDeadline(t time.Time) error {
+	return s.insecureConn.SetDeadline(t)
+}
+
+func (s *secureSession) SetReadDeadline(t time.Time) error {
+	return s.insecureConn.SetReadDeadline(t)
+}
+
+func (s *secureSession) SetWriteDeadline(t time.Time) error {
+	return s.insecureConn.SetWriteDeadline(t)
+}
+
+func (s *secureSession) Close() error {
+	return s.insecureConn.Close()
+}
diff --git a/p2p/security/noise/transport.go b/p2p/security/noise/transport.go
new file mode 100644
index 00000000..c8d7a44f
--- /dev/null
+++ b/p2p/security/noise/transport.go
@@ -0,0 +1,47 @@
+package noise
+
+import (
+	"context"
+	"net"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+	"github.com/libp2p/go-libp2p-core/peer"
+	"github.com/libp2p/go-libp2p-core/sec"
+)
+
+// ID is the protocol ID for noise
+const ID = "/noise"
+
+var _ sec.SecureTransport = &Transport{}
+
+// Transport implements the interface sec.SecureTransport
+// https://godoc.org/github.com/libp2p/go-libp2p-core/sec#SecureConn
+type Transport struct {
+	localID    peer.ID
+	privateKey crypto.PrivKey
+}
+
+// New creates a new Noise transport using the given private key as its
+// libp2p identity key.
+func New(privkey crypto.PrivKey) (*Transport, error) {
+	localID, err := peer.IDFromPrivateKey(privkey)
+	if err != nil {
+		return nil, err
+	}
+
+	return &Transport{
+		localID:    localID,
+		privateKey: privkey,
+	}, nil
+}
+
+// SecureInbound runs the Noise handshake as the responder.
+// If p is empty, connections from any peer are accepted.
+func (t *Transport) SecureInbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
+	return newSecureSession(t, ctx, insecure, p, false)
+}
+
+// SecureOutbound runs the Noise handshake as the initiator.
+func (t *Transport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
+	return newSecureSession(t, ctx, insecure, p, true)
+}


Test patch:
diff --git a/p2p/security/noise/benchmark_test.go b/p2p/security/noise/benchmark_test.go
new file mode 100644
index 00000000..b11faf57
--- /dev/null
+++ b/p2p/security/noise/benchmark_test.go
@@ -0,0 +1,252 @@
+package noise
+
+import (
+	"context"
+	"io"
+	"io/ioutil"
+	"math/rand"
+	"net"
+	"testing"
+	"time"
+
+	"golang.org/x/crypto/chacha20poly1305"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+	"github.com/libp2p/go-libp2p-core/sec"
+)
+
+type testMode int
+
+const (
+	readBufferGtEncMsg testMode = iota
+	readBufferLtPlainText
+)
+
+var bcs = map[string]struct {
+	m testMode
+}{
+	"readBuffer > encrypted message": {
+		readBufferGtEncMsg,
+	},
+	"readBuffer < decrypted plaintext": {
+		readBufferLtPlainText,
+	},
+}
+
+func makeTransport(b *testing.B) *Transport {
+	b.Helper()
+
+	priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, 256)
+	if err != nil {
+		b.Fatal(err)
+	}
+	tpt, err := New(priv)
+	if err != nil {
+		b.Fatalf("error constructing transport: %v", err)
+	}
+	return tpt
+}
+
+type benchenv struct {
+	*testing.B
+
+	initTpt *Transport
+	respTpt *Transport
+	rndSrc  rand.Source
+}
+
+func setupEnv(b *testing.B) *benchenv {
+	b.StopTimer()
+	defer b.StartTimer()
+	initTpt := makeTransport(b)
+	respTpt := makeTransport(b)
+
+	return &benchenv{
+		B:       b,
+		initTpt: initTpt,
+		respTpt: respTpt,
+		rndSrc:  rand.NewSource(42),
+	}
+}
+
+func (b benchenv) connect(stopTimer bool) (*secureSession, *secureSession) {
+	initConn, respConn := net.Pipe()
+
+	if stopTimer {
+		b.StopTimer()
+		defer b.StartTimer()
+	}
+
+	var initSession sec.SecureConn
+	var initErr error
+	done := make(chan struct{})
+	go func() {
+		defer close(done)
+		initSession, initErr = b.initTpt.SecureOutbound(context.TODO(), initConn, b.respTpt.localID)
+	}()
+
+	respSession, respErr := b.respTpt.SecureInbound(context.TODO(), respConn, "")
+	<-done
+
+	if initErr != nil {
+		b.Fatal(initErr)
+	}
+
+	if respErr != nil {
+		b.Fatal(respErr)
+	}
+
+	return initSession.(*secureSession), respSession.(*secureSession)
+}
+
+func drain(r io.Reader, done chan<- error, writeTo io.Writer) {
+	_, err := io.Copy(writeTo, r)
+	done <- err
+}
+
+type discardWithBuffer struct {
+	buf []byte
+	io.Writer
+}
+
+func (d *discardWithBuffer) ReadFrom(r io.Reader) (n int64, err error) {
+	readSize := 0
+	for {
+		readSize, err = r.Read(d.buf)
+		n += int64(readSize)
+		if err != nil {
+			if err == io.EOF {
+				return n, nil
+			}
+			return
+		}
+	}
+}
+
+func sink(dst io.WriteCloser, src io.Reader, done chan<- error, buf []byte) {
+	_, err := io.CopyBuffer(dst, src, buf)
+	if err != nil {
+		done <- err
+	}
+	done <- dst.Close()
+}
+
+func pipeRandom(src rand.Source, w io.WriteCloser, r io.Reader, n int64, plainTextBuf []byte,
+	writeTo io.Writer) error {
+	rnd := rand.New(src)
+	lr := io.LimitReader(rnd, n)
+
+	writeCh := make(chan error, 1)
+	readCh := make(chan error, 1)
+
+	go sink(w, lr, writeCh, plainTextBuf)
+	go drain(r, readCh, writeTo)
+
+	writeDone := false
+	readDone := false
+	for !(readDone && writeDone) {
+		select {
+		case err := <-readCh:
+			if err != nil && err != io.EOF {
+				return err
+			}
+			readDone = true
+		case err := <-writeCh:
+			if err != nil && err != io.EOF {
+				return err
+			}
+			writeDone = true
+		}
+	}
+
+	return nil
+}
+
+func benchDataTransfer(b *benchenv, dataSize int64, m testMode) {
+	var totalBytes int64
+	var totalTime time.Duration
+
+	plainTextBufs := make([][]byte, 61)
+	writeTos := make(map[int]io.Writer)
+	for i := 0; i < len(plainTextBufs); i++ {
+		var rbuf []byte
+		// plaintext will be 2 KB to 62 KB
+		plainTextBufs[i] = make([]byte, (i+2)*1024)
+		switch m {
+		case readBufferGtEncMsg:
+			rbuf = make([]byte, len(plainTextBufs[i])+chacha20poly1305.Overhead+1)
+		case readBufferLtPlainText:
+			rbuf = make([]byte, len(plainTextBufs[i])-2)
+		}
+		writeTos[i] = &discardWithBuffer{rbuf, ioutil.Discard}
+	}
+
+	b.ResetTimer()
+	b.ReportAllocs()
+
+	for i := 0; i < b.N; i++ {
+		initSession, respSession := b.connect(true)
+
+		start := time.Now()
+
+		bufi := i % len(plainTextBufs)
+		err := pipeRandom(b.rndSrc, initSession, respSession, dataSize, plainTextBufs[bufi], writeTos[bufi])
+		if err != nil {
+			b.Fatalf("error sending random data: %s", err)
+		}
+		elapsed := time.Since(start)
+		totalTime += elapsed
+		totalBytes += dataSize
+	}
+	bytesPerSec := float64(totalBytes) / totalTime.Seconds()
+	b.ReportMetric(bytesPerSec, "bytes/sec")
+}
+
+func BenchmarkTransfer1MB(b *testing.B) {
+	for n, bc := range bcs {
+		b.Run(n, func(b *testing.B) {
+			benchDataTransfer(setupEnv(b), 1024*1024, bc.m)
+		})
+	}
+
+}
+
+func BenchmarkTransfer100MB(b *testing.B) {
+	for n, bc := range bcs {
+		b.Run(n, func(b *testing.B) {
+			benchDataTransfer(setupEnv(b), 1024*1024*100, bc.m)
+		})
+	}
+}
+
+func BenchmarkTransfer500Mb(b *testing.B) {
+	for n, bc := range bcs {
+		b.Run(n, func(b *testing.B) {
+			benchDataTransfer(setupEnv(b), 1024*1024*500, bc.m)
+		})
+	}
+}
+
+func (b benchenv) benchHandshake() {
+	b.ResetTimer()
+	b.ReportAllocs()
+
+	for i := 0; i < b.N; i++ {
+		i, r := b.connect(false)
+		b.StopTimer()
+		err := i.Close()
+		if err != nil {
+			b.Errorf("error closing session: %s", err)
+		}
+		err = r.Close()
+		if err != nil {
+			b.Errorf("error closing session: %s", err)
+		}
+		b.StartTimer()
+	}
+}
+
+func BenchmarkHandshakeXX(b *testing.B) {
+	env := setupEnv(b)
+	env.benchHandshake()
+}
diff --git a/p2p/security/noise/crypto_test.go b/p2p/security/noise/crypto_test.go
new file mode 100644
index 00000000..ca5125cd
--- /dev/null
+++ b/p2p/security/noise/crypto_test.go
@@ -0,0 +1,105 @@
+package noise
+
+import (
+	"bytes"
+	"context"
+	"net"
+	"testing"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+)
+
+func TestEncryptAndDecrypt_InitToResp(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	plaintext := []byte("helloworld")
+	ciphertext, err := initConn.encrypt(nil, plaintext)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	result, err := respConn.decrypt(nil, ciphertext)
+	if !bytes.Equal(plaintext, result) {
+		t.Fatalf("got %x expected %x", result, plaintext)
+	} else if err != nil {
+		t.Fatal(err)
+	}
+
+	plaintext = []byte("goodbye")
+	ciphertext, err = initConn.encrypt(nil, plaintext)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	result, err = respConn.decrypt(nil, ciphertext)
+	if !bytes.Equal(plaintext, result) {
+		t.Fatalf("got %x expected %x", result, plaintext)
+	} else if err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestEncryptAndDecrypt_RespToInit(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	plaintext := []byte("helloworld")
+	ciphertext, err := respConn.encrypt(nil, plaintext)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	result, err := initConn.decrypt(nil, ciphertext)
+	if !bytes.Equal(plaintext, result) {
+		t.Fatalf("got %x expected %x", result, plaintext)
+	} else if err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestCryptoFailsIfCiphertextIsAltered(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	plaintext := []byte("helloworld")
+	ciphertext, err := respConn.encrypt(nil, plaintext)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	ciphertext[0] = ^ciphertext[0]
+
+	_, err = initConn.decrypt(nil, ciphertext)
+	if err == nil {
+		t.Fatal("expected decryption to fail when ciphertext altered")
+	}
+}
+
+func TestCryptoFailsIfHandshakeIncomplete(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	init, resp := net.Pipe()
+	_ = resp.Close()
+
+	session, _ := newSecureSession(initTransport, context.TODO(), init, "remote-peer", true)
+	_, err := session.encrypt(nil, []byte("hi"))
+	if err == nil {
+		t.Error("expected encryption error when handshake incomplete")
+	}
+	_, err = session.decrypt(nil, []byte("it's a secret"))
+	if err == nil {
+		t.Error("expected decryption error when handshake incomplete")
+	}
+}
diff --git a/p2p/security/noise/session_test.go b/p2p/security/noise/session_test.go
new file mode 100644
index 00000000..ff2d69b5
--- /dev/null
+++ b/p2p/security/noise/session_test.go
@@ -0,0 +1,26 @@
+package noise
+
+import (
+	"context"
+	"testing"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+
+	"github.com/stretchr/testify/require"
+)
+
+func TestContextCancellationRespected(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	init, resp := newConnPair(t)
+	defer init.Close()
+	defer resp.Close()
+
+	ctx, cancel := context.WithCancel(context.Background())
+	cancel()
+
+	_, err := initTransport.SecureOutbound(ctx, init, respTransport.localID)
+	require.Error(t, err)
+	require.Equal(t, ctx.Err(), err)
+}
diff --git a/p2p/security/noise/transport_test.go b/p2p/security/noise/transport_test.go
new file mode 100644
index 00000000..e88fbe59
--- /dev/null
+++ b/p2p/security/noise/transport_test.go
@@ -0,0 +1,374 @@
+package noise
+
+import (
+	"bytes"
+	"context"
+	"encoding/binary"
+	"errors"
+	"io"
+	"math/rand"
+	"net"
+	"testing"
+	"time"
+
+	"golang.org/x/crypto/chacha20poly1305"
+
+	"github.com/libp2p/go-libp2p-core/crypto"
+	"github.com/libp2p/go-libp2p-core/peer"
+	"github.com/libp2p/go-libp2p-core/sec"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func newTestTransport(t *testing.T, typ, bits int) *Transport {
+	priv, pub, err := crypto.GenerateKeyPair(typ, bits)
+	if err != nil {
+		t.Fatal(err)
+	}
+	id, err := peer.IDFromPublicKey(pub)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return &Transport{
+		localID:    id,
+		privateKey: priv,
+	}
+}
+
+// Create a new pair of connected TCP sockets.
+func newConnPair(t *testing.T) (net.Conn, net.Conn) {
+	lstnr, err := net.Listen("tcp", "localhost:0")
+	if err != nil {
+		t.Fatalf("Failed to listen: %v", err)
+		return nil, nil
+	}
+
+	var clientErr error
+	var client net.Conn
+	addr := lstnr.Addr()
+	done := make(chan struct{})
+
+	go func() {
+		defer close(done)
+		client, clientErr = net.Dial(addr.Network(), addr.String())
+	}()
+
+	server, err := lstnr.Accept()
+	<-done
+
+	lstnr.Close()
+
+	if err != nil {
+		t.Fatalf("Failed to accept: %v", err)
+	}
+
+	if clientErr != nil {
+		t.Fatalf("Failed to connect: %v", clientErr)
+	}
+
+	return client, server
+}
+
+func connect(t *testing.T, initTransport, respTransport *Transport) (*secureSession, *secureSession) {
+	init, resp := newConnPair(t)
+
+	var initConn sec.SecureConn
+	var initErr error
+	done := make(chan struct{})
+	go func() {
+		defer close(done)
+		initConn, initErr = initTransport.SecureOutbound(context.TODO(), init, respTransport.localID)
+	}()
+
+	respConn, respErr := respTransport.SecureInbound(context.TODO(), resp, "")
+	<-done
+
+	if initErr != nil {
+		t.Fatal(initErr)
+	}
+
+	if respErr != nil {
+		t.Fatal(respErr)
+	}
+
+	return initConn.(*secureSession), respConn.(*secureSession)
+}
+
+func TestDeadlines(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	init, resp := newConnPair(t)
+	defer init.Close()
+	defer resp.Close()
+
+	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
+	defer cancel()
+
+	_, err := initTransport.SecureOutbound(ctx, init, respTransport.localID)
+	if err == nil {
+		t.Fatalf("expected i/o timeout err; got: %s", err)
+	}
+
+	var neterr net.Error
+	if ok := errors.As(err, &neterr); !ok || !neterr.Timeout() {
+		t.Fatalf("expected i/o timeout err; got: %s", err)
+	}
+}
+
+func TestIDs(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	if initConn.LocalPeer() != initTransport.localID {
+		t.Fatal("Initiator Local Peer ID mismatch.")
+	}
+
+	if respConn.RemotePeer() != initTransport.localID {
+		t.Fatal("Responder Remote Peer ID mismatch.")
+	}
+
+	if initConn.LocalPeer() != respConn.RemotePeer() {
+		t.Fatal("Responder Local Peer ID mismatch.")
+	}
+
+	// TODO: check after stage 0 of handshake if updated
+	if initConn.RemotePeer() != respTransport.localID {
+		t.Errorf("Initiator Remote Peer ID mismatch. expected %x got %x", respTransport.localID, initConn.RemotePeer())
+	}
+}
+
+func TestKeys(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	sk := respConn.LocalPrivateKey()
+	pk := sk.GetPublic()
+
+	if !sk.Equals(respTransport.privateKey) {
+		t.Error("Private key Mismatch.")
+	}
+
+	if !pk.Equals(initConn.RemotePublicKey()) {
+		t.Errorf("Public key mismatch. expected %x got %x", pk, initConn.RemotePublicKey())
+	}
+}
+
+func TestPeerIDMatch(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	init, resp := newConnPair(t)
+
+	done := make(chan struct{})
+	go func() {
+		defer close(done)
+		conn, err := initTransport.SecureOutbound(context.TODO(), init, respTransport.localID)
+		assert.NoError(t, err)
+		assert.Equal(t, conn.RemotePeer(), respTransport.localID)
+		b := make([]byte, 6)
+		_, err = conn.Read(b)
+		assert.NoError(t, err)
+		assert.Equal(t, b, []byte("foobar"))
+	}()
+
+	conn, err := respTransport.SecureInbound(context.TODO(), resp, initTransport.localID)
+	require.NoError(t, err)
+	require.Equal(t, conn.RemotePeer(), initTransport.localID)
+	_, err = conn.Write([]byte("foobar"))
+	require.NoError(t, err)
+}
+
+func TestPeerIDMismatchOutboundFailsHandshake(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	init, resp := newConnPair(t)
+
+	errChan := make(chan error)
+	go func() {
+		_, err := initTransport.SecureOutbound(context.TODO(), init, "a-random-peer-id")
+		errChan <- err
+	}()
+
+	_, err := respTransport.SecureInbound(context.TODO(), resp, "")
+	require.Error(t, err)
+
+	initErr := <-errChan
+	require.Error(t, initErr, "expected initiator to fail with peer ID mismatch error")
+	require.Contains(t, initErr.Error(), "but remote key matches")
+}
+
+func TestPeerIDMismatchInboundFailsHandshake(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	init, resp := newConnPair(t)
+
+	done := make(chan struct{})
+	go func() {
+		defer close(done)
+		conn, err := initTransport.SecureOutbound(context.TODO(), init, respTransport.localID)
+		assert.NoError(t, err)
+		_, err = conn.Read([]byte{0})
+		assert.Error(t, err)
+	}()
+
+	_, err := respTransport.SecureInbound(context.TODO(), resp, "a-random-peer-id")
+	require.Error(t, err, "expected responder to fail with peer ID mismatch error")
+	<-done
+}
+
+func makeLargePlaintext(size int) []byte {
+	buf := make([]byte, size)
+	rand.Read(buf)
+	return buf
+}
+
+func TestLargePayloads(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	// enough to require a couple Noise messages, with a size that
+	// isn't a neat multiple of Noise message size, just in case
+	size := 100000
+
+	before := makeLargePlaintext(size)
+	_, err := initConn.Write(before)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	after := make([]byte, len(before))
+	afterLen, err := io.ReadFull(respConn, after)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if len(before) != afterLen {
+		t.Errorf("expected to read same amount of data as written. written=%d read=%d", len(before), afterLen)
+	}
+	if !bytes.Equal(before, after) {
+		t.Error("Message mismatch.")
+	}
+}
+
+// Tests XX handshake
+func TestHandshakeXX(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	before := []byte("hello world")
+	_, err := initConn.Write(before)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	after := make([]byte, len(before))
+	_, err = respConn.Read(after)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if !bytes.Equal(before, after) {
+		t.Errorf("Message mismatch. %v != %v", before, after)
+	}
+}
+
+func TestBufferEqEncPayload(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	before := []byte("hello world")
+	_, err := initConn.Write(before)
+	require.NoError(t, err)
+
+	after := make([]byte, len(before)+chacha20poly1305.Overhead)
+	afterLen, err := respConn.Read(after)
+	require.NoError(t, err)
+
+	require.Equal(t, len(before), afterLen)
+	require.Equal(t, before, after[:len(before)])
+}
+
+func TestBufferEqDecryptedPayload(t *testing.T) {
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	before := []byte("hello world")
+	_, err := initConn.Write(before)
+	require.NoError(t, err)
+
+	after := make([]byte, len(before)+1)
+	afterLen, err := respConn.Read(after)
+	require.NoError(t, err)
+
+	require.Equal(t, len(before), afterLen)
+	require.Equal(t, before, after[:len(before)])
+}
+
+func TestReadUnencryptedFails(t *testing.T) {
+	// case1 buffer > len(msg)
+	initTransport := newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport := newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn := connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	before := []byte("hello world")
+	msg := make([]byte, len(before)+LengthPrefixLength)
+	binary.BigEndian.PutUint16(msg, uint16(len(before)))
+	copy(msg[LengthPrefixLength:], before)
+	n, err := initConn.insecureConn.Write(msg)
+	require.NoError(t, err)
+	require.Equal(t, len(msg), n)
+
+	after := make([]byte, len(msg)+1)
+	afterLen, err := respConn.Read(after)
+	require.Error(t, err)
+	require.Equal(t, 0, afterLen)
+
+	// case2: buffer < len(msg)
+	initTransport = newTestTransport(t, crypto.Ed25519, 2048)
+	respTransport = newTestTransport(t, crypto.Ed25519, 2048)
+
+	initConn, respConn = connect(t, initTransport, respTransport)
+	defer initConn.Close()
+	defer respConn.Close()
+
+	before = []byte("hello world")
+	msg = make([]byte, len(before)+LengthPrefixLength)
+	binary.BigEndian.PutUint16(msg, uint16(len(before)))
+	copy(msg[LengthPrefixLength:], before)
+	n, err = initConn.insecureConn.Write(msg)
+	require.NoError(t, err)
+	require.Equal(t, len(msg), n)
+
+	after = make([]byte, 1)
+	afterLen, err = respConn.Read(after)
+	require.Error(t, err)
+	require.Equal(t, 0, afterLen)
+}