github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/swarm/network/simulation/bucket.go (about) 1 // Copyright 2018 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 simulation 18 19 import "github.com/ethereum/go-ethereum/p2p/enode" 20 21 // BucketKey is the type that should be used for keys in simulation buckets. 22 type BucketKey string 23 24 // NodeItem returns an item set in ServiceFunc function for a particular node. 25 func (s *Simulation) NodeItem(id enode.ID, key interface{}) (value interface{}, ok bool) { 26 s.mu.Lock() 27 defer s.mu.Unlock() 28 29 if _, ok := s.buckets[id]; !ok { 30 return nil, false 31 } 32 return s.buckets[id].Load(key) 33 } 34 35 // SetNodeItem sets a new item associated with the node with provided NodeID. 36 // Buckets should be used to avoid managing separate simulation global state. 37 func (s *Simulation) SetNodeItem(id enode.ID, key interface{}, value interface{}) { 38 s.mu.Lock() 39 defer s.mu.Unlock() 40 41 s.buckets[id].Store(key, value) 42 } 43 44 // NodesItems returns a map of items from all nodes that are all set under the 45 // same BucketKey. 46 func (s *Simulation) NodesItems(key interface{}) (values map[enode.ID]interface{}) { 47 s.mu.RLock() 48 defer s.mu.RUnlock() 49 50 ids := s.NodeIDs() 51 values = make(map[enode.ID]interface{}, len(ids)) 52 for _, id := range ids { 53 if _, ok := s.buckets[id]; !ok { 54 continue 55 } 56 if v, ok := s.buckets[id].Load(key); ok { 57 values[id] = v 58 } 59 } 60 return values 61 } 62 63 // UpNodesItems returns a map of items with the same BucketKey from all nodes that are up. 64 func (s *Simulation) UpNodesItems(key interface{}) (values map[enode.ID]interface{}) { 65 s.mu.RLock() 66 defer s.mu.RUnlock() 67 68 ids := s.UpNodeIDs() 69 values = make(map[enode.ID]interface{}) 70 for _, id := range ids { 71 if _, ok := s.buckets[id]; !ok { 72 continue 73 } 74 if v, ok := s.buckets[id].Load(key); ok { 75 values[id] = v 76 } 77 } 78 return values 79 }