From f4d376d7af6878a3ca90c68d52fda9934b11d0c1 Mon Sep 17 00:00:00 2001 From: Jim Posen Date: Tue, 8 Aug 2017 15:55:51 -0700 Subject: [PATCH] peer: Improve address sampling in PushAddrMsg. This changes fixes shuffling algorithm in PushAddrMsg to select a uniformly random subset of the given addresses using Fisher-Yates. --- peer/peer.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/peer/peer.go b/peer/peer.go index 0d4a932a..9c77ff1b 100644 --- a/peer/peer.go +++ b/peer/peer.go @@ -849,21 +849,22 @@ func (p *Peer) localVersionMsg() (*wire.MsgVersion, error) { // // This function is safe for concurrent access. func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.NetAddress, error) { + addressCount := len(addresses) // Nothing to send. - if len(addresses) == 0 { + if addressCount == 0 { return nil, nil } msg := wire.NewMsgAddr() - msg.AddrList = make([]*wire.NetAddress, len(addresses)) + msg.AddrList = make([]*wire.NetAddress, addressCount) copy(msg.AddrList, addresses) // Randomize the addresses sent if there are more than the maximum allowed. - if len(msg.AddrList) > wire.MaxAddrPerMsg { + if addressCount > wire.MaxAddrPerMsg { // Shuffle the address list. - for i := range msg.AddrList { - j := rand.Intn(i + 1) + for i := 0; i < wire.MaxAddrPerMsg; i++ { + j := i + rand.Intn(addressCount-i) msg.AddrList[i], msg.AddrList[j] = msg.AddrList[j], msg.AddrList[i] }