Add component and use manet.FromNetAddr

This commit is contained in:
Marco Munizaga 2022-06-16 10:15:03 -07:00
parent a7f238e4b0
commit bdfc1932c4

View File

@ -2,11 +2,11 @@ package canonicallog
import (
"net"
"strings"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
var log = logging.WithSkip(logging.Logger("canonical-log"), 1)
@ -14,37 +14,18 @@ var log = logging.WithSkip(logging.Logger("canonical-log"), 1)
// LogMisbehavingPeer is the canonical way to log a misbehaving peer.
// Protocols should use this to identify a misbehaving peer to allow the end
// user to easily identify these nodes across protocols and libp2p.
func LogMisbehavingPeer(p peer.ID, peerAddr multiaddr.Multiaddr, err error, msg string) {
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s err=%v msg=%s", p, peerAddr.String(), err, msg)
func LogMisbehavingPeer(p peer.ID, peerAddr multiaddr.Multiaddr, component string, err error, msg string) {
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s", p, peerAddr.String(), component, err, msg)
}
// LogMisbehavingPeer is the canonical way to log a misbehaving peer.
// Protocols should use this to identify a misbehaving peer to allow the end
// user to easily identify these nodes across protocols and libp2p.
func LogMisbehavingPeerNetAddr(p peer.ID, peerAddr net.Addr, originalErr error, msg string) {
ipStrandPort := strings.Split(peerAddr.String(), ":")
ip := net.ParseIP(ipStrandPort[0])
if ip == nil {
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s err=%v msg=%s", p, originalErr, msg)
return
func LogMisbehavingPeerNetAddr(p peer.ID, peerAddr net.Addr, component string, originalErr error, msg string) {
ma, err := manet.FromNetAddr(peerAddr)
if err != nil {
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s netAddr=%s component=%s err=%v msg=%s", p, peerAddr.String(), component, originalErr, msg)
}
proto := peerAddr.Network()
var stringBuilder strings.Builder
if ip4 := ip.To4(); ip4 != nil {
stringBuilder.WriteString("/ip4/")
stringBuilder.WriteString(ip4.String())
} else {
stringBuilder.WriteString("/ip6/")
stringBuilder.WriteString(ip.String())
}
stringBuilder.WriteString("/")
stringBuilder.WriteString(proto)
stringBuilder.WriteString("/")
stringBuilder.WriteString(ipStrandPort[1])
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s err=%v msg=%s", p, stringBuilder.String(), originalErr, msg)
log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s", p, ma, component, originalErr, msg)
}