Skip to content

Commit

Permalink
refactor(ARCO-212): Send GETDATA message for transaction to random co…
Browse files Browse the repository at this point in the history
…nnected peer
  • Loading branch information
boecklim committed Nov 26, 2024
1 parent 08a38f5 commit 8e249b9
Showing 1 changed file with 25 additions and 12 deletions.
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

0 comments on commit 8e249b9

Please sign in to comment.