github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/lnp2p/peer.go (about) 1 package lnp2p 2 3 import ( 4 "github.com/mit-dci/lit/crypto/koblitz" 5 "github.com/mit-dci/lit/lncore" 6 "github.com/mit-dci/lit/lndc" 7 ) 8 9 // A Peer is a remote client that's somehow connected to us. 10 type Peer struct { 11 lnaddr lncore.LnAddr 12 nickname *string 13 conn *lndc.Conn 14 idpubkey pubkey 15 16 idx *uint32 // deprecated 17 pmgr *PeerManager 18 } 19 20 // GetIdx is a compatibility function. 21 func (p *Peer) GetIdx() uint32 { 22 if p.idx == nil { 23 return 0 24 } 25 return *p.idx 26 } 27 28 // GetNickname returns the nickname, or an empty string if unset. 29 func (p *Peer) GetNickname() string { 30 if p.nickname == nil { 31 return "" 32 } 33 return *p.nickname 34 } 35 36 // SetNickname sets the peer's nickname. 37 func (p *Peer) SetNickname(name string) { 38 p.nickname = &name 39 if name == "" { 40 p.nickname = nil 41 } 42 } 43 44 // GetLnAddr returns the lightning network address for this peer. 45 func (p *Peer) GetLnAddr() lncore.LnAddr { 46 return p.lnaddr 47 } 48 49 // GetRemoteAddr does something. 50 func (p *Peer) GetRemoteAddr() string { 51 return p.conn.RemoteAddr().String() 52 } 53 54 // GetPubkey gets the public key for the user. 55 func (p *Peer) GetPubkey() koblitz.PublicKey { 56 return *p.idpubkey 57 } 58 59 const prettyLnAddrPrefixLen = 10 60 61 // GetPrettyName returns a more human-readable name, such as the nickname if 62 // available or a trucated version of the LN address otherwise. 63 func (p *Peer) GetPrettyName() string { 64 if p.nickname != nil { 65 return *p.nickname 66 } 67 68 return string(p.GetLnAddr()[:prettyLnAddrPrefixLen]) + "~" 69 } 70 71 // SendQueuedMessage adds the message to the queue to be sent to this peer. 72 // This queue is shared across all peers. 73 func (p *Peer) SendQueuedMessage(msg Message) error { 74 return p.pmgr.queueMessageToPeer(p, msg, nil) 75 } 76 77 // SendImmediateMessage adds a message to the queue but waits for the message to 78 // be sent before returning, also returning errors that might have occurred when 79 // sending the message, like the peer disconnecting. 80 func (p *Peer) SendImmediateMessage(msg Message) error { 81 var err error 82 errchan := make(chan error) 83 84 // Send it to the queue, as above. 85 err = p.pmgr.queueMessageToPeer(p, msg, &errchan) 86 if err != nil { 87 return err 88 } 89 90 // Catches errors if there are any. 91 err = <-errchan 92 if err != nil { 93 return err 94 } 95 96 return nil 97 } 98 99 // IntoPeerInfo generates the PeerInfo DB struct for the Peer. 100 func (p *Peer) IntoPeerInfo() lncore.PeerInfo { 101 var raddr string 102 if p.conn != nil { 103 raddr = p.conn.RemoteAddr().String() 104 } 105 return lncore.PeerInfo{ 106 LnAddr: &p.lnaddr, 107 Nickname: p.nickname, 108 NetAddr: &raddr, 109 } 110 }