From d5ec248691a2d51f91a9972839186e6220665fcb Mon Sep 17 00:00:00 2001 From: terence tsao Date: Mon, 25 Jan 2021 13:27:30 -0800 Subject: [PATCH] Rename getter functions to be idiomatic (#8320) * Rename getter functions * Rename new * Radek's feedback Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com> --- .../blockchain/receive_attestation.go | 2 +- beacon-chain/core/blocks/signature.go | 8 +++--- beacon-chain/core/helpers/signing_root.go | 6 ++-- beacon-chain/db/kv/blocks.go | 28 +++++++++---------- beacon-chain/main.go | 2 +- beacon-chain/node/node.go | 2 +- beacon-chain/p2p/discovery.go | 2 +- beacon-chain/p2p/fork.go | 6 ++-- beacon-chain/p2p/fork_test.go | 8 +++--- beacon-chain/p2p/options.go | 2 +- beacon-chain/p2p/peers/benchmark_test.go | 2 +- beacon-chain/p2p/peers/status.go | 6 ++-- beacon-chain/p2p/subnets.go | 8 +++--- beacon-chain/p2p/utils.go | 4 +-- beacon-chain/rpc/beacon/attestations.go | 2 +- beacon-chain/rpc/node/server.go | 2 +- beacon-chain/rpc/node/server_test.go | 2 +- beacon-chain/rpc/nodev1/node.go | 4 +-- beacon-chain/rpc/nodev1/node_test.go | 2 +- beacon-chain/rpc/validator/assignments.go | 2 +- beacon-chain/rpc/validator/status.go | 4 +-- beacon-chain/state/state_trie.go | 2 +- beacon-chain/state/stateutil/arrays.go | 4 +-- beacon-chain/state/stateutil/trie_helpers.go | 4 +-- .../sync/initial-sync/blocks_fetcher.go | 4 +-- .../sync/initial-sync/blocks_fetcher_peers.go | 4 +-- beacon-chain/sync/subscriber.go | 4 +-- endtoend/components/beacon_node.go | 4 +-- endtoend/endtoend_test.go | 2 +- endtoend/evaluators/metrics.go | 10 +++---- endtoend/helpers/epochTimer.go | 4 +-- fuzz/testing/beacon_fuzz_states.go | 4 +-- fuzz/testing/beacon_fuzz_states_test.go | 2 +- shared/htrutils/merkleize.go | 12 ++++---- shared/htrutils/merkleize_test.go | 2 +- shared/iputils/external_ip.go | 10 +++---- shared/keystore/keystore.go | 4 +-- shared/prereq/prereq.go | 4 +-- shared/prometheus/logrus_collector_test.go | 8 +++--- shared/slotutil/slotticker.go | 8 +++--- shared/slotutil/slotticker_test.go | 4 +-- shared/tracing/tracer.go | 2 +- shared/version/version.go | 14 +++++----- slasher/main.go | 2 +- slasher/node/node.go | 2 +- tools/analyzers/errcheck/analyzer.go | 10 +++---- tools/analyzers/slicedirect/testdata/slice.go | 4 +-- tools/bootnode/bootnode.go | 2 +- tools/deployContract/deployContract.go | 2 +- tools/drainContracts/drainContracts.go | 2 +- tools/eth1exporter/main.go | 6 ++-- tools/pcli/main.go | 2 +- validator/client/validator.go | 2 +- validator/client/wait_for_activation.go | 10 +++---- validator/main.go | 2 +- validator/node/node.go | 2 +- validator/rpc/health.go | 2 +- .../standard-protection-format/export.go | 8 +++--- .../standard-protection-format/export_test.go | 8 +++--- 59 files changed, 143 insertions(+), 143 deletions(-) diff --git a/beacon-chain/blockchain/receive_attestation.go b/beacon-chain/blockchain/receive_attestation.go index b5f2f848199..6e629a9b974 100644 --- a/beacon-chain/blockchain/receive_attestation.go +++ b/beacon-chain/blockchain/receive_attestation.go @@ -118,7 +118,7 @@ func (s *Service) processAttestationsRoutine(subscribedToStateEvents chan struct log.Warn("Genesis time received, now available to process attestations") } - st := slotutil.GetSlotTicker(s.genesisTime, params.BeaconConfig().SecondsPerSlot) + st := slotutil.NewSlotTicker(s.genesisTime, params.BeaconConfig().SecondsPerSlot) for { select { case <-s.ctx.Done(): diff --git a/beacon-chain/core/blocks/signature.go b/beacon-chain/core/blocks/signature.go index 839448a9659..f4a3bb57e8a 100644 --- a/beacon-chain/core/blocks/signature.go +++ b/beacon-chain/core/blocks/signature.go @@ -15,7 +15,7 @@ import ( ) // retrieves the signature set from the raw data, public key,signature and domain provided. -func retrieveSignatureSet(signedData, pub, signature, domain []byte) (*bls.SignatureSet, error) { +func signatureSet(signedData, pub, signature, domain []byte) (*bls.SignatureSet, error) { publicKey, err := bls.PublicKeyFromBytes(pub) if err != nil { return nil, errors.Wrap(err, "could not convert bytes to public key") @@ -37,7 +37,7 @@ func retrieveSignatureSet(signedData, pub, signature, domain []byte) (*bls.Signa // verifies the signature from the raw data, public key and domain provided. func verifySignature(signedData, pub, signature, domain []byte) error { - set, err := retrieveSignatureSet(signedData, pub, signature, domain) + set, err := signatureSet(signedData, pub, signature, domain) if err != nil { return err } @@ -85,7 +85,7 @@ func BlockSignatureSet(beaconState *stateTrie.BeaconState, block *ethpb.SignedBe return nil, err } proposerPubKey := proposer.PublicKey - return helpers.RetrieveBlockSignatureSet(block.Block, proposerPubKey, block.Signature, domain) + return helpers.BlockSignatureSet(block.Block, proposerPubKey, block.Signature, domain) } // RandaoSignatureSet retrieves the relevant randao specific signature set object @@ -97,7 +97,7 @@ func RandaoSignatureSet(beaconState *stateTrie.BeaconState, if err != nil { return nil, err } - set, err := retrieveSignatureSet(buf, proposerPub, body.RandaoReveal, domain) + set, err := signatureSet(buf, proposerPub, body.RandaoReveal, domain) if err != nil { return nil, err } diff --git a/beacon-chain/core/helpers/signing_root.go b/beacon-chain/core/helpers/signing_root.go index 8696420ebe3..4d1037caeeb 100644 --- a/beacon-chain/core/helpers/signing_root.go +++ b/beacon-chain/core/helpers/signing_root.go @@ -98,7 +98,7 @@ func VerifySigningRoot(obj fssz.HashRoot, pub, signature, domain []byte) error { // VerifyBlockSigningRoot verifies the signing root of a block given it's public key, signature and domain. func VerifyBlockSigningRoot(blk *ethpb.BeaconBlock, pub, signature, domain []byte) error { - set, err := RetrieveBlockSignatureSet(blk, pub, signature, domain) + set, err := BlockSignatureSet(blk, pub, signature, domain) if err != nil { return err } @@ -117,9 +117,9 @@ func VerifyBlockSigningRoot(blk *ethpb.BeaconBlock, pub, signature, domain []byt return nil } -// RetrieveBlockSignatureSet retrieves the relevant signature, message and pubkey data from a block and collating it +// BlockSignatureSet retrieves the relevant signature, message and pubkey data from a block and collating it // into a signature set object. -func RetrieveBlockSignatureSet(blk *ethpb.BeaconBlock, pub, signature, domain []byte) (*bls.SignatureSet, error) { +func BlockSignatureSet(blk *ethpb.BeaconBlock, pub, signature, domain []byte) (*bls.SignatureSet, error) { publicKey, err := bls.PublicKeyFromBytes(pub) if err != nil { return nil, errors.Wrap(err, "could not convert bytes to public key") diff --git a/beacon-chain/db/kv/blocks.go b/beacon-chain/db/kv/blocks.go index 16972064fd3..083deedf8ed 100644 --- a/beacon-chain/db/kv/blocks.go +++ b/beacon-chain/db/kv/blocks.go @@ -71,7 +71,7 @@ func (s *Store) Blocks(ctx context.Context, f *filters.QueryFilter) ([]*ethpb.Si err := s.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(blocksBucket) - keys, err := getBlockRootsByFilter(ctx, tx, f) + keys, err := blockRootsByFilter(ctx, tx, f) if err != nil { return err } @@ -100,7 +100,7 @@ func (s *Store) BlockRoots(ctx context.Context, f *filters.QueryFilter) ([][32]b defer span.End() blockRoots := make([][32]byte, 0) err := s.db.View(func(tx *bolt.Tx) error { - keys, err := getBlockRootsByFilter(ctx, tx, f) + keys, err := blockRootsByFilter(ctx, tx, f) if err != nil { return err } @@ -143,7 +143,7 @@ func (s *Store) BlocksBySlot(ctx context.Context, slot uint64) (bool, []*ethpb.S err := s.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(blocksBucket) - keys, err := getBlockRootsBySlot(ctx, tx, slot) + keys, err := blockRootsBySlot(ctx, tx, slot) if err != nil { return err } @@ -167,7 +167,7 @@ func (s *Store) BlockRootsBySlot(ctx context.Context, slot uint64) (bool, [][32] defer span.End() blockRoots := make([][32]byte, 0) err := s.db.View(func(tx *bolt.Tx) error { - keys, err := getBlockRootsBySlot(ctx, tx, slot) + keys, err := blockRootsBySlot(ctx, tx, slot) if err != nil { return err } @@ -374,9 +374,9 @@ func (s *Store) HighestSlotBlocksBelow(ctx context.Context, slot uint64) ([]*eth return []*ethpb.SignedBeaconBlock{blk}, nil } -// getBlockRootsByFilter retrieves the block roots given the filter criteria. -func getBlockRootsByFilter(ctx context.Context, tx *bolt.Tx, f *filters.QueryFilter) ([][]byte, error) { - ctx, span := trace.StartSpan(ctx, "BeaconDB.getBlockRootsByFilter") +// blockRootsByFilter retrieves the block roots given the filter criteria. +func blockRootsByFilter(ctx context.Context, tx *bolt.Tx, f *filters.QueryFilter) ([][]byte, error) { + ctx, span := trace.StartSpan(ctx, "BeaconDB.blockRootsByFilter") defer span.End() // If no filter criteria are specified, return an error. @@ -394,7 +394,7 @@ func getBlockRootsByFilter(ctx context.Context, tx *bolt.Tx, f *filters.QueryFil // We retrieve block roots that match a filter criteria of slot ranges, if specified. filtersMap := f.Filters() - rootsBySlotRange, err := fetchBlockRootsBySlotRange( + rootsBySlotRange, err := blockRootsBySlotRange( ctx, tx.Bucket(blockSlotIndicesBucket), filtersMap[filters.StartSlot], @@ -431,15 +431,15 @@ func getBlockRootsByFilter(ctx context.Context, tx *bolt.Tx, f *filters.QueryFil return keys, nil } -// fetchBlockRootsBySlotRange looks into a boltDB bucket and performs a binary search +// blockRootsBySlotRange looks into a boltDB bucket and performs a binary search // range scan using sorted left-padded byte keys using a start slot and an end slot. // However, if step is one, the implemented logic won’t skip half of the slots in the range. -func fetchBlockRootsBySlotRange( +func blockRootsBySlotRange( ctx context.Context, bkt *bolt.Bucket, startSlotEncoded, endSlotEncoded, startEpochEncoded, endEpochEncoded, slotStepEncoded interface{}, ) ([][]byte, error) { - ctx, span := trace.StartSpan(ctx, "BeaconDB.fetchBlockRootsBySlotRange") + ctx, span := trace.StartSpan(ctx, "BeaconDB.blockRootsBySlotRange") defer span.End() // Return nothing when all slot parameters are missing @@ -501,9 +501,9 @@ func fetchBlockRootsBySlotRange( return roots, nil } -// getBlockRootsByFilter retrieves the block roots by slot -func getBlockRootsBySlot(ctx context.Context, tx *bolt.Tx, slot uint64) ([][]byte, error) { - ctx, span := trace.StartSpan(ctx, "BeaconDB.getBlockRootsBySlot") +// blockRootsBySlot retrieves the block roots by slot +func blockRootsBySlot(ctx context.Context, tx *bolt.Tx, slot uint64) ([][]byte, error) { + ctx, span := trace.StartSpan(ctx, "BeaconDB.blockRootsBySlot") defer span.End() roots := make([][]byte, 0) diff --git a/beacon-chain/main.go b/beacon-chain/main.go index c800d14c8f8..745f68ecbc3 100644 --- a/beacon-chain/main.go +++ b/beacon-chain/main.go @@ -117,7 +117,7 @@ func main() { app.Name = "beacon-chain" app.Usage = "this is a beacon chain implementation for Ethereum 2.0" app.Action = startNode - app.Version = version.GetVersion() + app.Version = version.Version() app.Commands = []*cli.Command{ db.DatabaseCommands, } diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index 26f93bb7ea1..ee86f388439 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -242,7 +242,7 @@ func (b *BeaconNode) Start() { b.lock.Lock() log.WithFields(logrus.Fields{ - "version": version.GetVersion(), + "version": version.Version(), }).Info("Starting beacon node") b.services.StartAll() diff --git a/beacon-chain/p2p/discovery.go b/beacon-chain/p2p/discovery.go index 2f334fd97a6..549f9611fcb 100644 --- a/beacon-chain/p2p/discovery.go +++ b/beacon-chain/p2p/discovery.go @@ -44,7 +44,7 @@ func (s *Service) RefreshENR() { for _, idx := range committees { bitV.SetBitAt(idx, true) } - currentBitV, err := retrieveBitvector(s.dv5Listener.Self().Record()) + currentBitV, err := bitvector(s.dv5Listener.Self().Record()) if err != nil { log.Errorf("Could not retrieve bitfield: %v", err) return diff --git a/beacon-chain/p2p/fork.go b/beacon-chain/p2p/fork.go index 4197138e116..140f1ecdfa9 100644 --- a/beacon-chain/p2p/fork.go +++ b/beacon-chain/p2p/fork.go @@ -36,11 +36,11 @@ func (s *Service) forkDigest() ([4]byte, error) { // local record values for current and next fork version/epoch. func (s *Service) compareForkENR(record *enr.Record) error { currentRecord := s.dv5Listener.LocalNode().Node().Record() - peerForkENR, err := retrieveForkEntry(record) + peerForkENR, err := forkEntry(record) if err != nil { return err } - currentForkENR, err := retrieveForkEntry(currentRecord) + currentForkENR, err := forkEntry(currentRecord) if err != nil { return err } @@ -124,7 +124,7 @@ func addForkEntry( // Retrieves an enrForkID from an ENR record by key lookup // under the eth2EnrKey. -func retrieveForkEntry(record *enr.Record) (*pb.ENRForkID, error) { +func forkEntry(record *enr.Record) (*pb.ENRForkID, error) { sszEncodedForkEntry := make([]byte, 16) entry := enr.WithEntry(eth2ENRKey, &sszEncodedForkEntry) err := record.Load(entry) diff --git a/beacon-chain/p2p/fork_test.go b/beacon-chain/p2p/fork_test.go index 2533534dfc9..210f053ecb3 100644 --- a/beacon-chain/p2p/fork_test.go +++ b/beacon-chain/p2p/fork_test.go @@ -229,7 +229,7 @@ func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) { } enc, err := enrForkID.MarshalSSZ() require.NoError(t, err) - forkEntry := enr.WithEntry(eth2ENRKey, enc) + entry := enr.WithEntry(eth2ENRKey, enc) // In epoch 1 of current time, the fork version should be // {0, 0, 0, 1} according to the configuration override above. temp := t.TempDir() @@ -241,12 +241,12 @@ func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) { db, err := enode.OpenDB("") require.NoError(t, err) localNode := enode.NewLocalNode(db, pkey) - localNode.Set(forkEntry) + localNode.Set(entry) want, err := helpers.ComputeForkDigest([]byte{0, 0, 0, 0}, genesisValidatorsRoot) require.NoError(t, err) - resp, err := retrieveForkEntry(localNode.Node().Record()) + resp, err := forkEntry(localNode.Node().Record()) require.NoError(t, err) assert.DeepEqual(t, want[:], resp.CurrentForkDigest) assert.DeepEqual(t, nextForkVersion, resp.NextForkVersion) @@ -266,7 +266,7 @@ func TestAddForkEntry_Genesis(t *testing.T) { localNode := enode.NewLocalNode(db, pkey) localNode, err = addForkEntry(localNode, time.Now().Add(10*time.Second), bytesutil.PadTo([]byte{'A', 'B', 'C', 'D'}, 32)) require.NoError(t, err) - forkEntry, err := retrieveForkEntry(localNode.Node().Record()) + forkEntry, err := forkEntry(localNode.Node().Record()) require.NoError(t, err) assert.DeepEqual(t, params.BeaconConfig().GenesisForkVersion, forkEntry.NextForkVersion, diff --git a/beacon-chain/p2p/options.go b/beacon-chain/p2p/options.go index b11f505d92a..8d3d8593130 100644 --- a/beacon-chain/p2p/options.go +++ b/beacon-chain/p2p/options.go @@ -32,7 +32,7 @@ func (s *Service) buildOptions(ip net.IP, priKey *ecdsa.PrivateKey) []libp2p.Opt options := []libp2p.Option{ privKeyOption(priKey), libp2p.ListenAddrs(listen), - libp2p.UserAgent(version.GetBuildData()), + libp2p.UserAgent(version.BuildData()), libp2p.ConnectionGater(s), } diff --git a/beacon-chain/p2p/peers/benchmark_test.go b/beacon-chain/p2p/peers/benchmark_test.go index 7c72ef02e23..2a9d0079ac9 100644 --- a/beacon-chain/p2p/peers/benchmark_test.go +++ b/beacon-chain/p2p/peers/benchmark_test.go @@ -13,6 +13,6 @@ func Benchmark_retrieveIndicesFromBitfield(b *testing.B) { } b.ResetTimer() for i := 0; i < b.N; i++ { - retrieveIndicesFromBitfield(bv) + indicesFromBitfield(bv) } } diff --git a/beacon-chain/p2p/peers/status.go b/beacon-chain/p2p/peers/status.go index 3adf3eb33da..107dcc9b646 100644 --- a/beacon-chain/p2p/peers/status.go +++ b/beacon-chain/p2p/peers/status.go @@ -237,7 +237,7 @@ func (p *Status) CommitteeIndices(pid peer.ID) ([]uint64, error) { if peerData.Enr == nil || peerData.MetaData == nil { return []uint64{}, nil } - return retrieveIndicesFromBitfield(peerData.MetaData.Attnets), nil + return indicesFromBitfield(peerData.MetaData.Attnets), nil } return nil, peerdata.ErrPeerUnknown } @@ -253,7 +253,7 @@ func (p *Status) SubscribedToSubnet(index uint64) []peer.ID { // look at active peers connectedStatus := peerData.ConnState == PeerConnecting || peerData.ConnState == PeerConnected if connectedStatus && peerData.MetaData != nil && peerData.MetaData.Attnets != nil { - indices := retrieveIndicesFromBitfield(peerData.MetaData.Attnets) + indices := indicesFromBitfield(peerData.MetaData.Attnets) for _, idx := range indices { if idx == index { peers = append(peers, pid) @@ -796,7 +796,7 @@ func sameIP(firstAddr, secondAddr ma.Multiaddr) bool { return firstIP.Equal(secondIP) } -func retrieveIndicesFromBitfield(bitV bitfield.Bitvector64) []uint64 { +func indicesFromBitfield(bitV bitfield.Bitvector64) []uint64 { committeeIdxs := make([]uint64, 0, bitV.Count()) for i := uint64(0); i < 64; i++ { if bitV.BitAt(i) { diff --git a/beacon-chain/p2p/subnets.go b/beacon-chain/p2p/subnets.go index 3544429b7a6..67da8e19b5d 100644 --- a/beacon-chain/p2p/subnets.go +++ b/beacon-chain/p2p/subnets.go @@ -73,7 +73,7 @@ func (s *Service) filterPeerForSubnet(index uint64) func(node *enode.Node) bool if !s.filterPeer(node) { return false } - subnets, err := retrieveAttSubnets(node.Record()) + subnets, err := attSubnets(node.Record()) if err != nil { return false } @@ -119,8 +119,8 @@ func intializeAttSubnets(node *enode.LocalNode) *enode.LocalNode { // Reads the attestation subnets entry from a node's ENR and determines // the committee indices of the attestation subnets the node is subscribed to. -func retrieveAttSubnets(record *enr.Record) ([]uint64, error) { - bitV, err := retrieveBitvector(record) +func attSubnets(record *enr.Record) ([]uint64, error) { + bitV, err := bitvector(record) if err != nil { return nil, err } @@ -135,7 +135,7 @@ func retrieveAttSubnets(record *enr.Record) ([]uint64, error) { // Parses the attestation subnets ENR entry in a node and extracts its value // as a bitvector for further manipulation. -func retrieveBitvector(record *enr.Record) (bitfield.Bitvector64, error) { +func bitvector(record *enr.Record) (bitfield.Bitvector64, error) { bitV := bitfield.NewBitvector64() entry := enr.WithEntry(attSubnetEnrKey, &bitV) err := record.Load(entry) diff --git a/beacon-chain/p2p/utils.go b/beacon-chain/p2p/utils.go index 0a5c93de009..6bdbcb5c354 100644 --- a/beacon-chain/p2p/utils.go +++ b/beacon-chain/p2p/utils.go @@ -87,11 +87,11 @@ func privKey(cfg *Config) (*ecdsa.PrivateKey, error) { if defaultKeysExist && privateKeyPath == "" { privateKeyPath = defaultKeyPath } - return retrievePrivKeyFromFile(privateKeyPath) + return privKeyFromFile(privateKeyPath) } // Retrieves a p2p networking private key from a file path. -func retrievePrivKeyFromFile(path string) (*ecdsa.PrivateKey, error) { +func privKeyFromFile(path string) (*ecdsa.PrivateKey, error) { src, err := ioutil.ReadFile(path) if err != nil { log.WithError(err).Error("Error reading private key from file") diff --git a/beacon-chain/rpc/beacon/attestations.go b/beacon-chain/rpc/beacon/attestations.go index 540accc1403..de02bac414c 100644 --- a/beacon-chain/rpc/beacon/attestations.go +++ b/beacon-chain/rpc/beacon/attestations.go @@ -334,7 +334,7 @@ func (bs *Server) StreamIndexedAttestations( func (bs *Server) collectReceivedAttestations(ctx context.Context) { attsByRoot := make(map[[32]byte][]*ethpb.Attestation) twoThirdsASlot := 2 * slotutil.DivideSlotBy(3) /* 2/3 slot duration */ - ticker := slotutil.GetSlotTickerWithOffset(bs.GenesisTimeFetcher.GenesisTime(), twoThirdsASlot, params.BeaconConfig().SecondsPerSlot) + ticker := slotutil.NewSlotTickerWithOffset(bs.GenesisTimeFetcher.GenesisTime(), twoThirdsASlot, params.BeaconConfig().SecondsPerSlot) for { select { case <-ticker.C(): diff --git a/beacon-chain/rpc/node/server.go b/beacon-chain/rpc/node/server.go index 107980a42a1..2c8c13227ab 100644 --- a/beacon-chain/rpc/node/server.go +++ b/beacon-chain/rpc/node/server.go @@ -79,7 +79,7 @@ func (ns *Server) GetGenesis(ctx context.Context, _ *ptypes.Empty) (*ethpb.Genes // GetVersion checks the version information of the beacon node. func (ns *Server) GetVersion(_ context.Context, _ *ptypes.Empty) (*ethpb.Version, error) { return ðpb.Version{ - Version: version.GetVersion(), + Version: version.Version(), }, nil } diff --git a/beacon-chain/rpc/node/server_test.go b/beacon-chain/rpc/node/server_test.go index 160c6189588..77baa44273c 100644 --- a/beacon-chain/rpc/node/server_test.go +++ b/beacon-chain/rpc/node/server_test.go @@ -71,7 +71,7 @@ func TestNodeServer_GetGenesis(t *testing.T) { } func TestNodeServer_GetVersion(t *testing.T) { - v := version.GetVersion() + v := version.Version() ns := &Server{} res, err := ns.GetVersion(context.Background(), &ptypes.Empty{}) require.NoError(t, err) diff --git a/beacon-chain/rpc/nodev1/node.go b/beacon-chain/rpc/nodev1/node.go index 9a62f4367e8..cf57c4e0868 100644 --- a/beacon-chain/rpc/nodev1/node.go +++ b/beacon-chain/rpc/nodev1/node.go @@ -226,10 +226,10 @@ func (ns *Server) PeerCount(ctx context.Context, _ *ptypes.Empty) (*ethpb.PeerCo // GetVersion requests that the beacon node identify information about its implementation in a // format similar to a HTTP User-Agent field. func (ns *Server) GetVersion(ctx context.Context, _ *ptypes.Empty) (*ethpb.VersionResponse, error) { - ctx, span := trace.StartSpan(ctx, "nodev1.GetVersion") + ctx, span := trace.StartSpan(ctx, "nodev1.Version") defer span.End() - v := fmt.Sprintf("Prysm/%s (%s %s)", version.GetSemanticVersion(), runtime.GOOS, runtime.GOARCH) + v := fmt.Sprintf("Prysm/%s (%s %s)", version.SemanticVersion(), runtime.GOOS, runtime.GOARCH) return ðpb.VersionResponse{ Data: ðpb.Version{ Version: v, diff --git a/beacon-chain/rpc/nodev1/node_test.go b/beacon-chain/rpc/nodev1/node_test.go index b7c6d252810..80194881d2a 100644 --- a/beacon-chain/rpc/nodev1/node_test.go +++ b/beacon-chain/rpc/nodev1/node_test.go @@ -35,7 +35,7 @@ func (id dummyIdentity) Verify(_ *enr.Record, _ []byte) error { return nil } func (id dummyIdentity) NodeAddr(_ *enr.Record) []byte { return id[:] } func TestGetVersion(t *testing.T) { - semVer := version.GetSemanticVersion() + semVer := version.SemanticVersion() os := runtime.GOOS arch := runtime.GOARCH res, err := (&Server{}).GetVersion(context.Background(), &ptypes.Empty{}) diff --git a/beacon-chain/rpc/validator/assignments.go b/beacon-chain/rpc/validator/assignments.go index 29691b98e38..eb5f0aa445d 100644 --- a/beacon-chain/rpc/validator/assignments.go +++ b/beacon-chain/rpc/validator/assignments.go @@ -61,7 +61,7 @@ func (vs *Server) StreamDuties(req *ethpb.DutiesRequest, stream ethpb.BeaconNode defer stateSub.Unsubscribe() secondsPerEpoch := params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch - epochTicker := slotutil.GetSlotTicker(vs.TimeFetcher.GenesisTime(), secondsPerEpoch) + epochTicker := slotutil.NewSlotTicker(vs.TimeFetcher.GenesisTime(), secondsPerEpoch) for { select { // Ticks every epoch to submit assignments to connected validator clients. diff --git a/beacon-chain/rpc/validator/status.go b/beacon-chain/rpc/validator/status.go index 4711bfb5164..13ea8409d91 100644 --- a/beacon-chain/rpc/validator/status.go +++ b/beacon-chain/rpc/validator/status.go @@ -135,7 +135,7 @@ func (vs *Server) validatorStatus( Status: ethpb.ValidatorStatus_UNKNOWN_STATUS, ActivationEpoch: params.BeaconConfig().FarFutureEpoch, } - vStatus, idx, err := retrieveStatusForPubKey(headState, pubKey) + vStatus, idx, err := statusForPubKey(headState, pubKey) if err != nil && err != errPubkeyDoesNotExist { traceutil.AnnotateError(span, err) return resp, nonExistentIndex @@ -217,7 +217,7 @@ func (vs *Server) validatorStatus( } } -func retrieveStatusForPubKey(headState *stateTrie.BeaconState, pubKey []byte) (ethpb.ValidatorStatus, uint64, error) { +func statusForPubKey(headState *stateTrie.BeaconState, pubKey []byte) (ethpb.ValidatorStatus, uint64, error) { if headState == nil { return ethpb.ValidatorStatus_UNKNOWN_STATUS, 0, errors.New("head state does not exist") } diff --git a/beacon-chain/state/state_trie.go b/beacon-chain/state/state_trie.go index 241c462b83c..2e5ade99eec 100644 --- a/beacon-chain/state/state_trie.go +++ b/beacon-chain/state/state_trie.go @@ -228,7 +228,7 @@ func (b *BeaconState) FieldReferencesCount() map[string]uint64 { // pads the leaves to a length of 32. func merkleize(leaves [][]byte) [][][]byte { hashFunc := hashutil.CustomSHA256Hasher() - layers := make([][][]byte, htrutils.GetDepth(uint64(len(leaves)))+1) + layers := make([][][]byte, htrutils.Depth(uint64(len(leaves)))+1) for len(leaves) != 32 { leaves = append(leaves, make([]byte, 32)) } diff --git a/beacon-chain/state/stateutil/arrays.go b/beacon-chain/state/stateutil/arrays.go index 65da95ac320..e66f4f595a9 100644 --- a/beacon-chain/state/stateutil/arrays.go +++ b/beacon-chain/state/stateutil/arrays.go @@ -33,7 +33,7 @@ func (h *stateRootHasher) arraysRoot(input [][]byte, length uint64, fieldName st defer lock.Unlock() hashFunc := hashutil.CustomSHA256Hasher() if _, ok := layersCache[fieldName]; !ok && h.rootsCache != nil { - depth := htrutils.GetDepth(length) + depth := htrutils.Depth(length) layersCache[fieldName] = make([][][32]byte, depth+1) } @@ -93,7 +93,7 @@ func (h *stateRootHasher) merkleizeWithCache(leaves [][32]byte, length uint64, return leaves[0] } hashLayer := leaves - layers := make([][][32]byte, htrutils.GetDepth(length)+1) + layers := make([][][32]byte, htrutils.Depth(length)+1) if items, ok := layersCache[fieldName]; ok && h.rootsCache != nil { if len(items[0]) == len(leaves) { layers = items diff --git a/beacon-chain/state/stateutil/trie_helpers.go b/beacon-chain/state/stateutil/trie_helpers.go index ca9796482dd..cc468d3fb26 100644 --- a/beacon-chain/state/stateutil/trie_helpers.go +++ b/beacon-chain/state/stateutil/trie_helpers.go @@ -19,7 +19,7 @@ func ReturnTrieLayer(elements [][32]byte, length uint64) [][]*[32]byte { return [][]*[32]byte{{&leaves[0]}} } hashLayer := leaves - layers := make([][][32]byte, htrutils.GetDepth(length)+1) + layers := make([][][32]byte, htrutils.Depth(length)+1) layers[0] = hashLayer layers, _ = merkleizeTrieLeaves(layers, hashLayer, hasher) refLayers := make([][]*[32]byte, len(layers)) @@ -38,7 +38,7 @@ func ReturnTrieLayer(elements [][32]byte, length uint64) [][]*[32]byte { // it. func ReturnTrieLayerVariable(elements [][32]byte, length uint64) [][]*[32]byte { hasher := hashutil.CustomSHA256Hasher() - depth := htrutils.GetDepth(length) + depth := htrutils.Depth(length) layers := make([][]*[32]byte, depth+1) // Return zerohash at depth if len(elements) == 0 { diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher.go b/beacon-chain/sync/initial-sync/blocks_fetcher.go index dab85f388b8..de43abcb8a4 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher.go @@ -304,7 +304,7 @@ func (f *blocksFetcher) requestBlocks( if ctx.Err() != nil { return nil, ctx.Err() } - l := f.getPeerLock(pid) + l := f.peerLock(pid) l.Lock() log.WithFields(logrus.Fields{ "peer": pid, @@ -334,7 +334,7 @@ func (f *blocksFetcher) requestBlocksByRoot( if ctx.Err() != nil { return nil, ctx.Err() } - l := f.getPeerLock(pid) + l := f.peerLock(pid) l.Lock() log.WithFields(logrus.Fields{ "peer": pid, diff --git a/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go b/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go index 3559e8e6572..9fc6f99c135 100644 --- a/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go +++ b/beacon-chain/sync/initial-sync/blocks_fetcher_peers.go @@ -17,8 +17,8 @@ import ( "go.opencensus.io/trace" ) -// getPeerLock returns peer lock for a given peer. If lock is not found, it is created. -func (f *blocksFetcher) getPeerLock(pid peer.ID) *peerLock { +// peerLock returns peer lock for a given peer. If lock is not found, it is created. +func (f *blocksFetcher) peerLock(pid peer.ID) *peerLock { f.Lock() defer f.Unlock() if lock, ok := f.peerLocks[pid]; ok && lock != nil { diff --git a/beacon-chain/sync/subscriber.go b/beacon-chain/sync/subscriber.go index dbd1343c793..c5b9ecd82b4 100644 --- a/beacon-chain/sync/subscriber.go +++ b/beacon-chain/sync/subscriber.go @@ -205,7 +205,7 @@ func (s *Service) subscribeStaticWithSubnets(topic string, validator pubsub.Vali s.subscribeWithBase(s.addDigestAndIndexToTopic(topic, i), validator, handle) } genesis := s.chain.GenesisTime() - ticker := slotutil.GetSlotTicker(genesis, params.BeaconConfig().SecondsPerSlot) + ticker := slotutil.NewSlotTicker(genesis, params.BeaconConfig().SecondsPerSlot) go func() { for { @@ -252,7 +252,7 @@ func (s *Service) subscribeDynamicWithSubnets( } subscriptions := make(map[uint64]*pubsub.Subscription, params.BeaconConfig().MaxCommitteesPerSlot) genesis := s.chain.GenesisTime() - ticker := slotutil.GetSlotTicker(genesis, params.BeaconConfig().SecondsPerSlot) + ticker := slotutil.NewSlotTicker(genesis, params.BeaconConfig().SecondsPerSlot) go func() { for { diff --git a/endtoend/components/beacon_node.go b/endtoend/components/beacon_node.go index 659b9057cf2..f03f0d0f89b 100644 --- a/endtoend/components/beacon_node.go +++ b/endtoend/components/beacon_node.go @@ -105,7 +105,7 @@ func StartBootnode(t *testing.T) string { t.Fatalf("could not find enr for bootnode, this means the bootnode had issues starting: %v", err) } - enr, err := getENRFromLogFile(stdOutFile.Name()) + enr, err := enrFromLogFile(stdOutFile.Name()) if err != nil { t.Fatalf("could not get enr for bootnode: %v", err) } @@ -113,7 +113,7 @@ func StartBootnode(t *testing.T) string { return enr } -func getENRFromLogFile(name string) (string, error) { +func enrFromLogFile(name string) (string, error) { byteContent, err := ioutil.ReadFile(name) if err != nil { return "", err diff --git a/endtoend/endtoend_test.go b/endtoend/endtoend_test.go index c3f2d727b4f..232128fa178 100644 --- a/endtoend/endtoend_test.go +++ b/endtoend/endtoend_test.go @@ -97,7 +97,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) { // Offsetting the ticker from genesis so it ticks in the middle of an epoch, in order to keep results consistent. tickingStartTime := genesisTime.Add(middleOfEpoch) - ticker := helpers.GetEpochTicker(tickingStartTime, epochSeconds) + ticker := helpers.NewEpochTicker(tickingStartTime, epochSeconds) for currentEpoch := range ticker.C() { for _, evaluator := range config.Evaluators { // Only run if the policy says so. diff --git a/endtoend/evaluators/metrics.go b/endtoend/evaluators/metrics.go index 2d7fddc6eb8..d0b7a4b2898 100644 --- a/endtoend/evaluators/metrics.go +++ b/endtoend/evaluators/metrics.go @@ -113,7 +113,7 @@ func metricsTest(conns ...*grpc.ClientConn) error { if err != nil { return err } - timeSlot, err := getValueOfTopic(pageContent, "beacon_clock_time_slot") + timeSlot, err := valueOfTopic(pageContent, "beacon_clock_time_slot") if err != nil { return err } @@ -148,7 +148,7 @@ func metricsTest(conns ...*grpc.ClientConn) error { } func metricCheckLessThan(pageContent, topic string, value int) error { - topicValue, err := getValueOfTopic(pageContent, topic) + topicValue, err := valueOfTopic(pageContent, topic) if err != nil { return err } @@ -164,7 +164,7 @@ func metricCheckLessThan(pageContent, topic string, value int) error { } func metricCheckComparison(pageContent, topic1, topic2 string, comparison float64) error { - topic2Value, err := getValueOfTopic(pageContent, topic2) + topic2Value, err := valueOfTopic(pageContent, topic2) // If we can't find the first topic (error metrics), then assume the test passes. if topic2Value != -1 { return nil @@ -172,7 +172,7 @@ func metricCheckComparison(pageContent, topic1, topic2 string, comparison float6 if err != nil { return err } - topic1Value, err := getValueOfTopic(pageContent, topic1) + topic1Value, err := valueOfTopic(pageContent, topic1) if topic1Value != -1 { return nil } @@ -192,7 +192,7 @@ func metricCheckComparison(pageContent, topic1, topic2 string, comparison float6 return nil } -func getValueOfTopic(pageContent, topic string) (int, error) { +func valueOfTopic(pageContent, topic string) (int, error) { regexExp, err := regexp.Compile(topic + " ") if err != nil { return -1, errors.Wrap(err, "could not create regex expression") diff --git a/endtoend/helpers/epochTimer.go b/endtoend/helpers/epochTimer.go index a2f68118573..06c092d6bec 100644 --- a/endtoend/helpers/epochTimer.go +++ b/endtoend/helpers/epochTimer.go @@ -30,8 +30,8 @@ func (s *EpochTicker) Done() { }() } -// GetEpochTicker is the constructor for EpochTicker. -func GetEpochTicker(genesisTime time.Time, secondsPerEpoch uint64) *EpochTicker { +// NewEpochTicker starts the EpochTicker. +func NewEpochTicker(genesisTime time.Time, secondsPerEpoch uint64) *EpochTicker { ticker := &EpochTicker{ c: make(chan uint64), done: make(chan struct{}), diff --git a/fuzz/testing/beacon_fuzz_states.go b/fuzz/testing/beacon_fuzz_states.go index 4f1e85b520e..c1f3b9909b9 100644 --- a/fuzz/testing/beacon_fuzz_states.go +++ b/fuzz/testing/beacon_fuzz_states.go @@ -12,8 +12,8 @@ import ( const fileBase = "0-11-0/mainnet/beaconstate" const fileBaseENV = "BEACONSTATES_PATH" -// GetBeaconFuzzState returns a beacon state by ID using the beacon-fuzz corpora. -func GetBeaconFuzzState(ID uint64) (*pb.BeaconState, error) { +// BeaconFuzzState returns a beacon state by ID using the beacon-fuzz corpora. +func BeaconFuzzState(ID uint64) (*pb.BeaconState, error) { base := fileBase // Using an environment variable allows a host image to specify the path when only the binary // executable was uploaded (without the runfiles). i.e. fuzzit's platform. diff --git a/fuzz/testing/beacon_fuzz_states_test.go b/fuzz/testing/beacon_fuzz_states_test.go index 836956d4672..768d7ba565d 100644 --- a/fuzz/testing/beacon_fuzz_states_test.go +++ b/fuzz/testing/beacon_fuzz_states_test.go @@ -7,6 +7,6 @@ import ( ) func TestGetBeaconFuzzState(t *testing.T) { - _, err := GetBeaconFuzzState(1) + _, err := BeaconFuzzState(1) require.NoError(t, err) } diff --git a/shared/htrutils/merkleize.go b/shared/htrutils/merkleize.go index 33ff35bc4e0..68edcbb833b 100644 --- a/shared/htrutils/merkleize.go +++ b/shared/htrutils/merkleize.go @@ -29,8 +29,8 @@ const ( bit5 ) -// GetDepth retrieves the appropriate depth for the provided trie size. -func GetDepth(v uint64) (out uint8) { +// Depth retrieves the appropriate depth for the provided trie size. +func Depth(v uint64) (out uint8) { // bitmagic: binary search through a uint32, offset down by 1 to not round powers of 2 up. // Then adding 1 to it to not get the index of the first bit, but the length of the bits (depth of tree) // Zero is a special case, it has a 0 depth. @@ -81,8 +81,8 @@ func Merkleize(hasher Hasher, count, limit uint64, leaf func(i uint64) []byte) ( } return } - depth := GetDepth(count) - limitDepth := GetDepth(limit) + depth := Depth(count) + limitDepth := Depth(limit) tmp := make([][32]byte, limitDepth+1) j := uint8(0) @@ -144,8 +144,8 @@ func ConstructProof(hasher Hasher, count, limit uint64, leaf func(i uint64) []by if limit <= 1 { return } - depth := GetDepth(count) - limitDepth := GetDepth(limit) + depth := Depth(count) + limitDepth := Depth(limit) branch = append(branch, trieutil.ZeroHashes[:limitDepth]...) tmp := make([][32]byte, limitDepth+1) diff --git a/shared/htrutils/merkleize_test.go b/shared/htrutils/merkleize_test.go index c811d01a92e..33ced3bb9d8 100644 --- a/shared/htrutils/merkleize_test.go +++ b/shared/htrutils/merkleize_test.go @@ -12,7 +12,7 @@ func TestGetDepth(t *testing.T) { trieSize := uint64(896745231) expected := uint8(30) - result := htrutils.GetDepth(trieSize) + result := htrutils.Depth(trieSize) assert.Equal(t, expected, result) } diff --git a/shared/iputils/external_ip.go b/shared/iputils/external_ip.go index fbfc1bf05fc..cf4af375fdc 100644 --- a/shared/iputils/external_ip.go +++ b/shared/iputils/external_ip.go @@ -8,7 +8,7 @@ import ( // ExternalIPv4 returns the first IPv4 available. func ExternalIPv4() (string, error) { - ips, err := retrieveIPAddrs() + ips, err := ipAddrs() if err != nil { return "", err } @@ -28,7 +28,7 @@ func ExternalIPv4() (string, error) { // ExternalIPv6 retrieves any allocated IPv6 addresses // from the accessible network interfaces. func ExternalIPv6() (string, error) { - ips, err := retrieveIPAddrs() + ips, err := ipAddrs() if err != nil { return "", err } @@ -49,7 +49,7 @@ func ExternalIPv6() (string, error) { // ExternalIP returns the first IPv4/IPv6 available. func ExternalIP() (string, error) { - ips, err := retrieveIPAddrs() + ips, err := ipAddrs() if err != nil { return "", err } @@ -59,8 +59,8 @@ func ExternalIP() (string, error) { return ips[0].String(), nil } -// retrieveIP returns all the valid IPs available. -func retrieveIPAddrs() ([]net.IP, error) { +// ipAddrs returns all the valid IPs available. +func ipAddrs() ([]net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err diff --git a/shared/keystore/keystore.go b/shared/keystore/keystore.go index bfca3ad1034..72951fe3903 100644 --- a/shared/keystore/keystore.go +++ b/shared/keystore/keystore.go @@ -237,7 +237,7 @@ func decryptKeyJSON(keyProtected *encryptedKeyJSON, auth string) (keyBytes, keyI return nil, nil, err } - derivedKey, err := getKDFKey(keyProtected.Crypto, auth) + derivedKey, err := kdfKey(keyProtected.Crypto, auth) if err != nil { return nil, nil, err } @@ -254,7 +254,7 @@ func decryptKeyJSON(keyProtected *encryptedKeyJSON, auth string) (keyBytes, keyI return plainText, keyID, nil } -func getKDFKey(cryptoJSON cryptoJSON, auth string) ([]byte, error) { +func kdfKey(cryptoJSON cryptoJSON, auth string) ([]byte, error) { authArray := []byte(auth) salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string)) if err != nil { diff --git a/shared/prereq/prereq.go b/shared/prereq/prereq.go index b962936338b..82650dc71ca 100644 --- a/shared/prereq/prereq.go +++ b/shared/prereq/prereq.go @@ -34,7 +34,7 @@ func execShellOutputFunc(ctx context.Context, command string, args ...string) (s return string(result), nil } -func getSupportedPlatforms() []platform { +func supportedPlatforms() []platform { return []platform{ {os: "linux", arch: "amd64"}, {os: "linux", arch: "arm64"}, @@ -66,7 +66,7 @@ func parseVersion(input string, num int, sep string) ([]int, error) { // meetsMinPlatformReqs returns true if the runtime matches any on the list of supported platforms func meetsMinPlatformReqs(ctx context.Context) (bool, error) { - okPlatforms := getSupportedPlatforms() + okPlatforms := supportedPlatforms() for _, platform := range okPlatforms { if runtimeOS == platform.os && runtimeArch == platform.arch { // If MacOS we make sure it meets the minimum version cutoff diff --git a/shared/prometheus/logrus_collector_test.go b/shared/prometheus/logrus_collector_test.go index d9e95d0bf91..2ae9a3ae851 100644 --- a/shared/prometheus/logrus_collector_test.go +++ b/shared/prometheus/logrus_collector_test.go @@ -61,8 +61,8 @@ func TestLogrusCollector(t *testing.T) { logExampleMessage(log.StandardLogger(), tt.level) } time.Sleep(time.Millisecond) - metrics := getMetrics(t) - count := getValueFor(t, metrics, prefix, tt.level) + metrics := metrics(t) + count := valueFor(t, metrics, prefix, tt.level) if count != tt.want { t.Errorf("Expecting %d and receive %d", tt.want, count) } @@ -70,7 +70,7 @@ func TestLogrusCollector(t *testing.T) { } } -func getMetrics(t *testing.T) []string { +func metrics(t *testing.T) []string { resp, err := http.Get(fmt.Sprintf("http://%s/metrics", addr)) require.NoError(t, err) body, err := ioutil.ReadAll(resp.Body) @@ -78,7 +78,7 @@ func getMetrics(t *testing.T) []string { return strings.Split(string(body), "\n") } -func getValueFor(t *testing.T, metrics []string, prefix string, level log.Level) int { +func valueFor(t *testing.T, metrics []string, prefix string, level log.Level) int { // Expect line with this pattern: // # HELP log_entries_total Total number of log messages. // # TYPE log_entries_total counter diff --git a/shared/slotutil/slotticker.go b/shared/slotutil/slotticker.go index 0ff11362c83..0b899487395 100644 --- a/shared/slotutil/slotticker.go +++ b/shared/slotutil/slotticker.go @@ -38,8 +38,8 @@ func (s *SlotTicker) Done() { }() } -// GetSlotTicker is the constructor for SlotTicker. -func GetSlotTicker(genesisTime time.Time, secondsPerSlot uint64) *SlotTicker { +// NewSlotTicker starts and returns a new SlotTicker instance. +func NewSlotTicker(genesisTime time.Time, secondsPerSlot uint64) *SlotTicker { if genesisTime.IsZero() { panic("zero genesis time") } @@ -51,9 +51,9 @@ func GetSlotTicker(genesisTime time.Time, secondsPerSlot uint64) *SlotTicker { return ticker } -// GetSlotTickerWithOffset is a constructor for SlotTicker that allows a offset of time from genesis, +// NewSlotTickerWithOffset starts and returns a SlotTicker instance that allows a offset of time from genesis, // entering a offset greater than secondsPerSlot is not allowed. -func GetSlotTickerWithOffset(genesisTime time.Time, offset time.Duration, secondsPerSlot uint64) *SlotTicker { +func NewSlotTickerWithOffset(genesisTime time.Time, offset time.Duration, secondsPerSlot uint64) *SlotTicker { if genesisTime.Unix() == 0 { panic("zero genesis time") } diff --git a/shared/slotutil/slotticker_test.go b/shared/slotutil/slotticker_test.go index f853af30d79..41ae1b4cfdc 100644 --- a/shared/slotutil/slotticker_test.go +++ b/shared/slotutil/slotticker_test.go @@ -115,8 +115,8 @@ func TestGetSlotTickerWithOffset_OK(t *testing.T) { secondsPerSlot := uint64(4) offset := time.Duration(secondsPerSlot/2) * time.Second - offsetTicker := GetSlotTickerWithOffset(genesisTime, offset, secondsPerSlot) - normalTicker := GetSlotTicker(genesisTime, secondsPerSlot) + offsetTicker := NewSlotTickerWithOffset(genesisTime, offset, secondsPerSlot) + normalTicker := NewSlotTicker(genesisTime, secondsPerSlot) firstTicked := 0 for { diff --git a/shared/tracing/tracer.go b/shared/tracing/tracer.go index 11526568aa5..afd821c074d 100644 --- a/shared/tracing/tracer.go +++ b/shared/tracing/tracer.go @@ -36,7 +36,7 @@ func Setup(serviceName, processName, endpoint string, sampleFraction float64, en ServiceName: serviceName, Tags: []jaeger.Tag{ jaeger.StringTag("process_name", processName), - jaeger.StringTag("version", version.GetVersion()), + jaeger.StringTag("version", version.Version()), }, }, BufferMaxCount: 10000, diff --git a/shared/version/version.go b/shared/version/version.go index b45cdf59ab8..91f58d2af86 100644 --- a/shared/version/version.go +++ b/shared/version/version.go @@ -15,22 +15,22 @@ var gitCommit = "Local build" var buildDate = "Moments ago" var gitTag = "Unknown" -// GetVersion returns the version string of this build. -func GetVersion() string { +// Version returns the version string of this build. +func Version() string { if buildDate == "{DATE}" { now := time.Now().Format(time.RFC3339) buildDate = now } - return fmt.Sprintf("%s. Built at: %s", GetBuildData(), buildDate) + return fmt.Sprintf("%s. Built at: %s", BuildData(), buildDate) } -// GetSemanticVersion returns the Major.Minor.Patch version of this build. -func GetSemanticVersion() string { +// SemanticVersion returns the Major.Minor.Patch version of this build. +func SemanticVersion() string { return gitTag } -// GetBuildData returns the git tag and commit of the current build. -func GetBuildData() string { +// BuildData returns the git tag and commit of the current build. +func BuildData() string { // if doing a local build, these values are not interpolated if gitCommit == "{STABLE_GIT_COMMIT}" { commit, err := exec.Command("git", "rev-parse", "HEAD").Output() diff --git a/slasher/main.go b/slasher/main.go index c92f6da4647..fa74be8a170 100644 --- a/slasher/main.go +++ b/slasher/main.go @@ -90,7 +90,7 @@ func main() { app := cli.App{} app.Name = "hash slinging slasher" app.Usage = `launches an Ethereum Serenity slasher server that interacts with a beacon chain.` - app.Version = version.GetVersion() + app.Version = version.Version() app.Commands = []*cli.Command{ db.DatabaseCommands, } diff --git a/slasher/node/node.go b/slasher/node/node.go index af464f6ea19..a16b638ad26 100644 --- a/slasher/node/node.go +++ b/slasher/node/node.go @@ -119,7 +119,7 @@ func (n *SlasherNode) Start() { n.lock.Unlock() log.WithFields(logrus.Fields{ - "version": version.GetVersion(), + "version": version.Version(), }).Info("Starting slasher client") stop := n.stop diff --git a/tools/analyzers/errcheck/analyzer.go b/tools/analyzers/errcheck/analyzer.go index 8c6bb817e48..c95434c3c2a 100644 --- a/tools/analyzers/errcheck/analyzer.go +++ b/tools/analyzers/errcheck/analyzer.go @@ -341,7 +341,7 @@ func walkThroughEmbeddedInterfaces(sel *types.Selection) ([]types.Type, bool) { // index because it would give the method itself. indexes := sel.Index() for _, fieldIndex := range indexes[:len(indexes)-1] { - currentT = getTypeAtFieldIndex(currentT, fieldIndex) + currentT = typeAtFieldIndex(currentT, fieldIndex) } // Now currentT is either a type implementing the actual function, @@ -366,7 +366,7 @@ func walkThroughEmbeddedInterfaces(sel *types.Selection) ([]types.Type, bool) { for !explicitlyDefinesMethod(interfaceT, fn) { // Otherwise, we find which of the embedded interfaces _does_ // define the method, add it to our list, and loop. - namedInterfaceT, ok := getEmbeddedInterfaceDefiningMethod(interfaceT, fn) + namedInterfaceT, ok := embeddedInterfaceDefiningMethod(interfaceT, fn) if !ok { // This should be impossible as long as we type-checked: either the // interface or one of its embedded ones must implement the method... @@ -382,7 +382,7 @@ func walkThroughEmbeddedInterfaces(sel *types.Selection) ([]types.Type, bool) { return result, true } -func getTypeAtFieldIndex(startingAt types.Type, fieldIndex int) types.Type { +func typeAtFieldIndex(startingAt types.Type, fieldIndex int) types.Type { t := maybeUnname(maybeDereference(startingAt)) s, ok := t.(*types.Struct) if !ok { @@ -392,12 +392,12 @@ func getTypeAtFieldIndex(startingAt types.Type, fieldIndex int) types.Type { return s.Field(fieldIndex).Type() } -// getEmbeddedInterfaceDefiningMethod searches through any embedded interfaces of the +// embeddedInterfaceDefiningMethod searches through any embedded interfaces of the // passed interface searching for one that defines the given function. If found, the // types.Named wrapping that interface will be returned along with true in the second value. // // If no such embedded interface is found, nil and false are returned. -func getEmbeddedInterfaceDefiningMethod(interfaceT *types.Interface, fn *types.Func) (*types.Named, bool) { +func embeddedInterfaceDefiningMethod(interfaceT *types.Interface, fn *types.Func) (*types.Named, bool) { for i := 0; i < interfaceT.NumEmbeddeds(); i++ { embedded := interfaceT.Embedded(i) if definesMethod(embedded.Underlying().(*types.Interface), fn) { diff --git a/tools/analyzers/slicedirect/testdata/slice.go b/tools/analyzers/slicedirect/testdata/slice.go index 74710ee47e7..2025a2b1d66 100644 --- a/tools/analyzers/slicedirect/testdata/slice.go +++ b/tools/analyzers/slicedirect/testdata/slice.go @@ -36,11 +36,11 @@ func StringSlice() { } func SliceFromFunction() { - x := getSlice()[:] // want "Expression is already a slice." + x := slice()[:] // want "Expression is already a slice." if len(x) == 3 { } } -func getSlice() []string { +func slice() []string { return []string{"bar"} } diff --git a/tools/bootnode/bootnode.go b/tools/bootnode/bootnode.go index 971bc165688..66dfa0b78bc 100644 --- a/tools/bootnode/bootnode.go +++ b/tools/bootnode/bootnode.go @@ -74,7 +74,7 @@ func main() { } } - fmt.Printf("Starting bootnode. Version: %s\n", version.GetVersion()) + fmt.Printf("Starting bootnode. Version: %s\n", version.Version()) if *debug { logrus.SetLevel(logrus.DebugLevel) diff --git a/tools/deployContract/deployContract.go b/tools/deployContract/deployContract.go index 4f980a2d1df..462578022ae 100644 --- a/tools/deployContract/deployContract.go +++ b/tools/deployContract/deployContract.go @@ -43,7 +43,7 @@ func main() { app := cli.App{} app.Name = "deployDepositContract" app.Usage = "this is a util to deploy deposit contract" - app.Version = version.GetVersion() + app.Version = version.Version() app.Flags = []cli.Flag{ &cli.StringFlag{ Name: "keystoreUTCPath", diff --git a/tools/drainContracts/drainContracts.go b/tools/drainContracts/drainContracts.go index 530d8189dab..1e1983050ab 100644 --- a/tools/drainContracts/drainContracts.go +++ b/tools/drainContracts/drainContracts.go @@ -39,7 +39,7 @@ func main() { app := cli.App{} app.Name = "drainContracts" app.Usage = "this is a util to drain all (testing) deposit contracts of their ETH." - app.Version = version.GetVersion() + app.Version = version.Version() app.Flags = []cli.Flag{ &cli.StringFlag{ Name: "keystoreUTCPath", diff --git a/tools/eth1exporter/main.go b/tools/eth1exporter/main.go index cadef226e18..6fa1bd0791b 100644 --- a/tools/eth1exporter/main.go +++ b/tools/eth1exporter/main.go @@ -60,7 +60,7 @@ func main() { t1 := time.Now() fmt.Printf("Checking %v wallets...\n", len(allWatching)) for _, v := range allWatching { - v.Balance = GetEthBalance(v.Address).String() + v.Balance = EthBalance(v.Address).String() totalLoaded++ } t2 := time.Now() @@ -93,8 +93,8 @@ func ConnectionToGeth(url string) error { return err } -// GetEthBalance from remote server. -func GetEthBalance(address string) *big.Float { +// EthBalance from remote server. +func EthBalance(address string) *big.Float { balance, err := eth.BalanceAt(context.TODO(), common.HexToAddress(address), nil) if err != nil { fmt.Printf("Error fetching ETH Balance for address: %v\n", address) diff --git a/tools/pcli/main.go b/tools/pcli/main.go index dde5c526896..bccc3242127 100644 --- a/tools/pcli/main.go +++ b/tools/pcli/main.go @@ -37,7 +37,7 @@ func main() { app := cli.App{} app.Name = "pcli" app.Usage = "A command line utility to run eth2 specific commands" - app.Version = version.GetVersion() + app.Version = version.Version() app.Commands = []*cli.Command{ { Name: "pretty", diff --git a/validator/client/validator.go b/validator/client/validator.go index b0813ae7d80..0cb803b9c01 100644 --- a/validator/client/validator.go +++ b/validator/client/validator.go @@ -173,7 +173,7 @@ func (v *validator) WaitForChainStart(ctx context.Context) error { // Once the ChainStart log is received, we update the genesis time of the validator client // and begin a slot ticker used to track the current slot the beacon node is in. - v.ticker = slotutil.GetSlotTicker(time.Unix(int64(v.genesisTime), 0), params.BeaconConfig().SecondsPerSlot) + v.ticker = slotutil.NewSlotTicker(time.Unix(int64(v.genesisTime), 0), params.BeaconConfig().SecondsPerSlot) log.WithField("genesisTime", time.Unix(int64(v.genesisTime), 0)).Info("Beacon chain started") return nil } diff --git a/validator/client/wait_for_activation.go b/validator/client/wait_for_activation.go index 393fa0747b2..ac384b0469f 100644 --- a/validator/client/wait_for_activation.go +++ b/validator/client/wait_for_activation.go @@ -58,7 +58,7 @@ func (v *validator) WaitForActivation(ctx context.Context, accountsChangedChan c stream, err := v.validatorClient.WaitForActivation(ctx, req) if err != nil { traceutil.AnnotateError(span, err) - attempts := getStreamAttempts(ctx) + attempts := streamAttempts(ctx) log.WithError(err).WithField("attempts", attempts). Error("Stream broken while waiting for activation. Reconnecting...") // Reconnection attempt backoff, up to 60s. @@ -82,7 +82,7 @@ func (v *validator) WaitForActivation(ctx context.Context, accountsChangedChan c } if err != nil { traceutil.AnnotateError(span, err) - attempts := getStreamAttempts(ctx) + attempts := streamAttempts(ctx) log.WithError(err).WithField("attempts", attempts). Error("Stream broken while waiting for activation. Reconnecting...") // Reconnection attempt backoff, up to 60s. @@ -108,7 +108,7 @@ func (v *validator) WaitForActivation(ctx context.Context, accountsChangedChan c break } - v.ticker = slotutil.GetSlotTicker(time.Unix(int64(v.genesisTime), 0), params.BeaconConfig().SecondsPerSlot) + v.ticker = slotutil.NewSlotTicker(time.Unix(int64(v.genesisTime), 0), params.BeaconConfig().SecondsPerSlot) return nil } @@ -117,7 +117,7 @@ type waitForActivationContextKey string const waitForActivationAttemptsContextKey = waitForActivationContextKey("WaitForActivation-attempts") -func getStreamAttempts(ctx context.Context) int { +func streamAttempts(ctx context.Context) int { attempts, ok := ctx.Value(waitForActivationAttemptsContextKey).(int) if !ok { return 1 @@ -126,6 +126,6 @@ func getStreamAttempts(ctx context.Context) int { } func incrementRetries(ctx context.Context) context.Context { - attempts := getStreamAttempts(ctx) + attempts := streamAttempts(ctx) return context.WithValue(ctx, waitForActivationAttemptsContextKey, attempts+1) } diff --git a/validator/main.go b/validator/main.go index 54696210fae..170bc1ec038 100644 --- a/validator/main.go +++ b/validator/main.go @@ -106,7 +106,7 @@ func main() { app := cli.App{} app.Name = "validator" app.Usage = `launches an Ethereum 2.0 validator client that interacts with a beacon chain, starts proposer and attester services, p2p connections, and more` - app.Version = version.GetVersion() + app.Version = version.Version() app.Action = startNode app.Commands = []*cli.Command{ accounts.WalletCommands, diff --git a/validator/node/node.go b/validator/node/node.go index 17ae6f717cd..3e6677acfe9 100644 --- a/validator/node/node.go +++ b/validator/node/node.go @@ -123,7 +123,7 @@ func (c *ValidatorClient) Start() { c.lock.Lock() log.WithFields(logrus.Fields{ - "version": version.GetVersion(), + "version": version.Version(), }).Info("Starting validator node") c.services.StartAll() diff --git a/validator/rpc/health.go b/validator/rpc/health.go index eca20b7cc8e..8c9d02854a6 100644 --- a/validator/rpc/health.go +++ b/validator/rpc/health.go @@ -51,7 +51,7 @@ func (s *Server) GetVersion(ctx context.Context, _ *ptypes.Empty) (*pb.VersionRe return &pb.VersionResponse{ Beacon: beacon.Version, - Validator: version.GetVersion(), + Validator: version.Version(), }, nil } diff --git a/validator/slashing-protection/local/standard-protection-format/export.go b/validator/slashing-protection/local/standard-protection-format/export.go index 8fbe463510d..215c759865a 100644 --- a/validator/slashing-protection/local/standard-protection-format/export.go +++ b/validator/slashing-protection/local/standard-protection-format/export.go @@ -45,7 +45,7 @@ func ExportStandardProtectionJSON(ctx context.Context, validatorDB db.Database) if err != nil { return nil, err } - signedBlocks, err := getSignedBlocksByPubKey(ctx, validatorDB, pubKey) + signedBlocks, err := signedBlocksByPubKey(ctx, validatorDB, pubKey) if err != nil { return nil, err } @@ -62,7 +62,7 @@ func ExportStandardProtectionJSON(ctx context.Context, validatorDB db.Database) if err != nil { return nil, err } - signedAttestations, err := getSignedAttestationsByPubKey(ctx, validatorDB, pubKey) + signedAttestations, err := signedAttestationsByPubKey(ctx, validatorDB, pubKey) if err != nil { return nil, err } @@ -95,7 +95,7 @@ func ExportStandardProtectionJSON(ctx context.Context, validatorDB db.Database) return interchangeJSON, nil } -func getSignedAttestationsByPubKey(ctx context.Context, validatorDB db.Database, pubKey [48]byte) ([]*format.SignedAttestation, error) { +func signedAttestationsByPubKey(ctx context.Context, validatorDB db.Database, pubKey [48]byte) ([]*format.SignedAttestation, error) { // If a key does not have an attestation history in our database, we return nil. // This way, a user will be able to export their slashing protection history // even if one of their keys does not have a history of signed attestations. @@ -124,7 +124,7 @@ func getSignedAttestationsByPubKey(ctx context.Context, validatorDB db.Database, return signedAttestations, nil } -func getSignedBlocksByPubKey(ctx context.Context, validatorDB db.Database, pubKey [48]byte) ([]*format.SignedBlock, error) { +func signedBlocksByPubKey(ctx context.Context, validatorDB db.Database, pubKey [48]byte) ([]*format.SignedBlock, error) { // If a key does not have a lowest or highest signed proposal history // in our database, we return nil. This way, a user will be able to export their // slashing protection history even if one of their keys does not have a history diff --git a/validator/slashing-protection/local/standard-protection-format/export_test.go b/validator/slashing-protection/local/standard-protection-format/export_test.go index d4b9695c69f..7b6e9b3013e 100644 --- a/validator/slashing-protection/local/standard-protection-format/export_test.go +++ b/validator/slashing-protection/local/standard-protection-format/export_test.go @@ -19,7 +19,7 @@ func Test_getSignedAttestationsByPubKey(t *testing.T) { validatorDB := dbtest.SetupDB(t, pubKeys) // No attestation history stored should return empty. - signedAttestations, err := getSignedAttestationsByPubKey(ctx, validatorDB, pubKeys[0]) + signedAttestations, err := signedAttestationsByPubKey(ctx, validatorDB, pubKeys[0]) require.NoError(t, err) assert.Equal(t, 0, len(signedAttestations)) @@ -37,7 +37,7 @@ func Test_getSignedAttestationsByPubKey(t *testing.T) { ))) // We then retrieve the signed attestations and expect a correct result. - signedAttestations, err = getSignedAttestationsByPubKey(ctx, validatorDB, pubKeys[0]) + signedAttestations, err = signedAttestationsByPubKey(ctx, validatorDB, pubKeys[0]) require.NoError(t, err) wanted := []*format.SignedAttestation{ @@ -63,7 +63,7 @@ func Test_getSignedBlocksByPubKey(t *testing.T) { validatorDB := dbtest.SetupDB(t, pubKeys) // No highest and/or lowest signed blocks will return empty. - signedBlocks, err := getSignedBlocksByPubKey(ctx, validatorDB, pubKeys[0]) + signedBlocks, err := signedBlocksByPubKey(ctx, validatorDB, pubKeys[0]) require.NoError(t, err) assert.Equal(t, 0, len(signedBlocks)) @@ -83,7 +83,7 @@ func Test_getSignedBlocksByPubKey(t *testing.T) { // We expect a valid proposal history containing slot 1 and slot 5 only // when we attempt to retrieve it from disk. - signedBlocks, err = getSignedBlocksByPubKey(ctx, validatorDB, pubKeys[0]) + signedBlocks, err = signedBlocksByPubKey(ctx, validatorDB, pubKeys[0]) require.NoError(t, err) wanted := []*format.SignedBlock{ {