Skip to content

Commit

Permalink
Add PeerID function to get the ID of the remote peer
Browse files Browse the repository at this point in the history
  • Loading branch information
cmmarslender committed May 28, 2024
1 parent 5be5193 commit 3899c50
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pkg/peerprotocol/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package peerprotocol

import (
"context"
"crypto/sha256"
"crypto/tls"
"fmt"
"net"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 3899c50

Please sign in to comment.