decred.org/dcrdex@v1.0.5/tatanka/tanka/peer.go (about)

     1  // This code is available on the terms of the project LICENSE.md file,
     2  // also available online at https://blueoakcouncil.org/license/1.0.0.
     3  
     4  package tanka
     5  
     6  import (
     7  	"encoding/hex"
     8  
     9  	"decred.org/dcrdex/dex/msgjson"
    10  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
    11  )
    12  
    13  const PeerIDLength = secp256k1.PubKeyBytesLenCompressed
    14  
    15  // PeerID is the primary identifier for both clients and servers on Tatanka
    16  // Mesh. The PeerID is the compressed-format serialized secp256k1.PublicKey.
    17  type PeerID [PeerIDLength]byte
    18  
    19  func (p PeerID) String() string {
    20  	return hex.EncodeToString(p[:])
    21  }
    22  
    23  // func (p *PeerID) MarshalJSON() ([]byte, error) {
    24  // 	return json.Marshal(hex.EncodeToString((*p)[:]))
    25  // }
    26  
    27  // func (p *PeerID) UnmarshalJSON(encHex []byte) (err error) {
    28  // 	if len(encHex) < 2 {
    29  // 		return fmt.Errorf("unmarshalled bytes, %q, not valid", string(encHex))
    30  // 	}
    31  // 	if encHex[0] != '"' || encHex[len(encHex)-1] != '"' {
    32  // 		return fmt.Errorf("unmarshalled bytes, %q, not quoted", string(encHex))
    33  // 	}
    34  // 	// DecodeString over-allocates by at least double, and it makes a copy.
    35  // 	src := encHex[1 : len(encHex)-1]
    36  // 	if len(src) != PeerIDLength*2 {
    37  // 		return fmt.Errorf("unmarshalled bytes of wrong length %d", len(src))
    38  // 	}
    39  // 	dst := make([]byte, len(src)/2)
    40  // 	_, err = hex.Decode(dst, src)
    41  // 	if err == nil {
    42  // 		var id PeerID
    43  // 		copy(id[:], dst)
    44  // 		*p = id
    45  // 	}
    46  // 	return err
    47  // }
    48  
    49  // Peer is a network peer, which could be a client or a server node.
    50  type Peer struct {
    51  	ID         PeerID               `json:"-"`
    52  	PubKey     *secp256k1.PublicKey `json:"-"`
    53  	Bonds      []*Bond              `json:"-"`
    54  	Reputation *Reputation          `json:"reputation"`
    55  }
    56  
    57  // BondTier sums the tier of the current bond set.
    58  func (p *Peer) BondTier() (tier uint64) {
    59  	for _, b := range p.Bonds {
    60  		tier += b.Strength
    61  	}
    62  	return
    63  }
    64  
    65  // Sender is an interface that is implemented by all network connections.
    66  type Sender interface {
    67  	Send(*msgjson.Message) error
    68  	SendRaw([]byte) error
    69  	Request(msg *msgjson.Message, respHandler func(*msgjson.Message)) error
    70  	RequestRaw(msgID uint64, rawMsg []byte, respHandler func(*msgjson.Message)) error
    71  	SetPeerID(PeerID)
    72  	PeerID() PeerID
    73  	Disconnect()
    74  }