github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/p2p/protocol.go (about)

     1  package p2p
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/quickchainproject/quickchain/p2p/discover"
     7  )
     8  
     9  // Protocol represents a P2P subprotocol implementation.
    10  type Protocol struct {
    11  	// Name should contain the official protocol name,
    12  	// often a three-letter word.
    13  	Name string
    14  
    15  	// Version should contain the version number of the protocol.
    16  	Version uint
    17  
    18  	// Length should contain the number of message codes used
    19  	// by the protocol.
    20  	Length uint64
    21  
    22  	// Run is called in a new groutine when the protocol has been
    23  	// negotiated with a peer. It should read and write messages from
    24  	// rw. The Payload for each message must be fully consumed.
    25  	//
    26  	// The peer connection is closed when Start returns. It should return
    27  	// any protocol-level error (such as an I/O error) that is
    28  	// encountered.
    29  	Run func(peer *Peer, rw MsgReadWriter) error
    30  
    31  	// NodeInfo is an optional helper method to retrieve protocol specific metadata
    32  	// about the host node.
    33  	NodeInfo func() interface{}
    34  
    35  	// PeerInfo is an optional helper method to retrieve protocol specific metadata
    36  	// about a certain peer in the network. If an info retrieval function is set,
    37  	// but returns nil, it is assumed that the protocol handshake is still running.
    38  	PeerInfo func(id discover.NodeID) interface{}
    39  }
    40  
    41  func (p Protocol) cap() Cap {
    42  	return Cap{p.Name, p.Version}
    43  }
    44  
    45  // Cap is the structure of a peer capability.
    46  type Cap struct {
    47  	Name    string
    48  	Version uint
    49  }
    50  
    51  func (cap Cap) RlpData() interface{} {
    52  	return []interface{}{cap.Name, cap.Version}
    53  }
    54  
    55  func (cap Cap) String() string {
    56  	return fmt.Sprintf("%s/%d", cap.Name, cap.Version)
    57  }
    58  
    59  type capsByNameAndVersion []Cap
    60  
    61  func (cs capsByNameAndVersion) Len() int      { return len(cs) }
    62  func (cs capsByNameAndVersion) Swap(i, j int) { cs[i], cs[j] = cs[j], cs[i] }
    63  func (cs capsByNameAndVersion) Less(i, j int) bool {
    64  	return cs[i].Name < cs[j].Name || (cs[i].Name == cs[j].Name && cs[i].Version < cs[j].Version)
    65  }