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