Skip to content

Commit

Permalink
Add PeerInfo() to get a list of connected spv peers
Browse files Browse the repository at this point in the history
  • Loading branch information
beansgum committed Dec 28, 2020
1 parent 3ba4434 commit ea7f606
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
46 changes: 46 additions & 0 deletions sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package dcrlibwallet

import (
"context"
"encoding/json"
"fmt"
"net"
"sort"
"strings"
"sync"

Expand Down Expand Up @@ -37,6 +40,8 @@ type syncData struct {

// reading/writing of properties of this struct are protected by syncData.mu.
type activeSyncData struct {
syncer *spv.Syncer

syncStage int32

cfiltersFetchProgress CFiltersFetchProgressReport
Expand Down Expand Up @@ -235,6 +240,7 @@ func (mw *MultiWallet) SpvSync() error {
mw.syncData.syncing = true
mw.syncData.cancelSync = cancel
mw.syncData.syncCanceled = make(chan struct{})
mw.syncData.syncer = syncer
mw.syncData.mu.Unlock()

for _, listener := range mw.syncProgressListeners() {
Expand Down Expand Up @@ -358,6 +364,46 @@ func (mw *MultiWallet) ConnectedPeers() int32 {
return mw.syncData.connectedPeers
}

func (mw *MultiWallet) PeerInfoRaw() ([]PeerInfo, error) {
if !mw.IsConnectedToDecredNetwork() {
return nil, errors.New(ErrNotConnected)
}

syncer := mw.syncData.syncer

infos := make([]PeerInfo, 0, len(syncer.GetRemotePeers()))
for _, rp := range syncer.GetRemotePeers() {
info := PeerInfo{
ID: int32(rp.ID()),
Addr: rp.RemoteAddr().String(),
AddrLocal: rp.LocalAddr().String(),
Services: fmt.Sprintf("%08d", uint64(rp.Services())),
Version: rp.Pver(),
SubVer: rp.UA(),
StartingHeight: int64(rp.InitialHeight()),
BanScore: int32(rp.BanScore()),
}

infos = append(infos, info)
}

sort.Slice(infos, func(i, j int) bool {
return infos[i].ID < infos[j].ID
})

return infos, nil
}

func (mw *MultiWallet) PeerInfo() (string, error) {
infos, err := mw.PeerInfoRaw()
if err != nil {
return "", err
}

result, _ := json.Marshal(infos)
return string(result), nil
}

func (mw *MultiWallet) GetBestBlock() *BlockInfo {
var bestBlock int32 = -1
var blockInfo *BlockInfo
Expand Down
11 changes: 11 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ type Accounts struct {
CurrentBlockHeight int32
}

type PeerInfo struct {
ID int32 `json:"id"`
Addr string `json:"addr"`
AddrLocal string `json:"addr_local"`
Services string `json:"services"`
Version uint32 `json:"version"`
SubVer string `json:"sub_ver"`
StartingHeight int64 `json:"starting_height"`
BanScore int32 `json:"ban_score"`
}

/** begin sync-related types */

type SyncProgressListener interface {
Expand Down

0 comments on commit ea7f606

Please sign in to comment.