Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(ARCO-212): Send GETDATA message for transaction to random connected peer #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
37 changes: 25 additions & 12 deletions peer_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package p2p
import (
"context"
"log/slog"
"math/rand"
"sort"
"sync"
"time"
Expand Down Expand Up @@ -128,23 +129,17 @@ func (pm *PeerManager) AnnounceTransaction(txHash *chainhash.Hash, peers []PeerI
}

func (pm *PeerManager) RequestTransaction(txHash *chainhash.Hash) PeerI {
// send to the first found peer that is connected
var sendToPeer PeerI
for _, peer := range pm.GetAnnouncedPeers() {
if peer.Connected() {
sendToPeer = peer
break
}
}
pm.mu.RLock()
defer pm.mu.RUnlock()

// we don't have any connected peers
if sendToPeer == nil {
peer := pm.GetRandomConnectedPeer()
if peer == nil {
return nil
}

sendToPeer.RequestTransaction(txHash)
peer.RequestTransaction(txHash)

return sendToPeer
return peer
}

func (pm *PeerManager) AnnounceBlock(blockHash *chainhash.Hash, peers []PeerI) []PeerI {
Expand Down Expand Up @@ -179,6 +174,24 @@ func (pm *PeerManager) RequestBlock(blockHash *chainhash.Hash) PeerI {
return sendToPeer
}

func (pm *PeerManager) GetRandomConnectedPeer() PeerI {
pm.mu.RLock()
defer pm.mu.RUnlock()

connectedPeers := make([]PeerI, 0, len(pm.peers))
for _, peer := range pm.peers {
if peer.Connected() {
connectedPeers = append(connectedPeers, peer)
}
}

if len(connectedPeers) == 0 {
return nil
}

return connectedPeers[rand.Intn(len(connectedPeers))]
}

func (pm *PeerManager) GetAnnouncedPeers() []PeerI {
pm.mu.RLock()
defer pm.mu.RUnlock()
Expand Down