From 3899c506281a91644639ea5b9a1f4d566e823d44 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 28 May 2024 14:55:30 -0500 Subject: [PATCH 1/2] Add PeerID function to get the ID of the remote peer --- pkg/peerprotocol/connection.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/pkg/peerprotocol/connection.go b/pkg/peerprotocol/connection.go index a5cb403..4f3bc5f 100644 --- a/pkg/peerprotocol/connection.go +++ b/pkg/peerprotocol/connection.go @@ -2,6 +2,7 @@ package peerprotocol import ( "context" + "crypto/sha256" "crypto/tls" "fmt" "net" @@ -145,6 +146,30 @@ func (c *Connection) Close() { } } +// PeerID returns the Peer ID for the remote peer +func (c *Connection) PeerID() ([32]byte, error) { + nullBytes := [32]byte{} + err := c.ensureConnection() + if err != nil { + return nullBytes, err + } + + netConn := c.conn.NetConn() + tlsConn, ok := netConn.(*tls.Conn) + if !ok { + return nullBytes, fmt.Errorf("could not get tls.Conn from websocket") + } + + // Access the connection state + state := tlsConn.ConnectionState() + if len(state.PeerCertificates) == 0 { + return nullBytes, fmt.Errorf("No certificates in chain") + } + + cert := state.PeerCertificates[0] + return sha256.Sum256(cert.Raw), nil +} + // Handshake performs the RPC handshake. This should be called before any other method func (c *Connection) Handshake() error { // Handshake From 38af161c36212146e1b767cf30adbbcda21c3b1a Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 28 May 2024 14:57:52 -0500 Subject: [PATCH 2/2] Fix lint --- pkg/peerprotocol/connection.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/peerprotocol/connection.go b/pkg/peerprotocol/connection.go index 4f3bc5f..63d4d42 100644 --- a/pkg/peerprotocol/connection.go +++ b/pkg/peerprotocol/connection.go @@ -163,7 +163,7 @@ func (c *Connection) PeerID() ([32]byte, error) { // Access the connection state state := tlsConn.ConnectionState() if len(state.PeerCertificates) == 0 { - return nullBytes, fmt.Errorf("No certificates in chain") + return nullBytes, fmt.Errorf("no certificates in chain") } cert := state.PeerCertificates[0]