github.com/MetalBlockchain/metalgo@v1.11.9/utils/ips/claimed_ip_port.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package ips
     5  
     6  import (
     7  	"net"
     8  	"net/netip"
     9  
    10  	"github.com/MetalBlockchain/metalgo/ids"
    11  	"github.com/MetalBlockchain/metalgo/staking"
    12  	"github.com/MetalBlockchain/metalgo/utils/hashing"
    13  	"github.com/MetalBlockchain/metalgo/utils/wrappers"
    14  )
    15  
    16  const (
    17  	// Certificate length, signature length, IP, timestamp, tx ID
    18  	baseIPCertDescLen = 2*wrappers.IntLen + net.IPv6len + wrappers.ShortLen + wrappers.LongLen + ids.IDLen
    19  	preimageLen       = ids.IDLen + wrappers.LongLen
    20  )
    21  
    22  // A self contained proof that a peer is claiming ownership of an IPPort at a
    23  // given time.
    24  type ClaimedIPPort struct {
    25  	// The peer's certificate.
    26  	Cert *staking.Certificate
    27  	// The peer's claimed IP and port.
    28  	AddrPort netip.AddrPort
    29  	// The time the peer claimed to own this IP and port.
    30  	Timestamp uint64
    31  	// [Cert]'s signature over the IPPort and timestamp.
    32  	// This is used in the networking library to ensure that this IPPort was
    33  	// actually claimed by the peer in question, and not by a malicious peer
    34  	// trying to get us to dial bogus IPPorts.
    35  	Signature []byte
    36  	// NodeID derived from the peer certificate.
    37  	NodeID ids.NodeID
    38  	// GossipID derived from the nodeID and timestamp.
    39  	GossipID ids.ID
    40  }
    41  
    42  func NewClaimedIPPort(
    43  	cert *staking.Certificate,
    44  	ipPort netip.AddrPort,
    45  	timestamp uint64,
    46  	signature []byte,
    47  ) *ClaimedIPPort {
    48  	ip := &ClaimedIPPort{
    49  		Cert:      cert,
    50  		AddrPort:  ipPort,
    51  		Timestamp: timestamp,
    52  		Signature: signature,
    53  		NodeID:    ids.NodeIDFromCert(cert),
    54  	}
    55  
    56  	packer := wrappers.Packer{
    57  		Bytes: make([]byte, preimageLen),
    58  	}
    59  	packer.PackFixedBytes(ip.NodeID[:])
    60  	packer.PackLong(timestamp)
    61  	ip.GossipID = hashing.ComputeHash256Array(packer.Bytes)
    62  	return ip
    63  }
    64  
    65  // Returns the approximate size of the binary representation of this ClaimedIPPort.
    66  func (i *ClaimedIPPort) Size() int {
    67  	return baseIPCertDescLen + len(i.Cert.Raw) + len(i.Signature)
    68  }