github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/p2p/discv5/topic_test.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package discv5 13 14 import ( 15 "encoding/binary" 16 "testing" 17 "time" 18 19 "github.com/Sberex/go-sberex/common" 20 "github.com/Sberex/go-sberex/common/mclock" 21 ) 22 23 func TestTopicRadius(t *testing.T) { 24 now := mclock.Now() 25 topic := Topic("qwerty") 26 rad := newTopicRadius(topic) 27 targetRad := (^uint64(0)) / 100 28 29 waitFn := func(addr common.Hash) time.Duration { 30 prefix := binary.BigEndian.Uint64(addr[0:8]) 31 dist := prefix ^ rad.topicHashPrefix 32 relDist := float64(dist) / float64(targetRad) 33 relTime := (1 - relDist/2) * 2 34 if relTime < 0 { 35 relTime = 0 36 } 37 return time.Duration(float64(targetWaitTime) * relTime) 38 } 39 40 bcnt := 0 41 cnt := 0 42 var sum float64 43 for cnt < 100 { 44 addr := rad.nextTarget(false).target 45 wait := waitFn(addr) 46 ticket := &ticket{ 47 topics: []Topic{topic}, 48 regTime: []mclock.AbsTime{mclock.AbsTime(wait)}, 49 node: &Node{nodeNetGuts: nodeNetGuts{sha: addr}}, 50 } 51 rad.adjustWithTicket(now, addr, ticketRef{ticket, 0}) 52 if rad.radius != maxRadius { 53 cnt++ 54 sum += float64(rad.radius) 55 } else { 56 bcnt++ 57 if bcnt > 500 { 58 t.Errorf("Radius did not converge in 500 iterations") 59 } 60 } 61 } 62 avgRel := sum / float64(cnt) / float64(targetRad) 63 if avgRel > 1.05 || avgRel < 0.95 { 64 t.Errorf("Average/target ratio is too far from 1 (%v)", avgRel) 65 } 66 }