Skip to content

Commit

Permalink
webrtc: add certhashes to discovered webrtc addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
sukunrt committed Oct 13, 2023
1 parent 65825b5 commit 9f660b1
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
17 changes: 17 additions & 0 deletions p2p/host/basic/basic_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/libp2p/go-libp2p/p2p/protocol/holepunch"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"
"github.com/libp2p/go-libp2p/p2p/protocol/ping"
libp2pwebrtc "github.com/libp2p/go-libp2p/p2p/transport/webrtc"
libp2pwebtransport "github.com/libp2p/go-libp2p/p2p/transport/webtransport"
"github.com/prometheus/client_golang/prometheus"

Expand Down Expand Up @@ -801,6 +802,22 @@ func (h *BasicHost) Addrs() []ma.Multiaddr {
addrs[i] = addrWithCerthash
}
}

for i, addr := range addrs {
if ok, n := libp2pwebrtc.IsWebRTCDirectMultiaddr(addr); ok && n == 0 {
t := s.TransportForListening(addr)
tpt, ok := t.(addCertHasher)
if !ok {
continue
}
addrWithCerthash, added := tpt.AddCertHashes(addr)
if !added {
log.Debug("Couldn't add certhashes to webrtc-direct multiaddress")
continue
}
addrs[i] = addrWithCerthash
}
}
return addrs
}

Expand Down
50 changes: 50 additions & 0 deletions p2p/transport/webrtc/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,56 @@ func (t *WebRTCTransport) RemoveMux(mux *udpmux.UDPMux) {
t.v6Reuse.Delete(mux)
}

func (t *WebRTCTransport) AddCertHashes(addr ma.Multiaddr) (ma.Multiaddr, bool) {
listenerFingerprint, err := t.getCertificateFingerprint()
if err != nil {
return nil, false
}

encodedLocalFingerprint, err := encodeDTLSFingerprint(listenerFingerprint)
if err != nil {
return nil, false
}

certComp, err := ma.NewComponent(ma.ProtocolWithCode(ma.P_CERTHASH).Name, encodedLocalFingerprint)
if err != nil {
return nil, false
}

return addr.Encapsulate(certComp), true
}

// IsWebRTCDirectMultiaddr returns whether addr is a /webrtc-direct multiaddr and the number of
// certhashes found
func IsWebRTCDirectMultiaddr(addr ma.Multiaddr) (bool, int) {
const (
init = iota
foundUDP
foundWebRTCDirect
)
state := init
certhashCount := 0

ma.ForEach(addr, func(c ma.Component) bool {
switch c.Protocol().Code {
case ma.P_UDP:
if state == init {
state = foundUDP
}
case ma.P_WEBRTC_DIRECT:
if state == foundUDP {
state = foundWebRTCDirect
}
case ma.P_CERTHASH:
if state == foundWebRTCDirect {
certhashCount++
}
}
return true
})
return state == foundWebRTCDirect, certhashCount
}

type fakeStreamConn struct{ *stream }

func (fakeStreamConn) LocalAddr() net.Addr { return nil }
Expand Down

0 comments on commit 9f660b1

Please sign in to comment.