Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PeerID function to get the ID of the remote peer #126

Merged
merged 2 commits into from
May 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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