Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 6 additions & 23 deletions device/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package device

import (
"container/list"
"encoding/base64"
"errors"
"sync"
"sync/atomic"
Expand All @@ -24,6 +25,7 @@ type Peer struct {
txBytes atomic.Uint64 // bytes send to peer (endpoint)
rxBytes atomic.Uint64 // bytes received from peer
lastHandshakeNano atomic.Int64 // nano seconds since epoch
string string // cached [Peer.String]

endpoint struct {
sync.Mutex
Expand Down Expand Up @@ -107,6 +109,9 @@ func (device *Device) NewPeer(pk NoisePublicKey) (*Peer, error) {
// init timers
peer.timersInit()

base64Key := base64.StdEncoding.EncodeToString(pk[:])
peer.string = "peer(" + base64Key[0:4] + "…" + base64Key[39:43] + ")"

// add
device.peers.keyMap[pk] = peer

Expand Down Expand Up @@ -145,29 +150,7 @@ func (peer *Peer) SendBuffers(buffers [][]byte) error {
}

func (peer *Peer) String() string {
// The awful goo that follows is identical to:
//
// base64Key := base64.StdEncoding.EncodeToString(peer.handshake.remoteStatic[:])
// abbreviatedKey := base64Key[0:4] + "…" + base64Key[39:43]
// return fmt.Sprintf("peer(%s)", abbreviatedKey)
//
// except that it is considerably more efficient.
src := peer.handshake.remoteStatic
b64 := func(input byte) byte {
return input + 'A' + byte(((25-int(input))>>8)&6) - byte(((51-int(input))>>8)&75) - byte(((61-int(input))>>8)&15) + byte(((62-int(input))>>8)&3)
}
b := []byte("peer(____…____)")
const first = len("peer(")
const second = len("peer(____…")
b[first+0] = b64((src[0] >> 2) & 63)
b[first+1] = b64(((src[0] << 4) | (src[1] >> 4)) & 63)
b[first+2] = b64(((src[1] << 2) | (src[2] >> 6)) & 63)
b[first+3] = b64(src[2] & 63)
b[second+0] = b64(src[29] & 63)
b[second+1] = b64((src[30] >> 2) & 63)
b[second+2] = b64(((src[30] << 4) | (src[31] >> 4)) & 63)
b[second+3] = b64((src[31] << 2) & 63)
return string(b)
return peer.string
}

func (peer *Peer) Start() {
Expand Down