From d2f4a8cc7c53a684ab2f420f5ed6dc527143a477 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5vard=20Anda=20Estensen?= Date: Mon, 18 Apr 2022 22:42:07 +0200 Subject: [PATCH] Replace ioutil with io and os (#10541) * Replace ioutil with io and os * Fix build errors --- api/client/beacon/client.go | 3 +-- api/gateway/apimiddleware/process_request.go | 9 ++++---- beacon-chain/blockchain/blockchain_test.go | 4 ++-- .../blockchain/service_norace_test.go | 4 ++-- .../blocks/attestation_regression_test.go | 6 ++--- beacon-chain/core/blocks/header_test.go | 4 ++-- .../proposer_slashing_regression_test.go | 6 ++--- beacon-chain/db/kv/backup_test.go | 5 ++--- beacon-chain/db/restore_test.go | 3 +-- beacon-chain/db/slasherkv/slasherkv_test.go | 4 ++-- beacon-chain/deterministic-genesis/service.go | 4 ++-- beacon-chain/node/registration/p2p.go | 4 ++-- beacon-chain/node/registration/p2p_test.go | 10 ++++----- beacon-chain/p2p/options_test.go | 6 ++--- beacon-chain/p2p/peers/peers_test.go | 4 ++-- .../p2p/peers/scorers/scorers_test.go | 4 ++-- beacon-chain/p2p/utils.go | 5 ++--- beacon-chain/powchain/engine_client_test.go | 12 +++++----- beacon-chain/powchain/powchain_test.go | 4 ++-- .../rpc/apimiddleware/custom_handlers.go | 3 +-- .../rpc/apimiddleware/custom_hooks.go | 22 +++++++++---------- .../v1alpha1/validator/validator_test.go | 4 ++-- beacon-chain/rpc/service_test.go | 4 ++-- beacon-chain/slasher/service_test.go | 4 ++-- .../sync/initial-sync/initial_sync_test.go | 4 ++-- beacon-chain/sync/sync_test.go | 4 ++-- cmd/flags_test.go | 3 +-- config/params/loader.go | 4 ++-- config/params/loader_test.go | 6 ++--- crypto/keystore/key.go | 3 +-- crypto/keystore/key_test.go | 4 ++-- crypto/keystore/keystore.go | 16 ++++++++------ io/file/fileutil.go | 7 +++--- io/file/fileutil_test.go | 13 +++++------ io/prompt/prompt.go | 3 +-- io/prompt/validate_test.go | 3 +-- .../prometheus/logrus_collector_test.go | 4 ++-- monitoring/prometheus/service_test.go | 4 ++-- .../attestations/attestations_test.go | 4 ++-- runtime/interop/generate_keys_test.go | 4 ++-- runtime/tos/tos_test.go | 5 ++--- testing/benchmark/pregen.go | 8 +++---- testing/bls/utils/utils.go | 4 ++-- testing/endtoend/components/boot_node.go | 4 ++-- testing/endtoend/components/eth1/miner.go | 5 ++--- .../endtoend/components/eth1/transactions.go | 4 ++-- testing/endtoend/components/validator.go | 3 +-- testing/endtoend/evaluators/metrics.go | 4 ++-- testing/endtoend/evaluators/node.go | 6 ++--- testing/endtoend/helpers/helpers.go | 11 +++++----- .../shared/altair/epoch_processing/helpers.go | 4 ++-- .../shared/altair/operations/block_header.go | 4 ++-- .../shared/altair/operations/helpers.go | 4 ++-- .../shared/altair/sanity/block_processing.go | 4 ++-- .../bellatrix/epoch_processing/helpers.go | 4 ++-- .../bellatrix/operations/block_header.go | 4 ++-- .../shared/bellatrix/operations/helpers.go | 4 ++-- .../bellatrix/sanity/block_processing.go | 4 ++-- .../shared/phase0/epoch_processing/helpers.go | 4 ++-- .../shared/phase0/operations/block_header.go | 4 ++-- .../shared/phase0/operations/helpers.go | 4 ++-- .../shared/phase0/sanity/block_processing.go | 4 ++-- testing/spectest/utils/utils.go | 5 ++--- testing/util/bazel.go | 7 +++--- time/slots/slotutil_test.go | 4 ++-- .../testdata/custom_imports.go | 3 +-- .../testdata/regular_imports.go | 3 +-- tools/beacon-fuzz/main.go | 3 +-- tools/benchmark-files-gen/main.go | 3 +-- tools/bootnode/bootnode_test.go | 4 ++-- tools/genesis-state-gen/main.go | 3 +-- tools/http-request-sink/main.go | 6 ++--- tools/http-request-sink/main_test.go | 4 ++-- tools/interop/convert-keys/main.go | 3 +-- tools/keystores/main.go | 5 ++--- tools/keystores/main_test.go | 8 +++---- tools/pcli/main.go | 3 +-- tools/specs-checker/download.go | 4 ++-- validator/accounts/accounts_backup_test.go | 12 +++++----- validator/accounts/accounts_import.go | 10 ++++----- validator/accounts/accounts_import_test.go | 11 +++++----- validator/accounts/accounts_list_test.go | 10 ++++----- validator/accounts/wallet/wallet.go | 3 +-- validator/accounts/wallet/wallet_test.go | 4 ++-- validator/accounts/wallet_create_test.go | 6 ++--- validator/accounts/wallet_recover.go | 3 +-- validator/accounts/wallet_recover_test.go | 5 ++--- validator/client/validator_test.go | 4 ++-- validator/db/kv/backup_test.go | 5 ++--- validator/db/kv/kv_test.go | 4 ++-- validator/db/restore_test.go | 3 +-- validator/graffiti/parse_graffiti.go | 4 ++-- validator/graffiti/parse_graffiti_test.go | 11 +++++----- validator/keymanager/local/refresh.go | 4 ++-- .../remote-web3signer/internal/client.go | 5 ++--- .../remote-web3signer/internal/client_test.go | 18 +++++++-------- validator/keymanager/remote/keymanager.go | 6 ++--- .../keymanager/remote/keymanager_test.go | 10 ++++----- validator/node/node.go | 3 +-- validator/node/node_test.go | 5 ++--- validator/rpc/accounts_test.go | 4 ++-- .../slashing-protection-history/import.go | 3 +-- 102 files changed, 256 insertions(+), 291 deletions(-) diff --git a/api/client/beacon/client.go b/api/client/beacon/client.go index 0521342fd..fa807ca18 100644 --- a/api/client/beacon/client.go +++ b/api/client/beacon/client.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -369,7 +368,7 @@ type WeakSubjectivityData struct { } func non200Err(response *http.Response) error { - bodyBytes, err := ioutil.ReadAll(response.Body) + bodyBytes, err := io.ReadAll(response.Body) var body string if err != nil { body = "(Unable to read response body.)" diff --git a/api/gateway/apimiddleware/process_request.go b/api/gateway/apimiddleware/process_request.go index c02e848ba..a03eaa9f9 100644 --- a/api/gateway/apimiddleware/process_request.go +++ b/api/gateway/apimiddleware/process_request.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "io" - "io/ioutil" "net" "net/http" "strconv" @@ -52,7 +51,7 @@ func SetRequestBodyToRequestContainer(requestContainer interface{}, req *http.Re return InternalServerErrorWithMessage(err, "could not marshal request") } // Set the body to the new JSON. - req.Body = ioutil.NopCloser(bytes.NewReader(j)) + req.Body = io.NopCloser(bytes.NewReader(j)) req.Header.Set("Content-Length", strconv.Itoa(len(j))) req.ContentLength = int64(len(j)) return nil @@ -93,7 +92,7 @@ func (m *ApiProxyMiddleware) ProxyRequest(req *http.Request) (*http.Response, Er // ReadGrpcResponseBody reads the body from the grpc-gateway's response. func ReadGrpcResponseBody(r io.Reader) ([]byte, ErrorJson) { - body, err := ioutil.ReadAll(r) + body, err := io.ReadAll(r) if err != nil { return nil, InternalServerErrorWithMessage(err, "could not read response body") } @@ -195,7 +194,7 @@ func WriteMiddlewareResponseHeadersAndBody(grpcResp *http.Response, responseJson } else { w.WriteHeader(grpcResp.StatusCode) } - if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(responseJson))); err != nil { + if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(responseJson))); err != nil { return InternalServerErrorWithMessage(err, "could not write response message") } } else { @@ -249,7 +248,7 @@ func WriteError(w http.ResponseWriter, errJson ErrorJson, responseHeader http.He w.Header().Set("Content-Length", strconv.Itoa(len(j))) w.Header().Set("Content-Type", "application/json") w.WriteHeader(errJson.StatusCode()) - if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(j))); err != nil { + if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil { log.WithError(err).Error("Could not write error message") } } diff --git a/beacon-chain/blockchain/blockchain_test.go b/beacon-chain/blockchain/blockchain_test.go index a1ea69142..9082070a2 100644 --- a/beacon-chain/blockchain/blockchain_test.go +++ b/beacon-chain/blockchain/blockchain_test.go @@ -1,7 +1,7 @@ package blockchain import ( - "io/ioutil" + "io" "testing" "github.com/sirupsen/logrus" @@ -9,7 +9,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/beacon-chain/blockchain/service_norace_test.go b/beacon-chain/blockchain/service_norace_test.go index 173d2acd6..fe76820c4 100644 --- a/beacon-chain/blockchain/service_norace_test.go +++ b/beacon-chain/blockchain/service_norace_test.go @@ -2,7 +2,7 @@ package blockchain import ( "context" - "io/ioutil" + "io" "testing" testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing" @@ -14,7 +14,7 @@ import ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } func TestChainService_SaveHead_DataRace(t *testing.T) { diff --git a/beacon-chain/core/blocks/attestation_regression_test.go b/beacon-chain/core/blocks/attestation_regression_test.go index 21779a305..479945b65 100644 --- a/beacon-chain/core/blocks/attestation_regression_test.go +++ b/beacon-chain/core/blocks/attestation_regression_test.go @@ -2,7 +2,7 @@ package blocks_test import ( "context" - "io/ioutil" + "os" "testing" "github.com/prysmaticlabs/go-bitfield" @@ -20,7 +20,7 @@ import ( // valid att.Data.Committee index would be 0, so this is an off by one error. // See: https://github.com/sigp/beacon-fuzz/issues/78 func TestProcessAttestationNoVerifySignature_BeaconFuzzIssue78(t *testing.T) { - attData, err := ioutil.ReadFile("testdata/beaconfuzz_78_attestation.ssz") + attData, err := os.ReadFile("testdata/beaconfuzz_78_attestation.ssz") if err != nil { t.Fatal(err) } @@ -28,7 +28,7 @@ func TestProcessAttestationNoVerifySignature_BeaconFuzzIssue78(t *testing.T) { if err := att.UnmarshalSSZ(attData); err != nil { t.Fatal(err) } - stateData, err := ioutil.ReadFile("testdata/beaconfuzz_78_beacon.ssz") + stateData, err := os.ReadFile("testdata/beaconfuzz_78_beacon.ssz") if err != nil { t.Fatal(err) } diff --git a/beacon-chain/core/blocks/header_test.go b/beacon-chain/core/blocks/header_test.go index aa1b2b046..ed79b0686 100644 --- a/beacon-chain/core/blocks/header_test.go +++ b/beacon-chain/core/blocks/header_test.go @@ -2,7 +2,7 @@ package blocks_test import ( "context" - "io/ioutil" + "io" "testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" @@ -23,7 +23,7 @@ import ( ) func init() { - logrus.SetOutput(ioutil.Discard) // Ignore "validator activated" logs + logrus.SetOutput(io.Discard) // Ignore "validator activated" logs } func TestProcessBlockHeader_ImproperBlockSlot(t *testing.T) { diff --git a/beacon-chain/core/blocks/proposer_slashing_regression_test.go b/beacon-chain/core/blocks/proposer_slashing_regression_test.go index 02e181c1a..0c3ad1f94 100644 --- a/beacon-chain/core/blocks/proposer_slashing_regression_test.go +++ b/beacon-chain/core/blocks/proposer_slashing_regression_test.go @@ -1,7 +1,7 @@ package blocks_test import ( - "io/ioutil" + "os" "testing" "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks" @@ -16,7 +16,7 @@ import ( // when it was not in actuality. // See: https://github.com/sigp/beacon-fuzz/issues/91 func TestVerifyProposerSlashing_BeaconFuzzIssue91(t *testing.T) { - file, err := ioutil.ReadFile("testdata/beaconfuzz_91_beacon.ssz") + file, err := os.ReadFile("testdata/beaconfuzz_91_beacon.ssz") require.NoError(t, err) rawState := ðpb.BeaconState{} err = rawState.UnmarshalSSZ(file) @@ -25,7 +25,7 @@ func TestVerifyProposerSlashing_BeaconFuzzIssue91(t *testing.T) { st, err := v1.InitializeFromProtoUnsafe(rawState) require.NoError(t, err) - file, err = ioutil.ReadFile("testdata/beaconfuzz_91_proposer_slashing.ssz") + file, err = os.ReadFile("testdata/beaconfuzz_91_proposer_slashing.ssz") require.NoError(t, err) slashing := ðpb.ProposerSlashing{} err = slashing.UnmarshalSSZ(file) diff --git a/beacon-chain/db/kv/backup_test.go b/beacon-chain/db/kv/backup_test.go index 77555b596..e66f22516 100644 --- a/beacon-chain/db/kv/backup_test.go +++ b/beacon-chain/db/kv/backup_test.go @@ -2,7 +2,6 @@ package kv import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -34,7 +33,7 @@ func TestStore_Backup(t *testing.T) { require.NoError(t, db.Backup(ctx, "", false)) backupsPath := filepath.Join(db.databasePath, backupsDirectoryName) - files, err := ioutil.ReadDir(backupsPath) + files, err := os.ReadDir(backupsPath) require.NoError(t, err) require.NotEqual(t, 0, len(files), "No backups created") require.NoError(t, db.Close(), "Failed to close database") @@ -78,7 +77,7 @@ func TestStore_BackupMultipleBuckets(t *testing.T) { require.NoError(t, db.Backup(ctx, "", false)) backupsPath := filepath.Join(db.databasePath, backupsDirectoryName) - files, err := ioutil.ReadDir(backupsPath) + files, err := os.ReadDir(backupsPath) require.NoError(t, err) require.NotEqual(t, 0, len(files), "No backups created") require.NoError(t, db.Close(), "Failed to close database") diff --git a/beacon-chain/db/restore_test.go b/beacon-chain/db/restore_test.go index 2d3a15fae..f5559f3e9 100644 --- a/beacon-chain/db/restore_test.go +++ b/beacon-chain/db/restore_test.go @@ -3,7 +3,6 @@ package db import ( "context" "flag" - "io/ioutil" "os" "path" "testing" @@ -55,7 +54,7 @@ func TestRestore(t *testing.T) { assert.NoError(t, Restore(cliCtx)) - files, err := ioutil.ReadDir(path.Join(restoreDir, kv.BeaconNodeDbDirName)) + files, err := os.ReadDir(path.Join(restoreDir, kv.BeaconNodeDbDirName)) require.NoError(t, err) assert.Equal(t, 1, len(files)) assert.Equal(t, kv.DatabaseFileName, files[0].Name()) diff --git a/beacon-chain/db/slasherkv/slasherkv_test.go b/beacon-chain/db/slasherkv/slasherkv_test.go index 5c99813d8..000a279d9 100644 --- a/beacon-chain/db/slasherkv/slasherkv_test.go +++ b/beacon-chain/db/slasherkv/slasherkv_test.go @@ -1,7 +1,7 @@ package slasherkv import ( - "io/ioutil" + "io" "testing" "github.com/sirupsen/logrus" @@ -9,6 +9,6 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/beacon-chain/deterministic-genesis/service.go b/beacon-chain/deterministic-genesis/service.go index adf167340..d199ef761 100644 --- a/beacon-chain/deterministic-genesis/service.go +++ b/beacon-chain/deterministic-genesis/service.go @@ -5,8 +5,8 @@ package interopcoldstart import ( "context" - "io/ioutil" "math/big" + "os" "time" types "github.com/prysmaticlabs/eth2-types" @@ -61,7 +61,7 @@ func (s *Service) Start() { log.Warn("Saving generated genesis state in database for interop testing") if s.cfg.GenesisPath != "" { - data, err := ioutil.ReadFile(s.cfg.GenesisPath) + data, err := os.ReadFile(s.cfg.GenesisPath) if err != nil { log.Fatalf("Could not read pre-loaded state: %v", err) } diff --git a/beacon-chain/node/registration/p2p.go b/beacon-chain/node/registration/p2p.go index 7e01e3592..fcc70a467 100644 --- a/beacon-chain/node/registration/p2p.go +++ b/beacon-chain/node/registration/p2p.go @@ -1,7 +1,7 @@ package registration import ( - "io/ioutil" + "os" "path/filepath" "github.com/prysmaticlabs/prysm/cmd" @@ -42,7 +42,7 @@ func P2PPreregistration(cliCtx *cli.Context) (bootstrapNodeAddrs []string, dataD } func readbootNodes(fileName string) ([]string, error) { - fileContent, err := ioutil.ReadFile(fileName) // #nosec G304 + fileContent, err := os.ReadFile(fileName) // #nosec G304 if err != nil { return nil, err } diff --git a/beacon-chain/node/registration/p2p_test.go b/beacon-chain/node/registration/p2p_test.go index 2f42e8a0d..a838a799a 100644 --- a/beacon-chain/node/registration/p2p_test.go +++ b/beacon-chain/node/registration/p2p_test.go @@ -2,7 +2,7 @@ package registration import ( "flag" - "io/ioutil" + "os" "testing" "github.com/prysmaticlabs/prysm/cmd" @@ -27,9 +27,9 @@ func TestP2PPreregistration(t *testing.T) { sampleNode := "- enr:-TESTNODE" testDataDir := "testDataDir" - file, err := ioutil.TempFile(t.TempDir(), "bootstrapFile*.yaml") + file, err := os.CreateTemp(t.TempDir(), "bootstrapFile*.yaml") require.NoError(t, err) - err = ioutil.WriteFile(file.Name(), []byte(sampleNode), 0644) + err = os.WriteFile(file.Name(), []byte(sampleNode), 0644) require.NoError(t, err, "Error in WriteFile call") params.SetupTestConfigCleanup(t) config := params.BeaconNetworkConfig() @@ -49,7 +49,7 @@ func TestP2PPreregistration(t *testing.T) { } func TestBootStrapNodeFile(t *testing.T) { - file, err := ioutil.TempFile(t.TempDir(), "bootstrapFile") + file, err := os.CreateTemp(t.TempDir(), "bootstrapFile") require.NoError(t, err) sampleNode0 := "- enr:-Ku4QMKVC_MowDsmEa20d5uGjrChI0h8_KsKXDmgVQbIbngZV0i" + @@ -58,7 +58,7 @@ func TestBootStrapNodeFile(t *testing.T) { "E1rtwzvGy40mq9eD66XfHPBWgIIN1ZHCCD6A" sampleNode1 := "- enr:-TESTNODE2" sampleNode2 := "- enr:-TESTNODE3" - err = ioutil.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644) + err = os.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644) require.NoError(t, err, "Error in WriteFile call") nodeList, err := readbootNodes(file.Name()) require.NoError(t, err, "Error in readbootNodes call") diff --git a/beacon-chain/p2p/options_test.go b/beacon-chain/p2p/options_test.go index 558ee50c8..56802fbe6 100644 --- a/beacon-chain/p2p/options_test.go +++ b/beacon-chain/p2p/options_test.go @@ -3,8 +3,8 @@ package p2p import ( "crypto/rand" "encoding/hex" - "io/ioutil" "net" + "os" "testing" gethCrypto "github.com/ethereum/go-ethereum/crypto" @@ -17,7 +17,7 @@ import ( ) func TestPrivateKeyLoading(t *testing.T) { - file, err := ioutil.TempFile(t.TempDir(), "key") + file, err := os.CreateTemp(t.TempDir(), "key") require.NoError(t, err) key, _, err := crypto.GenerateSecp256k1Key(rand.Reader) require.NoError(t, err, "Could not generate key") @@ -27,7 +27,7 @@ func TestPrivateKeyLoading(t *testing.T) { } out := hex.EncodeToString(raw) - err = ioutil.WriteFile(file.Name(), []byte(out), params.BeaconIoConfig().ReadWritePermissions) + err = os.WriteFile(file.Name(), []byte(out), params.BeaconIoConfig().ReadWritePermissions) require.NoError(t, err, "Could not write key to file") log.WithField("file", file.Name()).WithField("key", out).Info("Wrote key to file") cfg := &Config{ diff --git a/beacon-chain/p2p/peers/peers_test.go b/beacon-chain/p2p/peers/peers_test.go index e2e8bddf0..57e45ad8c 100644 --- a/beacon-chain/p2p/peers/peers_test.go +++ b/beacon-chain/p2p/peers/peers_test.go @@ -1,7 +1,7 @@ package peers_test import ( - "io/ioutil" + "io" "testing" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" @@ -11,7 +11,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) resetCfg := features.InitWithReset(&features.Flags{ EnablePeerScorer: true, diff --git a/beacon-chain/p2p/peers/scorers/scorers_test.go b/beacon-chain/p2p/peers/scorers/scorers_test.go index 3b2d3ccad..5e4dfb4bc 100644 --- a/beacon-chain/p2p/peers/scorers/scorers_test.go +++ b/beacon-chain/p2p/peers/scorers/scorers_test.go @@ -1,7 +1,7 @@ package scorers_test import ( - "io/ioutil" + "io" "math" "testing" @@ -13,7 +13,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) resetCfg := features.InitWithReset(&features.Flags{ EnablePeerScorer: true, diff --git a/beacon-chain/p2p/utils.go b/beacon-chain/p2p/utils.go index a72a300c7..f2e2ef9e0 100644 --- a/beacon-chain/p2p/utils.go +++ b/beacon-chain/p2p/utils.go @@ -7,7 +7,6 @@ import ( "encoding/base64" "encoding/hex" "fmt" - "io/ioutil" "net" "os" "path" @@ -89,7 +88,7 @@ func privKey(cfg *Config) (*ecdsa.PrivateKey, error) { // Retrieves a p2p networking private key from a file path. func privKeyFromFile(path string) (*ecdsa.PrivateKey, error) { - src, err := ioutil.ReadFile(path) // #nosec G304 + src, err := os.ReadFile(path) // #nosec G304 if err != nil { log.WithError(err).Error("Error reading private key from file") return nil, err @@ -135,7 +134,7 @@ func metaDataFromConfig(cfg *Config) (metadata.Metadata, error) { if defaultMetadataExist && metaDataPath == "" { metaDataPath = defaultKeyPath } - src, err := ioutil.ReadFile(metaDataPath) // #nosec G304 + src, err := os.ReadFile(metaDataPath) // #nosec G304 if err != nil { log.WithError(err).Error("Error reading metadata from file") return nil, err diff --git a/beacon-chain/powchain/engine_client_test.go b/beacon-chain/powchain/engine_client_test.go index b0f808e97..62524a8b8 100644 --- a/beacon-chain/powchain/engine_client_test.go +++ b/beacon-chain/powchain/engine_client_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "math/big" "net/http" "net/http/httptest" @@ -100,7 +100,7 @@ func TestClient_HTTP(t *testing.T) { defer func() { require.NoError(t, r.Body.Close()) }() - enc, err := ioutil.ReadAll(r.Body) + enc, err := io.ReadAll(r.Body) require.NoError(t, err) jsonRequestString := string(enc) @@ -350,7 +350,7 @@ func TestClient_HTTP(t *testing.T) { defer func() { require.NoError(t, r.Body.Close()) }() - enc, err := ioutil.ReadAll(r.Body) + enc, err := io.ReadAll(r.Body) require.NoError(t, err) jsonRequestString := string(enc) // We expect the JSON string RPC request contains the right arguments. @@ -387,7 +387,7 @@ func TestClient_HTTP(t *testing.T) { defer func() { require.NoError(t, r.Body.Close()) }() - enc, err := ioutil.ReadAll(r.Body) + enc, err := io.ReadAll(r.Body) require.NoError(t, err) jsonRequestString := string(enc) // We expect the JSON string RPC request contains the right arguments. @@ -972,7 +972,7 @@ func forkchoiceUpdateSetup(t *testing.T, fcs *pb.ForkchoiceState, att *pb.Payloa defer func() { require.NoError(t, r.Body.Close()) }() - enc, err := ioutil.ReadAll(r.Body) + enc, err := io.ReadAll(r.Body) require.NoError(t, err) jsonRequestString := string(enc) @@ -1011,7 +1011,7 @@ func newPayloadSetup(t *testing.T, status *pb.PayloadStatus, payload *pb.Executi defer func() { require.NoError(t, r.Body.Close()) }() - enc, err := ioutil.ReadAll(r.Body) + enc, err := io.ReadAll(r.Body) require.NoError(t, err) jsonRequestString := string(enc) diff --git a/beacon-chain/powchain/powchain_test.go b/beacon-chain/powchain/powchain_test.go index f7a1c5aa3..052fe0af5 100644 --- a/beacon-chain/powchain/powchain_test.go +++ b/beacon-chain/powchain/powchain_test.go @@ -1,7 +1,7 @@ package powchain import ( - "io/ioutil" + "io" "testing" "github.com/sirupsen/logrus" @@ -9,7 +9,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/beacon-chain/rpc/apimiddleware/custom_handlers.go b/beacon-chain/rpc/apimiddleware/custom_handlers.go index d85511c15..597ef0cb3 100644 --- a/beacon-chain/rpc/apimiddleware/custom_handlers.go +++ b/beacon-chain/rpc/apimiddleware/custom_handlers.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -179,7 +178,7 @@ func writeSSZResponseHeaderAndBody(grpcResp *http.Response, w http.ResponseWrite } else { w.WriteHeader(grpcResp.StatusCode) } - if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(respSsz))); err != nil { + if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(respSsz))); err != nil { return apimiddleware.InternalServerErrorWithMessage(err, "could not write response message") } return nil diff --git a/beacon-chain/rpc/apimiddleware/custom_hooks.go b/beacon-chain/rpc/apimiddleware/custom_hooks.go index e2716c4e3..d47862ff1 100644 --- a/beacon-chain/rpc/apimiddleware/custom_hooks.go +++ b/beacon-chain/rpc/apimiddleware/custom_hooks.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "strconv" "strings" @@ -36,7 +36,7 @@ func wrapFeeRecipientsArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) return true, nil } @@ -57,7 +57,7 @@ func wrapAttestationsArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -79,7 +79,7 @@ func wrapValidatorIndicesArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -101,7 +101,7 @@ func wrapSignedAggregateAndProofArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -123,7 +123,7 @@ func wrapBeaconCommitteeSubscriptionsArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -145,7 +145,7 @@ func wrapSyncCommitteeSubscriptionsArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -167,7 +167,7 @@ func wrapSyncCommitteeSignaturesArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -189,7 +189,7 @@ func wrapSignedContributionAndProofsArray( if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body") } - req.Body = ioutil.NopCloser(bytes.NewReader(b)) + req.Body = io.NopCloser(bytes.NewReader(b)) } return true, nil } @@ -224,7 +224,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint, } }{} - buf, err := ioutil.ReadAll(req.Body) + buf, err := io.ReadAll(req.Body) if err != nil { return false, apimiddleware.InternalServerErrorWithMessage(err, "could not read body") } @@ -243,7 +243,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint, } else { endpoint.PostRequest = &signedBeaconBlockBellatrixContainerJson{} } - req.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) + req.Body = io.NopCloser(bytes.NewBuffer(buf)) return true, nil } diff --git a/beacon-chain/rpc/prysm/v1alpha1/validator/validator_test.go b/beacon-chain/rpc/prysm/v1alpha1/validator/validator_test.go index 1cff72eef..11335f4c5 100644 --- a/beacon-chain/rpc/prysm/v1alpha1/validator/validator_test.go +++ b/beacon-chain/rpc/prysm/v1alpha1/validator/validator_test.go @@ -1,7 +1,7 @@ package validator import ( - "io/ioutil" + "io" "testing" "github.com/prysmaticlabs/prysm/config/params" @@ -10,7 +10,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) // Use minimal config to reduce test setup time. prevConfig := params.BeaconConfig().Copy() defer params.OverrideBeaconConfig(prevConfig) diff --git a/beacon-chain/rpc/service_test.go b/beacon-chain/rpc/service_test.go index c3569d223..3d0d22c4f 100644 --- a/beacon-chain/rpc/service_test.go +++ b/beacon-chain/rpc/service_test.go @@ -3,7 +3,7 @@ package rpc import ( "context" "errors" - "io/ioutil" + "io" "testing" "time" @@ -18,7 +18,7 @@ import ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } func TestLifecycle_OK(t *testing.T) { diff --git a/beacon-chain/slasher/service_test.go b/beacon-chain/slasher/service_test.go index e988ae4f5..4896bbe32 100644 --- a/beacon-chain/slasher/service_test.go +++ b/beacon-chain/slasher/service_test.go @@ -2,7 +2,7 @@ package slasher import ( "context" - "io/ioutil" + "io" "testing" "time" @@ -26,7 +26,7 @@ var _ = SlashingChecker(&mockslasher.MockSlashingChecker{}) func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/beacon-chain/sync/initial-sync/initial_sync_test.go b/beacon-chain/sync/initial-sync/initial_sync_test.go index 9753797c4..c98a45a4b 100644 --- a/beacon-chain/sync/initial-sync/initial_sync_test.go +++ b/beacon-chain/sync/initial-sync/initial_sync_test.go @@ -3,7 +3,7 @@ package initialsync import ( "context" "fmt" - "io/ioutil" + "io" "sync" "testing" "time" @@ -53,7 +53,7 @@ type peerData struct { func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) resetCfg := features.InitWithReset(&features.Flags{ EnablePeerScorer: true, diff --git a/beacon-chain/sync/sync_test.go b/beacon-chain/sync/sync_test.go index 25cfb2b11..0e239003b 100644 --- a/beacon-chain/sync/sync_test.go +++ b/beacon-chain/sync/sync_test.go @@ -1,7 +1,7 @@ package sync import ( - "io/ioutil" + "io" "testing" "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags" @@ -10,7 +10,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) resetFlags := flags.Get() flags.Init(&flags.GlobalFlags{ diff --git a/cmd/flags_test.go b/cmd/flags_test.go index a31fe61ce..b31444b65 100644 --- a/cmd/flags_test.go +++ b/cmd/flags_test.go @@ -2,7 +2,6 @@ package cmd import ( "flag" - "io/ioutil" "os" "testing" @@ -15,7 +14,7 @@ func TestLoadFlagsFromConfig(t *testing.T) { set := flag.NewFlagSet("test", 0) context := cli.NewContext(&app, set, nil) - require.NoError(t, ioutil.WriteFile("flags_test.yaml", []byte("testflag: 100"), 0666)) + require.NoError(t, os.WriteFile("flags_test.yaml", []byte("testflag: 100"), 0666)) require.NoError(t, set.Parse([]string{"test-command", "--" + ConfigFileFlag.Name, "flags_test.yaml"})) command := &cli.Command{ diff --git a/config/params/loader.go b/config/params/loader.go index 5ba4cb112..f2f6af39e 100644 --- a/config/params/loader.go +++ b/config/params/loader.go @@ -3,7 +3,7 @@ package params import ( "encoding/hex" "fmt" - "io/ioutil" + "os" "strings" types "github.com/prysmaticlabs/eth2-types" @@ -27,7 +27,7 @@ func isMinimal(lines []string) bool { // LoadChainConfigFile load, convert hex values into valid param yaml format, // unmarshal , and apply beacon chain config file. func LoadChainConfigFile(chainConfigFileName string, conf *BeaconChainConfig) { - yamlFile, err := ioutil.ReadFile(chainConfigFileName) // #nosec G304 + yamlFile, err := os.ReadFile(chainConfigFileName) // #nosec G304 if err != nil { log.WithError(err).Fatal("Failed to read chain config file.") } diff --git a/config/params/loader_test.go b/config/params/loader_test.go index 55741f39c..ea7ff970c 100644 --- a/config/params/loader_test.go +++ b/config/params/loader_test.go @@ -1,7 +1,7 @@ package params_test import ( - "io/ioutil" + "os" "path" "path/filepath" "reflect" @@ -143,7 +143,7 @@ func TestLoadConfigFile(t *testing.T) { } func TestLoadConfigFile_OverwriteCorrectly(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") require.NoError(t, err) // Set current config to minimal config params.OverrideBeaconConfig(params.MinimalSpecConfig()) @@ -269,7 +269,7 @@ func presetsFilePath(t *testing.T, config string) []string { func fieldsFromYamls(t *testing.T, fps []string) []string { var keys []string for _, fp := range fps { - yamlFile, err := ioutil.ReadFile(fp) + yamlFile, err := os.ReadFile(fp) require.NoError(t, err) m := make(map[string]interface{}) require.NoError(t, yaml.Unmarshal(yamlFile, &m)) diff --git a/crypto/keystore/key.go b/crypto/keystore/key.go index 15740841c..ec97c5c3d 100644 --- a/crypto/keystore/key.go +++ b/crypto/keystore/key.go @@ -21,7 +21,6 @@ package keystore import ( "encoding/hex" "encoding/json" - "io/ioutil" "os" "path/filepath" @@ -167,7 +166,7 @@ func writeKeyFile(fname string, content []byte) error { } // Atomic write: create a temporary hidden file first // then move it into place. TempFile assigns mode 0600. - f, err := ioutil.TempFile(filepath.Dir(fname), "."+filepath.Base(fname)+".tmp") + f, err := os.CreateTemp(filepath.Dir(fname), "."+filepath.Base(fname)+".tmp") if err != nil { return err } diff --git a/crypto/keystore/key_test.go b/crypto/keystore/key_test.go index 2a8a05319..3de824476 100644 --- a/crypto/keystore/key_test.go +++ b/crypto/keystore/key_test.go @@ -2,7 +2,7 @@ package keystore import ( "bytes" - "io/ioutil" + "os" "path" "testing" @@ -65,7 +65,7 @@ func TestWriteFile(t *testing.T) { err := writeKeyFile(tempDir, testKeystore) require.NoError(t, err) - keystore, err := ioutil.ReadFile(tempDir) + keystore, err := os.ReadFile(tempDir) require.NoError(t, err) require.Equal(t, true, bytes.Equal(keystore, testKeystore)) } diff --git a/crypto/keystore/keystore.go b/crypto/keystore/keystore.go index 329003da3..c45679711 100644 --- a/crypto/keystore/keystore.go +++ b/crypto/keystore/keystore.go @@ -27,7 +27,7 @@ import ( "errors" "fmt" "io" - "io/ioutil" + "io/fs" "os" "path/filepath" "strings" @@ -55,7 +55,7 @@ type Keystore struct { // GetKey from file using the filename path and a decryption password. func (_ Keystore) GetKey(filename, password string) (*Key, error) { // Load the key from the keystore and decrypt its contents - keyJSON, err := ioutil.ReadFile(filename) // #nosec G304 -- ReadFile is safe + keyJSON, err := os.ReadFile(filename) // #nosec G304 -- ReadFile is safe if err != nil { return nil, err } @@ -67,7 +67,7 @@ func (_ Keystore) GetKey(filename, password string) (*Key, error) { func (_ Keystore) GetKeys(directory, filePrefix, password string, warnOnFail bool) (map[string]*Key, error) { // Load the key from the keystore and decrypt its contents // #nosec G304 - files, err := ioutil.ReadDir(directory) + files, err := os.ReadDir(directory) if err != nil { return nil, err } @@ -76,19 +76,21 @@ func (_ Keystore) GetKeys(directory, filePrefix, password string, warnOnFail boo n := f.Name() filePath := filepath.Join(directory, n) filePath = filepath.Clean(filePath) - if f.Mode()&os.ModeSymlink == os.ModeSymlink { + if f.Type()&os.ModeSymlink == os.ModeSymlink { if targetFilePath, err := filepath.EvalSymlinks(filePath); err == nil { filePath = targetFilePath // Override link stats with target file's stats. - if f, err = os.Stat(filePath); err != nil { + dirEntry, err := os.Stat(filePath) + if err != nil { return nil, err } + f = fs.FileInfoToDirEntry(dirEntry) } } cp := strings.Contains(n, strings.TrimPrefix(filePrefix, "/")) - if f.Mode().IsRegular() && cp { + if f.Type().IsRegular() && cp { // #nosec G304 - keyJSON, err := ioutil.ReadFile(filePath) + keyJSON, err := os.ReadFile(filePath) if err != nil { return nil, err } diff --git a/io/file/fileutil.go b/io/file/fileutil.go index 8e2545945..37322c668 100644 --- a/io/file/fileutil.go +++ b/io/file/fileutil.go @@ -5,7 +5,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "os" "os/user" "path" @@ -102,7 +101,7 @@ func WriteFile(file string, data []byte) error { return errors.New("file already exists without proper 0600 permissions") } } - return ioutil.WriteFile(expanded, data, params.BeaconIoConfig().ReadWritePermissions) + return os.WriteFile(expanded, data, params.BeaconIoConfig().ReadWritePermissions) } // HomeDir for a user. @@ -197,7 +196,7 @@ func ReadFileAsBytes(filename string) ([]byte, error) { if err != nil { return nil, errors.Wrap(err, "could not determine absolute path of password file") } - return ioutil.ReadFile(filePath) // #nosec G304 + return os.ReadFile(filePath) // #nosec G304 } // CopyFile copy a file from source to destination path. @@ -226,7 +225,7 @@ func CopyDir(src, dst string) error { if dstExists { return errors.New("destination directory already exists") } - fds, err := ioutil.ReadDir(src) + fds, err := os.ReadDir(src) if err != nil { return err } diff --git a/io/file/fileutil_test.go b/io/file/fileutil_test.go index 4ac75b7cc..69c5ac1ab 100644 --- a/io/file/fileutil_test.go +++ b/io/file/fileutil_test.go @@ -18,7 +18,6 @@ package file_test import ( "bufio" "bytes" - "io/ioutil" "os" "os/user" "path/filepath" @@ -112,7 +111,7 @@ func TestWriteFile_AlreadyExists_WrongPermissions(t *testing.T) { err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, []byte("hi"), os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, []byte("hi"), os.ModePerm)) err = file.WriteFile(someFileName, []byte("hi")) assert.ErrorContains(t, "already exists without proper 0600 permissions", err) } @@ -122,7 +121,7 @@ func TestWriteFile_AlreadyExists_OK(t *testing.T) { err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, []byte("hi"), params.BeaconIoConfig().ReadWritePermissions)) + require.NoError(t, os.WriteFile(someFileName, []byte("hi"), params.BeaconIoConfig().ReadWritePermissions)) assert.NoError(t, file.WriteFile(someFileName, []byte("hi"))) } @@ -138,7 +137,7 @@ func TestWriteFile_OK(t *testing.T) { func TestCopyFile(t *testing.T) { fName := t.TempDir() + "testfile" - err := ioutil.WriteFile(fName, []byte{1, 2, 3}, params.BeaconIoConfig().ReadWritePermissions) + err := os.WriteFile(fName, []byte{1, 2, 3}, params.BeaconIoConfig().ReadWritePermissions) require.NoError(t, err) err = file.CopyFile(fName, fName+"copy") @@ -360,7 +359,7 @@ func tmpDirWithContents(t *testing.T) (string, []string) { require.NoError(t, os.MkdirAll(filepath.Join(dir, "subfolder1", "subfolder12"), 0777)) require.NoError(t, os.MkdirAll(filepath.Join(dir, "subfolder2"), 0777)) for _, fname := range fnames { - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, fname), []byte(fname), 0777)) + require.NoError(t, os.WriteFile(filepath.Join(dir, fname), []byte(fname), 0777)) } sort.Strings(fnames) return dir, fnames @@ -378,7 +377,7 @@ func tmpDirWithContentsForRecursiveFind(t *testing.T) (string, []string) { require.NoError(t, os.MkdirAll(filepath.Join(dir, "subfolder1", "subfolder11"), 0777)) require.NoError(t, os.MkdirAll(filepath.Join(dir, "subfolder2"), 0777)) for _, fname := range fnames { - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, fname), []byte(fname), 0777)) + require.NoError(t, os.WriteFile(filepath.Join(dir, fname), []byte(fname), 0777)) } sort.Strings(fnames) return dir, fnames @@ -415,7 +414,7 @@ func TestHasReadWritePermissions(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fullPath := filepath.Join(os.TempDir(), tt.args.itemPath) - require.NoError(t, ioutil.WriteFile(fullPath, []byte("foo"), tt.args.perms)) + require.NoError(t, os.WriteFile(fullPath, []byte("foo"), tt.args.perms)) t.Cleanup(func() { if err := os.RemoveAll(fullPath); err != nil { t.Fatalf("Could not delete temp dir: %v", err) diff --git a/io/prompt/prompt.go b/io/prompt/prompt.go index 73382e282..5419989c0 100644 --- a/io/prompt/prompt.go +++ b/io/prompt/prompt.go @@ -4,7 +4,6 @@ import ( "bufio" "fmt" "io" - "io/ioutil" "os" "strings" @@ -132,7 +131,7 @@ func InputPassword( if err != nil { return "", errors.Wrap(err, "could not determine absolute path of password file") } - data, err := ioutil.ReadFile(passwordFilePath) // #nosec G304 + data, err := os.ReadFile(passwordFilePath) // #nosec G304 if err != nil { return "", errors.Wrap(err, "could not read password file") } diff --git a/io/prompt/validate_test.go b/io/prompt/validate_test.go index badd725a7..4a3f4d210 100644 --- a/io/prompt/validate_test.go +++ b/io/prompt/validate_test.go @@ -1,7 +1,6 @@ package prompt import ( - "io/ioutil" "os" "testing" @@ -114,7 +113,7 @@ func TestDefaultAndValidatePrompt(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { content := []byte(tt.input + "\n") - tmpfile, err := ioutil.TempFile("", "content") + tmpfile, err := os.CreateTemp("", "content") require.NoError(t, err) defer func() { err := os.Remove(tmpfile.Name()) diff --git a/monitoring/prometheus/logrus_collector_test.go b/monitoring/prometheus/logrus_collector_test.go index b106a8758..b71e1dc33 100644 --- a/monitoring/prometheus/logrus_collector_test.go +++ b/monitoring/prometheus/logrus_collector_test.go @@ -2,7 +2,7 @@ package prometheus_test import ( "fmt" - "io/ioutil" + "io" "net/http" "strconv" "strings" @@ -73,7 +73,7 @@ func TestLogrusCollector(t *testing.T) { 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) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) return strings.Split(string(body), "\n") } diff --git a/monitoring/prometheus/service_test.go b/monitoring/prometheus/service_test.go index e9ff054d7..e33f9c697 100644 --- a/monitoring/prometheus/service_test.go +++ b/monitoring/prometheus/service_test.go @@ -2,7 +2,7 @@ package prometheus import ( "errors" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -17,7 +17,7 @@ import ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } func TestLifecycle(t *testing.T) { diff --git a/proto/prysm/v1alpha1/attestation/aggregation/attestations/attestations_test.go b/proto/prysm/v1alpha1/attestation/aggregation/attestations/attestations_test.go index cdbaf71ba..77841e71a 100644 --- a/proto/prysm/v1alpha1/attestation/aggregation/attestations/attestations_test.go +++ b/proto/prysm/v1alpha1/attestation/aggregation/attestations/attestations_test.go @@ -2,7 +2,7 @@ package attestations import ( "fmt" - "io/ioutil" + "io" "sort" "testing" @@ -19,7 +19,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/runtime/interop/generate_keys_test.go b/runtime/interop/generate_keys_test.go index 30b8e9661..8d0caa825 100644 --- a/runtime/interop/generate_keys_test.go +++ b/runtime/interop/generate_keys_test.go @@ -1,7 +1,7 @@ package interop_test import ( - "io/ioutil" + "os" "testing" "github.com/bazelbuild/rules_go/go/tools/bazel" @@ -23,7 +23,7 @@ type KeyTest struct { func TestKeyGenerator(t *testing.T) { path, err := bazel.Runfile("keygen_test_vector.yaml") require.NoError(t, err) - file, err := ioutil.ReadFile(path) + file, err := os.ReadFile(path) require.NoError(t, err) testCases := &KeyTest{} require.NoError(t, yaml.Unmarshal(file, testCases)) diff --git a/runtime/tos/tos_test.go b/runtime/tos/tos_test.go index 331d35fb8..f8fafebfb 100644 --- a/runtime/tos/tos_test.go +++ b/runtime/tos/tos_test.go @@ -2,7 +2,6 @@ package tos import ( "flag" - "io/ioutil" "os" "path/filepath" "testing" @@ -19,7 +18,7 @@ func TestVerifyTosAcceptedOrPrompt(t *testing.T) { context := cli.NewContext(&app, set, nil) // replacing stdin - tmpfile, err := ioutil.TempFile("", "tmp") + tmpfile, err := os.CreateTemp("", "tmp") require.NoError(t, err) origStdin := os.Stdin os.Stdin = tmpfile @@ -48,7 +47,7 @@ func TestVerifyTosAcceptedOrPrompt(t *testing.T) { require.NoError(t, os.Remove(tmpfile.Name())) // saved in file - require.NoError(t, ioutil.WriteFile(filepath.Join(context.String(cmd.DataDirFlag.Name), acceptTosFilename), []byte(""), 0666)) + require.NoError(t, os.WriteFile(filepath.Join(context.String(cmd.DataDirFlag.Name), acceptTosFilename), []byte(""), 0666)) require.NoError(t, VerifyTosAcceptedOrPrompt(context)) require.NoError(t, os.RemoveAll(context.String(cmd.DataDirFlag.Name))) diff --git a/testing/benchmark/pregen.go b/testing/benchmark/pregen.go index 286cbde82..40f94fdf5 100644 --- a/testing/benchmark/pregen.go +++ b/testing/benchmark/pregen.go @@ -4,7 +4,7 @@ package benchmark import ( "fmt" - "io/ioutil" + "os" "github.com/bazelbuild/rules_go/go/tools/bazel" "github.com/prysmaticlabs/prysm/beacon-chain/state" @@ -45,7 +45,7 @@ func PreGenState1Epoch() (state.BeaconState, error) { if err != nil { return nil, err } - beaconBytes, err := ioutil.ReadFile(path) // #nosec G304 + beaconBytes, err := os.ReadFile(path) // #nosec G304 if err != nil { return nil, err } @@ -62,7 +62,7 @@ func PreGenstateFullEpochs() (state.BeaconState, error) { if err != nil { return nil, err } - beaconBytes, err := ioutil.ReadFile(path) // #nosec G304 + beaconBytes, err := os.ReadFile(path) // #nosec G304 if err != nil { return nil, err } @@ -79,7 +79,7 @@ func PreGenFullBlock() (*ethpb.SignedBeaconBlock, error) { if err != nil { return nil, err } - blockBytes, err := ioutil.ReadFile(path) // #nosec G304 + blockBytes, err := os.ReadFile(path) // #nosec G304 if err != nil { return nil, err } diff --git a/testing/bls/utils/utils.go b/testing/bls/utils/utils.go index c0189bb91..7c7e8aef2 100644 --- a/testing/bls/utils/utils.go +++ b/testing/bls/utils/utils.go @@ -1,7 +1,7 @@ package utils import ( - "io/ioutil" + "os" "path" "strings" "testing" @@ -14,7 +14,7 @@ import ( func RetrieveFiles(name string, t *testing.T) ([]string, [][]byte) { filepath, err := bazel.Runfile(name) require.NoError(t, err) - testFiles, err := ioutil.ReadDir(filepath) + testFiles, err := os.ReadDir(filepath) require.NoError(t, err) var fileNames []string diff --git a/testing/endtoend/components/boot_node.go b/testing/endtoend/components/boot_node.go index 2887023e5..4cbc447b9 100644 --- a/testing/endtoend/components/boot_node.go +++ b/testing/endtoend/components/boot_node.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "os" "os/exec" "strings" @@ -84,7 +84,7 @@ func (node *BootNode) Started() <-chan struct{} { } func enrFromLogFile(name string) (string, error) { - byteContent, err := ioutil.ReadFile(name) // #nosec G304 + byteContent, err := os.ReadFile(name) // #nosec G304 if err != nil { return "", err } diff --git a/testing/endtoend/components/eth1/miner.go b/testing/endtoend/components/eth1/miner.go index c5ee275d2..4f9871d0f 100644 --- a/testing/endtoend/components/eth1/miner.go +++ b/testing/endtoend/components/eth1/miner.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "math/big" "os" "os/exec" @@ -135,7 +134,7 @@ func (m *Miner) Start(ctx context.Context) error { if err != nil { return err } - jsonBytes, err := ioutil.ReadFile(keystorePath) // #nosec G304 -- ReadFile is safe + jsonBytes, err := os.ReadFile(keystorePath) // #nosec G304 -- ReadFile is safe if err != nil { return err } @@ -236,7 +235,7 @@ func (m *Miner) Started() <-chan struct{} { } func enodeFromLogFile(name string) (string, error) { - byteContent, err := ioutil.ReadFile(name) // #nosec G304 + byteContent, err := os.ReadFile(name) // #nosec G304 if err != nil { return "", err } diff --git a/testing/endtoend/components/eth1/transactions.go b/testing/endtoend/components/eth1/transactions.go index da490d173..1ff6c7a9b 100644 --- a/testing/endtoend/components/eth1/transactions.go +++ b/testing/endtoend/components/eth1/transactions.go @@ -4,9 +4,9 @@ import ( "context" "crypto/ecdsa" "fmt" - "io/ioutil" "math/big" mathRand "math/rand" + "os" "time" "github.com/MariusVanDerWijden/FuzzyVM/filler" @@ -49,7 +49,7 @@ func (t *TransactionGenerator) Start(ctx context.Context) error { // deterministically generated. mathRand.Seed(seed) - keystoreBytes, err := ioutil.ReadFile(t.keystore) // #nosec G304 + keystoreBytes, err := os.ReadFile(t.keystore) // #nosec G304 if err != nil { return err } diff --git a/testing/endtoend/components/validator.go b/testing/endtoend/components/validator.go index b0a6c36c2..cbad7a410 100644 --- a/testing/endtoend/components/validator.go +++ b/testing/endtoend/components/validator.go @@ -5,7 +5,6 @@ import ( "context" "encoding/hex" "fmt" - "io/ioutil" "math/big" "os" "os/exec" @@ -223,7 +222,7 @@ func SendAndMineDeposits(keystorePath string, validatorNum, offset int, partial defer client.Close() web3 := ethclient.NewClient(client) - keystoreBytes, err := ioutil.ReadFile(keystorePath) // #nosec G304 + keystoreBytes, err := os.ReadFile(keystorePath) // #nosec G304 if err != nil { return err } diff --git a/testing/endtoend/evaluators/metrics.go b/testing/endtoend/evaluators/metrics.go index 1c34575f5..3646f38bf 100644 --- a/testing/endtoend/evaluators/metrics.go +++ b/testing/endtoend/evaluators/metrics.go @@ -3,7 +3,7 @@ package evaluators import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "regexp" "strconv" @@ -100,7 +100,7 @@ func metricsTest(conns ...*grpc.ClientConn) error { // Continue if the connection fails, regular flake. continue } - dataInBytes, err := ioutil.ReadAll(response.Body) + dataInBytes, err := io.ReadAll(response.Body) if err != nil { return err } diff --git a/testing/endtoend/evaluators/node.go b/testing/endtoend/evaluators/node.go index 4b0b8c1f3..d7b3486dd 100644 --- a/testing/endtoend/evaluators/node.go +++ b/testing/endtoend/evaluators/node.go @@ -6,7 +6,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "time" @@ -61,7 +61,7 @@ func healthzCheck(conns ...*grpc.ClientConn) error { continue } if resp.StatusCode != http.StatusOK { - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } @@ -80,7 +80,7 @@ func healthzCheck(conns ...*grpc.ClientConn) error { continue } if resp.StatusCode != http.StatusOK { - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/testing/endtoend/helpers/helpers.go b/testing/endtoend/helpers/helpers.go index 0f7b4f5bd..18eaa3251 100644 --- a/testing/endtoend/helpers/helpers.go +++ b/testing/endtoend/helpers/helpers.go @@ -7,7 +7,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "os" "path" @@ -70,7 +69,7 @@ func WaitForTextInFile(file *os.File, text string) error { for { select { case <-ctx.Done(): - contents, err := ioutil.ReadAll(file) + contents, err := io.ReadAll(file) if err != nil { return err } @@ -108,7 +107,7 @@ func FindFollowingTextInFile(file *os.File, text string) (string, error) { for { select { case <-ctx.Done(): - contents, err := ioutil.ReadAll(file) + contents, err := io.ReadAll(file) if err != nil { return "", err } @@ -146,13 +145,13 @@ func FindFollowingTextInFile(file *os.File, text string) (string, error) { // GraffitiYamlFile outputs graffiti YAML file into a testing directory. func GraffitiYamlFile(testDir string) (string, error) { b := []byte(`default: "Rice" -random: +random: - "Sushi" - "Ramen" - "Takoyaki" `) f := filepath.Join(testDir, "graffiti.yaml") - if err := ioutil.WriteFile(f, b, os.ModePerm); err != nil { + if err := os.WriteFile(f, b, os.ModePerm); err != nil { return "", err } return f, nil @@ -222,7 +221,7 @@ func writeURLRespAtPath(url, fp string) error { } }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/testing/spectest/shared/altair/epoch_processing/helpers.go b/testing/spectest/shared/altair/epoch_processing/helpers.go index c1ad9eb74..97a792fd9 100644 --- a/testing/spectest/shared/altair/epoch_processing/helpers.go +++ b/testing/spectest/shared/altair/epoch_processing/helpers.go @@ -1,7 +1,7 @@ package epoch_processing import ( - "io/ioutil" + "os" "path" "strings" "testing" @@ -50,7 +50,7 @@ func RunEpochOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/altair/operations/block_header.go b/testing/spectest/shared/altair/operations/block_header.go index bc33aa276..e701374ca 100644 --- a/testing/spectest/shared/altair/operations/block_header.go +++ b/testing/spectest/shared/altair/operations/block_header.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -56,7 +56,7 @@ func RunBlockHeaderTest(t *testing.T, config string) { if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/altair/operations/helpers.go b/testing/spectest/shared/altair/operations/helpers.go index db36200d9..8e6d83913 100644 --- a/testing/spectest/shared/altair/operations/helpers.go +++ b/testing/spectest/shared/altair/operations/helpers.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -60,7 +60,7 @@ func RunBlockOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/altair/sanity/block_processing.go b/testing/spectest/shared/altair/sanity/block_processing.go index c45021dbb..3bfed9ff8 100644 --- a/testing/spectest/shared/altair/sanity/block_processing.go +++ b/testing/spectest/shared/altair/sanity/block_processing.go @@ -3,7 +3,7 @@ package sanity import ( "context" "fmt" - "io/ioutil" + "os" "path" "strings" "testing" @@ -85,7 +85,7 @@ func RunBlockProcessingTest(t *testing.T, config, folderPath string) { t.Errorf("Unexpected error: %v", transitionError) } - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/bellatrix/epoch_processing/helpers.go b/testing/spectest/shared/bellatrix/epoch_processing/helpers.go index 1b0fe4379..55e254205 100644 --- a/testing/spectest/shared/bellatrix/epoch_processing/helpers.go +++ b/testing/spectest/shared/bellatrix/epoch_processing/helpers.go @@ -1,7 +1,7 @@ package epoch_processing import ( - "io/ioutil" + "os" "path" "strings" "testing" @@ -50,7 +50,7 @@ func RunEpochOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/bellatrix/operations/block_header.go b/testing/spectest/shared/bellatrix/operations/block_header.go index 92dea9bb2..32f6da663 100644 --- a/testing/spectest/shared/bellatrix/operations/block_header.go +++ b/testing/spectest/shared/bellatrix/operations/block_header.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -56,7 +56,7 @@ func RunBlockHeaderTest(t *testing.T, config string) { if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/bellatrix/operations/helpers.go b/testing/spectest/shared/bellatrix/operations/helpers.go index 386f3426b..59efd6298 100644 --- a/testing/spectest/shared/bellatrix/operations/helpers.go +++ b/testing/spectest/shared/bellatrix/operations/helpers.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -60,7 +60,7 @@ func RunBlockOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/bellatrix/sanity/block_processing.go b/testing/spectest/shared/bellatrix/sanity/block_processing.go index c89254199..c2ff5b1e5 100644 --- a/testing/spectest/shared/bellatrix/sanity/block_processing.go +++ b/testing/spectest/shared/bellatrix/sanity/block_processing.go @@ -3,7 +3,7 @@ package sanity import ( "context" "fmt" - "io/ioutil" + "os" "path" "strings" "testing" @@ -85,7 +85,7 @@ func RunBlockProcessingTest(t *testing.T, config, folderPath string) { t.Errorf("Unexpected error: %v", transitionError) } - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/phase0/epoch_processing/helpers.go b/testing/spectest/shared/phase0/epoch_processing/helpers.go index 408dd48c1..0d9920e55 100644 --- a/testing/spectest/shared/phase0/epoch_processing/helpers.go +++ b/testing/spectest/shared/phase0/epoch_processing/helpers.go @@ -1,7 +1,7 @@ package epoch_processing import ( - "io/ioutil" + "os" "path" "strings" "testing" @@ -49,7 +49,7 @@ func RunEpochOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/phase0/operations/block_header.go b/testing/spectest/shared/phase0/operations/block_header.go index d413dce4d..87963b17d 100644 --- a/testing/spectest/shared/phase0/operations/block_header.go +++ b/testing/spectest/shared/phase0/operations/block_header.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -57,7 +57,7 @@ func RunBlockHeaderTest(t *testing.T, config string) { if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/phase0/operations/helpers.go b/testing/spectest/shared/phase0/operations/helpers.go index 43ca2dbe8..7dcdbf218 100644 --- a/testing/spectest/shared/phase0/operations/helpers.go +++ b/testing/spectest/shared/phase0/operations/helpers.go @@ -2,7 +2,7 @@ package operations import ( "context" - "io/ioutil" + "os" "path" "strings" "testing" @@ -60,7 +60,7 @@ func RunBlockOperationTest( if postSSZExists { require.NoError(t, err) - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/shared/phase0/sanity/block_processing.go b/testing/spectest/shared/phase0/sanity/block_processing.go index b401ef338..64a622077 100644 --- a/testing/spectest/shared/phase0/sanity/block_processing.go +++ b/testing/spectest/shared/phase0/sanity/block_processing.go @@ -3,7 +3,7 @@ package sanity import ( "context" "fmt" - "io/ioutil" + "os" "path" "strings" "testing" @@ -85,7 +85,7 @@ func RunBlockProcessingTest(t *testing.T, config, folderPath string) { t.Errorf("Unexpected error: %v", transitionError) } - postBeaconStateFile, err := ioutil.ReadFile(postSSZFilepath) // #nosec G304 + postBeaconStateFile, err := os.ReadFile(postSSZFilepath) // #nosec G304 require.NoError(t, err) postBeaconStateSSZ, err := snappy.Decode(nil /* dst */, postBeaconStateFile) require.NoError(t, err, "Failed to decompress") diff --git a/testing/spectest/utils/utils.go b/testing/spectest/utils/utils.go index 9b4b824f9..d8fb06cc4 100644 --- a/testing/spectest/utils/utils.go +++ b/testing/spectest/utils/utils.go @@ -1,7 +1,6 @@ package utils import ( - "io/ioutil" "os" "path" "testing" @@ -31,11 +30,11 @@ func UnmarshalYaml(y []byte, dest interface{}) error { // TestFolders sets the proper config and returns the result of ReadDir // on the passed in eth2-spec-tests directory along with its path. -func TestFolders(t testing.TB, config, forkOrPhase, folderPath string) ([]os.FileInfo, string) { +func TestFolders(t testing.TB, config, forkOrPhase, folderPath string) ([]os.DirEntry, string) { testsFolderPath := path.Join("tests", config, forkOrPhase, folderPath) filepath, err := bazel.Runfile(testsFolderPath) require.NoError(t, err) - testFolders, err := ioutil.ReadDir(filepath) + testFolders, err := os.ReadDir(filepath) require.NoError(t, err) if len(testFolders) == 0 { diff --git a/testing/util/bazel.go b/testing/util/bazel.go index 81e8f58b1..365f22f8a 100644 --- a/testing/util/bazel.go +++ b/testing/util/bazel.go @@ -1,7 +1,6 @@ package util import ( - "io/ioutil" "os" "path" @@ -24,7 +23,7 @@ func BazelFileBytes(filePaths ...string) ([]byte, error) { if err != nil { return nil, err } - fileBytes, err := ioutil.ReadFile(filepath) // #nosec G304 + fileBytes, err := os.ReadFile(filepath) // #nosec G304 if err != nil { return nil, err } @@ -79,10 +78,10 @@ func BazelListDirectories(filepath string) ([]string, error) { return ret, nil } -func bazelReadDir(filepath string) ([]os.FileInfo, error) { +func bazelReadDir(filepath string) ([]os.DirEntry, error) { p, err := bazel.Runfile(filepath) if err != nil { return nil, err } - return ioutil.ReadDir(p) + return os.ReadDir(p) } diff --git a/time/slots/slotutil_test.go b/time/slots/slotutil_test.go index 754635798..78729c6d7 100644 --- a/time/slots/slotutil_test.go +++ b/time/slots/slotutil_test.go @@ -1,7 +1,7 @@ package slots import ( - "io/ioutil" + "io" "testing" "github.com/sirupsen/logrus" @@ -9,7 +9,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/tools/analyzers/properpermissions/testdata/custom_imports.go b/tools/analyzers/properpermissions/testdata/custom_imports.go index 87c2ced0b..7a9ee73f4 100644 --- a/tools/analyzers/properpermissions/testdata/custom_imports.go +++ b/tools/analyzers/properpermissions/testdata/custom_imports.go @@ -3,7 +3,6 @@ package testdata import ( "crypto/rand" "fmt" - ioAlias "io/ioutil" "math/big" osAlias "os" "path/filepath" @@ -15,5 +14,5 @@ func UseAliasedPackages() { p := filepath.Join(tempDir(), fmt.Sprintf("/%d", randPath)) _ = osAlias.MkdirAll(p, osAlias.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" someFile := filepath.Join(p, "some.txt") - _ = ioAlias.WriteFile(someFile, []byte("hello"), osAlias.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" + _ = osAlias.WriteFile(someFile, []byte("hello"), osAlias.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" } diff --git a/tools/analyzers/properpermissions/testdata/regular_imports.go b/tools/analyzers/properpermissions/testdata/regular_imports.go index 795a73a4c..43a3592d7 100644 --- a/tools/analyzers/properpermissions/testdata/regular_imports.go +++ b/tools/analyzers/properpermissions/testdata/regular_imports.go @@ -3,7 +3,6 @@ package testdata import ( "crypto/rand" "fmt" - "io/ioutil" "math/big" "os" "path/filepath" @@ -23,5 +22,5 @@ func UseOsMkdirAllAndWriteFile() { p := filepath.Join(tempDir(), fmt.Sprintf("/%d", randPath)) _ = os.MkdirAll(p, os.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" someFile := filepath.Join(p, "some.txt") - _ = ioutil.WriteFile(someFile, []byte("hello"), os.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" + _ = os.WriteFile(someFile, []byte("hello"), os.ModePerm) // want "os and ioutil dir and file writing functions are not permissions-safe, use shared/file" } diff --git a/tools/beacon-fuzz/main.go b/tools/beacon-fuzz/main.go index 88b18c038..189a81048 100644 --- a/tools/beacon-fuzz/main.go +++ b/tools/beacon-fuzz/main.go @@ -4,7 +4,6 @@ import ( "bytes" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -48,7 +47,7 @@ func main() { if err != nil { panic(fmt.Sprintf("%s does not end in an integer for the filename.", p)) } - b, err := ioutil.ReadFile(p) // #nosec G304 + b, err := os.ReadFile(p) // #nosec G304 if err != nil { panic(err) } diff --git a/tools/benchmark-files-gen/main.go b/tools/benchmark-files-gen/main.go index b314b8e44..920f1cf6b 100644 --- a/tools/benchmark-files-gen/main.go +++ b/tools/benchmark-files-gen/main.go @@ -3,7 +3,6 @@ package main import ( "context" "flag" - "io/ioutil" "log" "os" "path" @@ -224,7 +223,7 @@ func generate2FullEpochState() error { } func genesisBeaconState() (state.BeaconState, error) { - beaconBytes, err := ioutil.ReadFile(path.Join(*outputDir, benchmark.GenesisFileName)) + beaconBytes, err := os.ReadFile(path.Join(*outputDir, benchmark.GenesisFileName)) if err != nil { return nil, errors.Wrap(err, "cannot read genesis state file") } diff --git a/tools/bootnode/bootnode_test.go b/tools/bootnode/bootnode_test.go index 949394331..aa0fa65c4 100644 --- a/tools/bootnode/bootnode_test.go +++ b/tools/bootnode/bootnode_test.go @@ -4,7 +4,7 @@ import ( "crypto/ecdsa" "crypto/rand" "fmt" - "io/ioutil" + "io" "testing" "time" @@ -20,7 +20,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/tools/genesis-state-gen/main.go b/tools/genesis-state-gen/main.go index 5a4e6644c..612f81404 100644 --- a/tools/genesis-state-gen/main.go +++ b/tools/genesis-state-gen/main.go @@ -6,7 +6,6 @@ import ( "encoding/json" "flag" "io" - "io/ioutil" "log" "os" "strings" @@ -131,7 +130,7 @@ func main() { } func genesisStateFromJSONValidators(r io.Reader, genesisTime uint64) (*ethpb.BeaconState, error) { - enc, err := ioutil.ReadAll(r) + enc, err := io.ReadAll(r) if err != nil { return nil, err } diff --git a/tools/http-request-sink/main.go b/tools/http-request-sink/main.go index ca5c779da..7854e08bf 100644 --- a/tools/http-request-sink/main.go +++ b/tools/http-request-sink/main.go @@ -7,7 +7,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "log" "net/http" "os" @@ -64,13 +64,13 @@ func captureRequest(f *os.File, m map[string]interface{}) error { } func parseRequest(req *http.Request, unmarshalStruct interface{}) error { - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { return err } if err = req.Body.Close(); err != nil { return err } - req.Body = ioutil.NopCloser(bytes.NewBuffer(body)) + req.Body = io.NopCloser(bytes.NewBuffer(body)) return json.Unmarshal(body, unmarshalStruct) } diff --git a/tools/http-request-sink/main_test.go b/tools/http-request-sink/main_test.go index f0562523f..5ee840d59 100644 --- a/tools/http-request-sink/main_test.go +++ b/tools/http-request-sink/main_test.go @@ -3,7 +3,7 @@ package main import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -52,7 +52,7 @@ func Test_parseAndCaptureRequest(t *testing.T) { f, err = os.Open(tmpFile) require.NoError(t, err) - fileContents, err := ioutil.ReadAll(f) + fileContents, err := io.ReadAll(f) require.NoError(t, err) receivedContent := map[string]interface{}{} diff --git a/tools/interop/convert-keys/main.go b/tools/interop/convert-keys/main.go index 7cada417b..79dd9b0bb 100644 --- a/tools/interop/convert-keys/main.go +++ b/tools/interop/convert-keys/main.go @@ -7,7 +7,6 @@ package main import ( "encoding/hex" "fmt" - "io/ioutil" "log" "os" @@ -31,7 +30,7 @@ func main() { } inFile := os.Args[1] - in, err := ioutil.ReadFile(inFile) // #nosec G304 + in, err := os.ReadFile(inFile) // #nosec G304 if err != nil { log.Fatalf("Failed to read file %s: %v", inFile, err) } diff --git a/tools/keystores/main.go b/tools/keystores/main.go index 20a178e2e..4387352cf 100644 --- a/tools/keystores/main.go +++ b/tools/keystores/main.go @@ -8,7 +8,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -110,7 +109,7 @@ func decrypt(cliCtx *cli.Context) error { return errors.Wrapf(err, "could not check if path exists: %s", fullPath) } if isDir { - files, err := ioutil.ReadDir(fullPath) + files, err := os.ReadDir(fullPath) if err != nil { return errors.Wrapf(err, "could not read directory: %s", fullPath) } @@ -224,7 +223,7 @@ func encrypt(cliCtx *cli.Context) error { // Reads the keystore file at the provided path and attempts // to decrypt it with the specified passwords. func readAndDecryptKeystore(fullPath, password string) error { - file, err := ioutil.ReadFile(fullPath) // #nosec G304 + file, err := os.ReadFile(fullPath) // #nosec G304 if err != nil { return errors.Wrapf(err, "could not read file at path: %s", fullPath) } diff --git a/tools/keystores/main_test.go b/tools/keystores/main_test.go index 0c71ded4c..b315725d8 100644 --- a/tools/keystores/main_test.go +++ b/tools/keystores/main_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -77,7 +77,7 @@ func TestDecrypt(t *testing.T) { encodedKeystore, err := json.MarshalIndent(keystore, "", "\t") require.NoError(t, err) keystoreFilePath := filepath.Join(keystoresDir, "keystore.json") - require.NoError(t, ioutil.WriteFile( + require.NoError(t, os.WriteFile( keystoreFilePath, encodedKeystore, params.BeaconIoConfig().ReadWritePermissions), ) @@ -95,7 +95,7 @@ func TestDecrypt(t *testing.T) { require.NoError(t, decrypt(cliCtx)) require.NoError(t, w.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) // We capture output from stdout. @@ -129,7 +129,7 @@ func TestEncrypt(t *testing.T) { require.NoError(t, encrypt(cliCtx)) require.NoError(t, w.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) // We capture output from stdout. diff --git a/tools/pcli/main.go b/tools/pcli/main.go index 8270119fd..dca1c3773 100644 --- a/tools/pcli/main.go +++ b/tools/pcli/main.go @@ -4,7 +4,6 @@ import ( "bufio" "context" "fmt" - "io/ioutil" "os" "regexp" "strings" @@ -212,7 +211,7 @@ func main() { // dataFetcher fetches and unmarshals data from file to provided data structure. func dataFetcher(fPath string, data fssz.Unmarshaler) error { - rawFile, err := ioutil.ReadFile(fPath) // #nosec G304 + rawFile, err := os.ReadFile(fPath) // #nosec G304 if err != nil { return err } diff --git a/tools/specs-checker/download.go b/tools/specs-checker/download.go index f0099ba45..03972ebcb 100644 --- a/tools/specs-checker/download.go +++ b/tools/specs-checker/download.go @@ -3,7 +3,7 @@ package main import ( _ "embed" "fmt" - "io/ioutil" + "io" "net/http" "os" "path" @@ -62,7 +62,7 @@ func getAndSaveFile(specDocUrl, outFilePath string) error { }() // Transform and save spec docs. - specDoc, err := ioutil.ReadAll(resp.Body) + specDoc, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/validator/accounts/accounts_backup_test.go b/validator/accounts/accounts_backup_test.go index d5b84f6fd..209bcbced 100644 --- a/validator/accounts/accounts_backup_test.go +++ b/validator/accounts/accounts_backup_test.go @@ -4,7 +4,7 @@ import ( "archive/zip" "encoding/hex" "encoding/json" - "io/ioutil" + "io" "os" "path/filepath" "sort" @@ -27,7 +27,7 @@ func TestBackupAccounts_Noninteractive_Derived(t *testing.T) { walletDir, _, passwordFilePath := setupWalletAndPasswordsDir(t) // Specify the password locally to this file for convenience. password := "Pa$sW0rD0__Fo0xPr" - require.NoError(t, ioutil.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) + require.NoError(t, os.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) // Write a directory where we will backup accounts to. backupDir := filepath.Join(t.TempDir(), "backupDir") @@ -35,7 +35,7 @@ func TestBackupAccounts_Noninteractive_Derived(t *testing.T) { // Write a password for the accounts we wish to backup to a file. backupPasswordFile := filepath.Join(backupDir, "backuppass.txt") - err := ioutil.WriteFile( + err := os.WriteFile( backupPasswordFile, []byte("Passw0rdz4938%%"), params.BeaconIoConfig().ReadWritePermissions, @@ -116,7 +116,7 @@ func TestBackupAccounts_Noninteractive_Derived(t *testing.T) { for i, unzipped := range r.File { ff, err := unzipped.Open() require.NoError(t, err) - encodedBytes, err := ioutil.ReadAll(ff) + encodedBytes, err := io.ReadAll(ff) require.NoError(t, err) keystoreFile := &keymanager.Keystore{} require.NoError(t, json.Unmarshal(encodedBytes, keystoreFile)) @@ -148,7 +148,7 @@ func TestBackupAccounts_Noninteractive_Imported(t *testing.T) { // Write a password for the accounts we wish to backup to a file. backupPasswordFile := filepath.Join(backupDir, "backuppass.txt") - err := ioutil.WriteFile( + err := os.WriteFile( backupPasswordFile, []byte("Passw0rdz4938%%"), params.BeaconIoConfig().ReadWritePermissions, @@ -206,7 +206,7 @@ func TestBackupAccounts_Noninteractive_Imported(t *testing.T) { for i, unzipped := range r.File { ff, err := unzipped.Open() require.NoError(t, err) - encodedBytes, err := ioutil.ReadAll(ff) + encodedBytes, err := io.ReadAll(ff) require.NoError(t, err) keystoreFile := &keymanager.Keystore{} require.NoError(t, json.Unmarshal(encodedBytes, keystoreFile)) diff --git a/validator/accounts/accounts_import.go b/validator/accounts/accounts_import.go index 81dfee754..83488acab 100644 --- a/validator/accounts/accounts_import.go +++ b/validator/accounts/accounts_import.go @@ -5,7 +5,7 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "regexp" "sort" @@ -162,7 +162,7 @@ func ImportAccountsCli(cliCtx *cli.Context) error { } keystoresImported := make([]*keymanager.Keystore, 0) if isDir { - files, err := ioutil.ReadDir(keysDir) + files, err := os.ReadDir(keysDir) if err != nil { return errors.Wrap(err, "could not read dir") } @@ -199,7 +199,7 @@ func ImportAccountsCli(cliCtx *cli.Context) error { var accountsPassword string if cliCtx.IsSet(flags.AccountPasswordFileFlag.Name) { passwordFilePath := cliCtx.String(flags.AccountPasswordFileFlag.Name) - data, err := ioutil.ReadFile(passwordFilePath) // #nosec G304 + data, err := os.ReadFile(passwordFilePath) // #nosec G304 if err != nil { return err } @@ -274,7 +274,7 @@ func importPrivateKeyAsAccount(cliCtx *cli.Context, wallet *wallet.Wallet, impor if !file.FileExists(fullPath) { return fmt.Errorf("file %s does not exist", fullPath) } - privKeyHex, err := ioutil.ReadFile(fullPath) // #nosec G304 + privKeyHex, err := os.ReadFile(fullPath) // #nosec G304 if err != nil { return errors.Wrapf(err, "could not read private key file at path %s", fullPath) } @@ -322,7 +322,7 @@ func importPrivateKeyAsAccount(cliCtx *cli.Context, wallet *wallet.Wallet, impor } func readKeystoreFile(_ context.Context, keystoreFilePath string) (*keymanager.Keystore, error) { - keystoreBytes, err := ioutil.ReadFile(keystoreFilePath) // #nosec G304 + keystoreBytes, err := os.ReadFile(keystoreFilePath) // #nosec G304 if err != nil { return nil, errors.Wrap(err, "could not read keystore file") } diff --git a/validator/accounts/accounts_import_test.go b/validator/accounts/accounts_import_test.go index 370465bea..2630fd8a0 100644 --- a/validator/accounts/accounts_import_test.go +++ b/validator/accounts/accounts_import_test.go @@ -5,7 +5,6 @@ import ( "crypto/rand" "encoding/json" "fmt" - "io/ioutil" "math/big" "os" "path/filepath" @@ -111,10 +110,10 @@ func TestImport_DuplicateKeys(t *testing.T) { // Create a key and then copy it to create a duplicate _, keystorePath := createKeystore(t, keysDir) time.Sleep(time.Second) - input, err := ioutil.ReadFile(keystorePath) + input, err := os.ReadFile(keystorePath) require.NoError(t, err) keystorePath2 := filepath.Join(keysDir, "copyOfKeystore.json") - err = ioutil.WriteFile(keystorePath2, input, os.ModePerm) + err = os.WriteFile(keystorePath2, input, os.ModePerm) require.NoError(t, err) require.NoError(t, ImportAccountsCli(cliCtx)) @@ -352,7 +351,7 @@ func Test_importPrivateKeyAsAccount(t *testing.T) { privKeyHex := fmt.Sprintf("%x", privKey.Marshal()) require.NoError( t, - ioutil.WriteFile(privKeyFileName, []byte(privKeyHex), params.BeaconIoConfig().ReadWritePermissions), + os.WriteFile(privKeyFileName, []byte(privKeyHex), params.BeaconIoConfig().ReadWritePermissions), ) // We instantiate a new wallet from a cli context. @@ -417,7 +416,7 @@ func createKeystore(t *testing.T, path string) (*keymanager.Keystore, string) { // Write the encoded keystore to disk with the timestamp appended createdAt := prysmTime.Now().Unix() fullPath := filepath.Join(path, fmt.Sprintf(local.KeystoreFileNameFormat, createdAt)) - require.NoError(t, ioutil.WriteFile(fullPath, encoded, os.ModePerm)) + require.NoError(t, os.WriteFile(fullPath, encoded, os.ModePerm)) return keystoreFile, fullPath } @@ -443,6 +442,6 @@ func createRandomNameKeystore(t *testing.T, path string) (*keymanager.Keystore, random, err := rand.Int(rand.Reader, big.NewInt(1000000)) require.NoError(t, err) fullPath := filepath.Join(path, fmt.Sprintf("test-%d-keystore", random.Int64())) - require.NoError(t, ioutil.WriteFile(fullPath, encoded, os.ModePerm)) + require.NoError(t, os.WriteFile(fullPath, encoded, os.ModePerm)) return keystoreFile, fullPath } diff --git a/validator/accounts/accounts_list_test.go b/validator/accounts/accounts_list_test.go index aec068977..84d920c61 100644 --- a/validator/accounts/accounts_list_test.go +++ b/validator/accounts/accounts_list_test.go @@ -3,7 +3,7 @@ package accounts import ( "context" "fmt" - "io/ioutil" + "io" "math" "os" "strconv" @@ -133,7 +133,7 @@ func TestListAccounts_LocalKeymanager(t *testing.T) { ) require.NoError(t, writer.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) os.Stdout = rescueStdout @@ -277,7 +277,7 @@ func TestListAccounts_DerivedKeymanager(t *testing.T) { keymanager.ListKeymanagerAccountConfig{ShowPrivateKeys: true})) require.NoError(t, writer.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) os.Stdout = rescueStdout @@ -425,7 +425,7 @@ func TestListAccounts_RemoteKeymanager(t *testing.T) { })) require.NoError(t, writer.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) os.Stdout = rescueStdout @@ -542,7 +542,7 @@ func TestListAccounts_ListValidatorIndices(t *testing.T) { ) require.NoError(t, writer.Close()) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) os.Stdout = rescueStdout diff --git a/validator/accounts/wallet/wallet.go b/validator/accounts/wallet/wallet.go index 7c870ec51..4e056c3a8 100644 --- a/validator/accounts/wallet/wallet.go +++ b/validator/accounts/wallet/wallet.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -367,7 +366,7 @@ func (w *Wallet) ReadFileAtPath(_ context.Context, filePath, fileName string) ([ if len(matches) == 0 { return []byte{}, fmt.Errorf("no files found in path: %s", fullPath) } - rawData, err := ioutil.ReadFile(matches[0]) + rawData, err := os.ReadFile(matches[0]) if err != nil { return nil, errors.Wrapf(err, "could not read path: %s", filePath) } diff --git a/validator/accounts/wallet/wallet_test.go b/validator/accounts/wallet/wallet_test.go index 40c27ba13..f0a0e093d 100644 --- a/validator/accounts/wallet/wallet_test.go +++ b/validator/accounts/wallet/wallet_test.go @@ -2,7 +2,7 @@ package wallet_test import ( "context" - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -19,7 +19,7 @@ import ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } func Test_Exists_RandomFiles(t *testing.T) { diff --git a/validator/accounts/wallet_create_test.go b/validator/accounts/wallet_create_test.go index 8f49ea201..74ee1944e 100644 --- a/validator/accounts/wallet_create_test.go +++ b/validator/accounts/wallet_create_test.go @@ -3,7 +3,7 @@ package accounts import ( "context" "flag" - "io/ioutil" + "io" "os" "path/filepath" "strconv" @@ -33,7 +33,7 @@ const ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } type testWalletConfig struct { @@ -105,7 +105,7 @@ func setupWalletAndPasswordsDir(t testing.TB) (string, string, string) { passwordFileDir := filepath.Join(t.TempDir(), "passwordFile") require.NoError(t, os.MkdirAll(passwordFileDir, params.BeaconIoConfig().ReadWriteExecutePermissions)) passwordFilePath := filepath.Join(passwordFileDir, passwordFileName) - require.NoError(t, ioutil.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) + require.NoError(t, os.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) return walletDir, passwordsDir, passwordFilePath } diff --git a/validator/accounts/wallet_recover.go b/validator/accounts/wallet_recover.go index e2dce6763..611eb6c1a 100644 --- a/validator/accounts/wallet_recover.go +++ b/validator/accounts/wallet_recover.go @@ -3,7 +3,6 @@ package accounts import ( "context" "fmt" - "io/ioutil" "os" "sort" "strconv" @@ -157,7 +156,7 @@ func RecoverWallet(ctx context.Context, cfg *RecoverWalletConfig) (*wallet.Walle func inputMnemonic(cliCtx *cli.Context) (mnemonicPhrase string, err error) { if cliCtx.IsSet(flags.MnemonicFileFlag.Name) { mnemonicFilePath := cliCtx.String(flags.MnemonicFileFlag.Name) - data, err := ioutil.ReadFile(mnemonicFilePath) // #nosec G304 -- ReadFile is safe + data, err := os.ReadFile(mnemonicFilePath) // #nosec G304 -- ReadFile is safe if err != nil { return "", err } diff --git a/validator/accounts/wallet_recover_test.go b/validator/accounts/wallet_recover_test.go index edffab8d3..beb409249 100644 --- a/validator/accounts/wallet_recover_test.go +++ b/validator/accounts/wallet_recover_test.go @@ -3,7 +3,6 @@ package accounts import ( "context" "flag" - "io/ioutil" "os" "path/filepath" "strconv" @@ -31,9 +30,9 @@ func setupRecoverCfg(t *testing.T) *recoverCfgStruct { testDir := t.TempDir() walletDir := filepath.Join(testDir, walletDirName) passwordFilePath := filepath.Join(testDir, passwordFileName) - require.NoError(t, ioutil.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) + require.NoError(t, os.WriteFile(passwordFilePath, []byte(password), os.ModePerm)) mnemonicFilePath := filepath.Join(testDir, mnemonicFileName) - require.NoError(t, ioutil.WriteFile(mnemonicFilePath, []byte(mnemonic), os.ModePerm)) + require.NoError(t, os.WriteFile(mnemonicFilePath, []byte(mnemonic), os.ModePerm)) return &recoverCfgStruct{ walletDir: walletDir, diff --git a/validator/client/validator_test.go b/validator/client/validator_test.go index a23c735f0..6d5738af8 100644 --- a/validator/client/validator_test.go +++ b/validator/client/validator_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "math" "sync" "testing" @@ -42,7 +42,7 @@ import ( func init() { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) } var _ iface.Validator = (*validator)(nil) diff --git a/validator/db/kv/backup_test.go b/validator/db/kv/backup_test.go index 485836028..8f7129a95 100644 --- a/validator/db/kv/backup_test.go +++ b/validator/db/kv/backup_test.go @@ -2,7 +2,6 @@ package kv import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -20,7 +19,7 @@ func TestStore_Backup(t *testing.T) { require.NoError(t, db.Backup(ctx, "", true)) backupsPath := filepath.Join(db.databasePath, backupsDirectoryName) - files, err := ioutil.ReadDir(backupsPath) + files, err := os.ReadDir(backupsPath) require.NoError(t, err) require.NotEqual(t, 0, len(files), "No backups created") require.NoError(t, db.Close(), "Failed to close database") @@ -69,7 +68,7 @@ func TestStore_NestedBackup(t *testing.T) { require.NoError(t, db.Backup(ctx, "", true)) backupsPath := filepath.Join(db.databasePath, backupsDirectoryName) - files, err := ioutil.ReadDir(backupsPath) + files, err := os.ReadDir(backupsPath) require.NoError(t, err) require.NotEqual(t, 0, len(files), "No backups created") require.NoError(t, db.Close(), "Failed to close database") diff --git a/validator/db/kv/kv_test.go b/validator/db/kv/kv_test.go index b433ffa34..73ec17a3a 100644 --- a/validator/db/kv/kv_test.go +++ b/validator/db/kv/kv_test.go @@ -2,7 +2,7 @@ package kv import ( "context" - "io/ioutil" + "io" "testing" fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams" @@ -12,7 +12,7 @@ import ( func TestMain(m *testing.M) { logrus.SetLevel(logrus.DebugLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) m.Run() } diff --git a/validator/db/restore_test.go b/validator/db/restore_test.go index db9fe8e75..2ac08373b 100644 --- a/validator/db/restore_test.go +++ b/validator/db/restore_test.go @@ -3,7 +3,6 @@ package db import ( "context" "flag" - "io/ioutil" "os" "path" "testing" @@ -47,7 +46,7 @@ func TestRestore(t *testing.T) { assert.NoError(t, Restore(cliCtx)) - files, err := ioutil.ReadDir(restoreDir) + files, err := os.ReadDir(restoreDir) require.NoError(t, err) assert.Equal(t, 1, len(files)) assert.Equal(t, kv.ProtectionDbFileName, files[0].Name()) diff --git a/validator/graffiti/parse_graffiti.go b/validator/graffiti/parse_graffiti.go index 7b277f740..7fda39f4b 100644 --- a/validator/graffiti/parse_graffiti.go +++ b/validator/graffiti/parse_graffiti.go @@ -2,7 +2,7 @@ package graffiti import ( "encoding/hex" - "io/ioutil" + "os" "strings" types "github.com/prysmaticlabs/eth2-types" @@ -26,7 +26,7 @@ type Graffiti struct { // ParseGraffitiFile parses the graffiti file and returns the graffiti struct. func ParseGraffitiFile(f string) (*Graffiti, error) { - yamlFile, err := ioutil.ReadFile(f) // #nosec G304 + yamlFile, err := os.ReadFile(f) // #nosec G304 if err != nil { return nil, err } diff --git a/validator/graffiti/parse_graffiti_test.go b/validator/graffiti/parse_graffiti_test.go index 9f0482a1d..4c659a158 100644 --- a/validator/graffiti/parse_graffiti_test.go +++ b/validator/graffiti/parse_graffiti_test.go @@ -1,7 +1,6 @@ package graffiti import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -19,7 +18,7 @@ func TestParseGraffitiFile_Default(t *testing.T) { err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, input, os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, input, os.ModePerm)) got, err := ParseGraffitiFile(someFileName) require.NoError(t, err) @@ -41,7 +40,7 @@ func TestParseGraffitiFile_Random(t *testing.T) { err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, input, os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, input, os.ModePerm)) got, err := ParseGraffitiFile(someFileName) require.NoError(t, err) @@ -67,7 +66,7 @@ func TestParseGraffitiFile_Ordered(t *testing.T) { err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, input, os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, input, os.ModePerm)) got, err := ParseGraffitiFile(someFileName) require.NoError(t, err) @@ -94,7 +93,7 @@ specific: err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, input, os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, input, os.ModePerm)) got, err := ParseGraffitiFile(someFileName) require.NoError(t, err) @@ -132,7 +131,7 @@ specific: err := os.MkdirAll(dirName, os.ModePerm) require.NoError(t, err) someFileName := filepath.Join(dirName, "somefile.txt") - require.NoError(t, ioutil.WriteFile(someFileName, input, os.ModePerm)) + require.NoError(t, os.WriteFile(someFileName, input, os.ModePerm)) got, err := ParseGraffitiFile(someFileName) require.NoError(t, err) diff --git a/validator/keymanager/local/refresh.go b/validator/keymanager/local/refresh.go index 7111cd8e3..b1790d4c9 100644 --- a/validator/keymanager/local/refresh.go +++ b/validator/keymanager/local/refresh.go @@ -3,7 +3,7 @@ package local import ( "context" "encoding/json" - "io/ioutil" + "os" "path/filepath" "github.com/fsnotify/fsnotify" @@ -56,7 +56,7 @@ func (km *Keymanager) listenForAccountChanges(ctx context.Context) { log.Errorf("Type %T is not a valid file system event", event) return } - fileBytes, err := ioutil.ReadFile(ev.Name) + fileBytes, err := os.ReadFile(ev.Name) if err != nil { log.WithError(err).Errorf("Could not read file at path: %s", ev.Name) return diff --git a/validator/keymanager/remote-web3signer/internal/client.go b/validator/keymanager/remote-web3signer/internal/client.go index c79a635a4..4d592b523 100644 --- a/validator/keymanager/remote-web3signer/internal/client.go +++ b/validator/keymanager/remote-web3signer/internal/client.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httputil" "net/url" @@ -181,7 +180,7 @@ func (client *ApiClient) doRequest(ctx context.Context, httpMethod, fullPath str func unmarshalResponse(responseBody io.ReadCloser, unmarshalledResponseObject interface{}) error { defer closeBody(responseBody) if err := json.NewDecoder(responseBody).Decode(&unmarshalledResponseObject); err != nil { - body, err := ioutil.ReadAll(responseBody) + body, err := io.ReadAll(responseBody) if err != nil { return errors.Wrap(err, "failed to read response body") } @@ -192,7 +191,7 @@ func unmarshalResponse(responseBody io.ReadCloser, unmarshalledResponseObject in func unmarshalSignatureResponse(responseBody io.ReadCloser) (bls.Signature, error) { defer closeBody(responseBody) - body, err := ioutil.ReadAll(responseBody) + body, err := io.ReadAll(responseBody) if err != nil { return nil, err } diff --git a/validator/keymanager/remote-web3signer/internal/client_test.go b/validator/keymanager/remote-web3signer/internal/client_test.go index 47cff6323..4177b1526 100644 --- a/validator/keymanager/remote-web3signer/internal/client_test.go +++ b/validator/keymanager/remote-web3signer/internal/client_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "testing" @@ -33,7 +33,7 @@ func TestNewApiClient(t *testing.T) { func TestClient_Sign_HappyPath(t *testing.T) { jsonSig := `0xb3baa751d0a9132cfe93e4e3d5ff9075111100e3789dca219ade5a24d27e19d16b3353149da1833e9b691bb38634e8dc04469be7032132906c927d7e1a49b414730612877bc6b2810c8f202daf793d1ab0d6b5cb21d52f9e52e883859887a5d9` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(jsonSig))) + r := io.NopCloser(bytes.NewReader([]byte(jsonSig))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 200, Body: r, @@ -52,7 +52,7 @@ func TestClient_Sign_HappyPath(t *testing.T) { func TestClient_Sign_500(t *testing.T) { jsonSig := `0xb3baa751d0a9132cfe93e4e3d5ff9075111100e3789dca219ade5a24d27e19d16b3353149da1833e9b691bb38634e8dc04469be7032132906c927d7e1a49b414730612877bc6b2810c8f202daf793d1ab0d6b5cb21d52f9e52e883859887a5d9` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(jsonSig))) + r := io.NopCloser(bytes.NewReader([]byte(jsonSig))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 500, Body: r, @@ -71,7 +71,7 @@ func TestClient_Sign_500(t *testing.T) { func TestClient_Sign_412(t *testing.T) { jsonSig := `0xb3baa751d0a9132cfe93e4e3d5ff9075111100e3789dca219ade5a24d27e19d16b3353149da1833e9b691bb38634e8dc04469be7032132906c927d7e1a49b414730612877bc6b2810c8f202daf793d1ab0d6b5cb21d52f9e52e883859887a5d9` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(jsonSig))) + r := io.NopCloser(bytes.NewReader([]byte(jsonSig))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 412, Body: r, @@ -90,7 +90,7 @@ func TestClient_Sign_412(t *testing.T) { func TestClient_Sign_400(t *testing.T) { jsonSig := `0xb3baa751d0a9132cfe93e4e3d5ff9075111100e3789dca219ade5a24d27e19d16b3353149da1833e9b691bb38634e8dc04469be7032132906c927d7e1a49b414730612877bc6b2810c8f202daf793d1ab0d6b5cb21d52f9e52e883859887a5d9` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(jsonSig))) + r := io.NopCloser(bytes.NewReader([]byte(jsonSig))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 400, Body: r, @@ -110,7 +110,7 @@ func TestClient_GetPublicKeys_HappyPath(t *testing.T) { // public keys are returned hex encoded with 0x json := `["0xa2b5aaad9c6efefe7bb9b1243a043404f3362937cfb6b31833929833173f476630ea2cfeb0d9ddf15f97ca8685948820"]` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(json))) + r := io.NopCloser(bytes.NewReader([]byte(json))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 200, Body: r, @@ -129,7 +129,7 @@ func TestClient_GetPublicKeys_EncodingError(t *testing.T) { // public keys are returned hex encoded with 0x json := `["a2b5aaad9c6efefe7bb9b1243a043404f3362937c","fb6b31833929833173f476630ea2cfe","b0d9ddf15fca8685948820"]` // create a new reader with that JSON - r := ioutil.NopCloser(bytes.NewReader([]byte(json))) + r := io.NopCloser(bytes.NewReader([]byte(json))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 200, Body: r, @@ -146,7 +146,7 @@ func TestClient_GetPublicKeys_EncodingError(t *testing.T) { func TestClient_ReloadSignerKeys_HappyPath(t *testing.T) { mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(nil)), + Body: io.NopCloser(bytes.NewReader(nil)), }} u, err := url.Parse("example.com") assert.NoError(t, err) @@ -158,7 +158,7 @@ func TestClient_ReloadSignerKeys_HappyPath(t *testing.T) { // TODO: not really in use, should be revisited func TestClient_GetServerStatus_HappyPath(t *testing.T) { json := `"some server status, not sure what it looks like, need to find some sample data"` - r := ioutil.NopCloser(bytes.NewReader([]byte(json))) + r := io.NopCloser(bytes.NewReader([]byte(json))) mock := &mockTransport{mockResponse: &http.Response{ StatusCode: 200, Body: r, diff --git a/validator/keymanager/remote/keymanager.go b/validator/keymanager/remote/keymanager.go index e3a4c055c..80f466678 100644 --- a/validator/keymanager/remote/keymanager.go +++ b/validator/keymanager/remote/keymanager.go @@ -8,7 +8,7 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" + "os" "path/filepath" "sort" "strings" @@ -98,7 +98,7 @@ func NewKeymanager(_ context.Context, cfg *SetupConfig) (*Keymanager, error) { // Load the CA for the server certificate if present. cp := x509.NewCertPool() if cfg.Opts.RemoteCertificate.CACertPath != "" { - serverCA, err := ioutil.ReadFile(cfg.Opts.RemoteCertificate.CACertPath) + serverCA, err := os.ReadFile(cfg.Opts.RemoteCertificate.CACertPath) if err != nil { return nil, errors.Wrap(err, "failed to obtain server's CA certificate") } @@ -143,7 +143,7 @@ func NewKeymanager(_ context.Context, cfg *SetupConfig) (*Keymanager, error) { // UnmarshalOptionsFile attempts to JSON unmarshal a keymanager // options file into a struct. func UnmarshalOptionsFile(r io.ReadCloser) (*KeymanagerOpts, error) { - enc, err := ioutil.ReadAll(r) + enc, err := io.ReadAll(r) if err != nil { return nil, errors.Wrap(err, "could not read config") } diff --git a/validator/keymanager/remote/keymanager_test.go b/validator/keymanager/remote/keymanager_test.go index 0c15020ba..9d85c70a6 100644 --- a/validator/keymanager/remote/keymanager_test.go +++ b/validator/keymanager/remote/keymanager_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "os" "strconv" "testing" @@ -171,19 +171,19 @@ func TestNewRemoteKeymanager(t *testing.T) { require.NoError(t, os.MkdirAll(dir, 0777)) if test.caCert != "" { caCertPath := fmt.Sprintf("%s/ca.crt", dir) - err := ioutil.WriteFile(caCertPath, []byte(test.caCert), params.BeaconIoConfig().ReadWritePermissions) + err := os.WriteFile(caCertPath, []byte(test.caCert), params.BeaconIoConfig().ReadWritePermissions) require.NoError(t, err, "Failed to write CA certificate") test.opts.RemoteCertificate.CACertPath = caCertPath } if test.clientCert != "" { clientCertPath := fmt.Sprintf("%s/client.crt", dir) - err := ioutil.WriteFile(clientCertPath, []byte(test.clientCert), params.BeaconIoConfig().ReadWritePermissions) + err := os.WriteFile(clientCertPath, []byte(test.clientCert), params.BeaconIoConfig().ReadWritePermissions) require.NoError(t, err, "Failed to write client certificate") test.opts.RemoteCertificate.ClientCertPath = clientCertPath } if test.clientKey != "" { clientKeyPath := fmt.Sprintf("%s/client.key", dir) - err := ioutil.WriteFile(clientKeyPath, []byte(test.clientKey), params.BeaconIoConfig().ReadWritePermissions) + err := os.WriteFile(clientKeyPath, []byte(test.clientKey), params.BeaconIoConfig().ReadWritePermissions) require.NoError(t, err, "Failed to write client key") test.opts.RemoteCertificate.ClientKeyPath = clientKeyPath } @@ -330,7 +330,7 @@ func TestUnmarshalOptionsFile_DefaultRequireTls(t *testing.T) { require.NoError(t, err) _, err = buffer.Write(b) require.NoError(t, err) - r := ioutil.NopCloser(&buffer) + r := io.NopCloser(&buffer) opts, err := UnmarshalOptionsFile(r) assert.NoError(t, err) diff --git a/validator/node/node.go b/validator/node/node.go index 4ed76e654..82ab2c15a 100644 --- a/validator/node/node.go +++ b/validator/node/node.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -789,7 +788,7 @@ func unmarshalFromFile(ctx context.Context, from string, to interface{}) error { log.WithError(err).Error("failed to close json file") } }(jsonFile) - byteValue, readerror := ioutil.ReadAll(jsonFile) + byteValue, readerror := io.ReadAll(jsonFile) if readerror != nil { return errors.Wrap(readerror, "failed to read json file") } diff --git a/validator/node/node_test.go b/validator/node/node_test.go index 3a9df9324..c457b07cc 100644 --- a/validator/node/node_test.go +++ b/validator/node/node_test.go @@ -4,7 +4,6 @@ import ( "context" "flag" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -36,7 +35,7 @@ func TestNode_Builds(t *testing.T) { require.NoError(t, os.MkdirAll(passwordDir, os.ModePerm)) passwordFile := filepath.Join(passwordDir, "password.txt") walletPassword := "$$Passw0rdz2$$" - require.NoError(t, ioutil.WriteFile( + require.NoError(t, os.WriteFile( passwordFile, []byte(walletPassword), os.ModePerm, @@ -484,7 +483,7 @@ func TestFeeRecipientConfig(t *testing.T) { require.NoError(t, set.Set(flags.FeeRecipientConfigFileFlag.Name, tt.args.feeRecipientFlagValues.dir)) } if tt.args.feeRecipientFlagValues.url != "" { - content, err := ioutil.ReadFile(tt.args.feeRecipientFlagValues.url) + content, err := os.ReadFile(tt.args.feeRecipientFlagValues.url) require.NoError(t, err) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) diff --git a/validator/rpc/accounts_test.go b/validator/rpc/accounts_test.go index 2ee06c4d0..6b28241ba 100644 --- a/validator/rpc/accounts_test.go +++ b/validator/rpc/accounts_test.go @@ -6,7 +6,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "path/filepath" "testing" "time" @@ -168,7 +168,7 @@ func TestServer_BackupAccounts(t *testing.T) { for i, f := range r.File { keystoreFile, err := f.Open() require.NoError(t, err) - encoded, err := ioutil.ReadAll(keystoreFile) + encoded, err := io.ReadAll(keystoreFile) if err != nil { require.NoError(t, keystoreFile.Close()) t.Fatal(err) diff --git a/validator/slashing-protection-history/import.go b/validator/slashing-protection-history/import.go index f8fa7ec9c..13b9bbfc5 100644 --- a/validator/slashing-protection-history/import.go +++ b/validator/slashing-protection-history/import.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "github.com/pkg/errors" types "github.com/prysmaticlabs/eth2-types" @@ -24,7 +23,7 @@ import ( // protection in the validator client's database. For more information, see the EIP document here: // https://eips.ethereum.org/EIPS/eip-3076. func ImportStandardProtectionJSON(ctx context.Context, validatorDB db.Database, r io.Reader) error { - encodedJSON, err := ioutil.ReadAll(r) + encodedJSON, err := io.ReadAll(r) if err != nil { return errors.Wrap(err, "could not read slashing protection JSON file") }