github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/swarm/network/simulation/bucket.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 12:09:47</date> 10 //</624342673108504576> 11 12 13 package simulation 14 15 import ( 16 "github.com/ethereum/go-ethereum/p2p/discover" 17 ) 18 19 //BucketKey是模拟存储桶中的键应该使用的类型。 20 type BucketKey string 21 22 //nodeItem返回在servicefunc函数中为particualar节点设置的项。 23 func (s *Simulation) NodeItem(id discover.NodeID, key interface{}) (value interface{}, ok bool) { 24 s.mu.Lock() 25 defer s.mu.Unlock() 26 27 if _, ok := s.buckets[id]; !ok { 28 return nil, false 29 } 30 return s.buckets[id].Load(key) 31 } 32 33 //setnodeitem设置与提供了nodeid的节点关联的新项。 34 //应使用存储桶来避免管理单独的模拟全局状态。 35 func (s *Simulation) SetNodeItem(id discover.NodeID, key interface{}, value interface{}) { 36 s.mu.Lock() 37 defer s.mu.Unlock() 38 39 s.buckets[id].Store(key, value) 40 } 41 42 //nodes items返回在 43 //同样的BucketKey。 44 func (s *Simulation) NodesItems(key interface{}) (values map[discover.NodeID]interface{}) { 45 s.mu.RLock() 46 defer s.mu.RUnlock() 47 48 ids := s.NodeIDs() 49 values = make(map[discover.NodeID]interface{}, len(ids)) 50 for _, id := range ids { 51 if _, ok := s.buckets[id]; !ok { 52 continue 53 } 54 if v, ok := s.buckets[id].Load(key); ok { 55 values[id] = v 56 } 57 } 58 return values 59 } 60 61 //up nodes items从所有向上的节点返回具有相同bucketkey的项的映射。 62 func (s *Simulation) UpNodesItems(key interface{}) (values map[discover.NodeID]interface{}) { 63 s.mu.RLock() 64 defer s.mu.RUnlock() 65 66 ids := s.UpNodeIDs() 67 values = make(map[discover.NodeID]interface{}) 68 for _, id := range ids { 69 if _, ok := s.buckets[id]; !ok { 70 continue 71 } 72 if v, ok := s.buckets[id].Load(key); ok { 73 values[id] = v 74 } 75 } 76 return values 77 } 78