* replace deprecated ioutil lib calls

* fix for FileInfo type required

* fix for ioutil.Discard

* fix .Discard

* fix for go-bindata generated files
This commit is contained in:
Wanwiset Peerapatanapokin 2024-01-19 15:05:03 +04:00 committed by GitHub
parent 81ff6421d0
commit aaa246f60e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
108 changed files with 474 additions and 457 deletions

View file

@ -20,7 +20,6 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"errors" "errors"
"io" "io"
"io/ioutil"
"github.com/XinFinOrg/XDPoSChain/accounts/keystore" "github.com/XinFinOrg/XDPoSChain/accounts/keystore"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -31,7 +30,7 @@ import (
// NewTransactor is a utility method to easily create a transaction signer from // NewTransactor is a utility method to easily create a transaction signer from
// an encrypted json key stream and the associated passphrase. // an encrypted json key stream and the associated passphrase.
func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) { func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
json, err := ioutil.ReadAll(keyin) json, err := io.ReadAll(keyin)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -20,7 +20,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"sync" "sync"
@ -76,7 +75,7 @@ type SimulatedBackend struct {
func SimulateWalletAddressAndSignFn() (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) { func SimulateWalletAddressAndSignFn() (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) {
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := ioutil.TempDir("", "eth-SimulateWalletAddressAndSignFn-test") dir, _ := os.MkdirTemp("", "eth-SimulateWalletAddressAndSignFn-test")
new := func(kd string) *keystore.KeyStore { new := func(kd string) *keystore.KeyStore {
return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP)

View file

@ -18,7 +18,6 @@ package bind
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -831,7 +830,7 @@ func TestBindings(t *testing.T) {
t.Skip("symlinked environment doesn't support bind (https://github.com/golang/go/issues/14845)") t.Skip("symlinked environment doesn't support bind (https://github.com/golang/go/issues/14845)")
} }
// Create a temporary workspace for the test suite // Create a temporary workspace for the test suite
ws, err := ioutil.TempDir("", "") ws, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary workspace: %v", err) t.Fatalf("failed to create temporary workspace: %v", err)
} }
@ -848,7 +847,7 @@ func TestBindings(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("test %d: failed to generate binding: %v", i, err) t.Fatalf("test %d: failed to generate binding: %v", i, err)
} }
if err = ioutil.WriteFile(filepath.Join(pkg, strings.ToLower(tt.name)+".go"), []byte(bind), 0600); err != nil { if err = os.WriteFile(filepath.Join(pkg, strings.ToLower(tt.name)+".go"), []byte(bind), 0600); err != nil {
t.Fatalf("test %d: failed to write binding: %v", i, err) t.Fatalf("test %d: failed to write binding: %v", i, err)
} }
// Generate the test file with the injected test code // Generate the test file with the injected test code
@ -857,7 +856,7 @@ func TestBindings(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("test %d: failed to generate tests: %v", i, err) t.Fatalf("test %d: failed to generate tests: %v", i, err)
} }
if err := ioutil.WriteFile(filepath.Join(pkg, strings.ToLower(tt.name)+"_test.go"), blob, 0600); err != nil { if err := os.WriteFile(filepath.Join(pkg, strings.ToLower(tt.name)+"_test.go"), blob, 0600); err != nil {
t.Fatalf("test %d: failed to write tests: %v", i, err) t.Fatalf("test %d: failed to write tests: %v", i, err)
} }
} }

View file

@ -18,7 +18,6 @@ package keystore
import ( import (
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"os" "os"
"path/filepath" "path/filepath"
@ -381,11 +380,11 @@ func TestUpdatedKeyfileContents(t *testing.T) {
return return
} }
// needed so that modTime of `file` is different to its current value after ioutil.WriteFile // needed so that modTime of `file` is different to its current value after os.WriteFile
time.Sleep(1000 * time.Millisecond) time.Sleep(1000 * time.Millisecond)
// Now replace file contents with crap // Now replace file contents with crap
if err := ioutil.WriteFile(file, []byte("foo"), 0644); err != nil { if err := os.WriteFile(file, []byte("foo"), 0644); err != nil {
t.Fatal(err) t.Fatal(err)
return return
} }
@ -398,9 +397,9 @@ func TestUpdatedKeyfileContents(t *testing.T) {
// forceCopyFile is like cp.CopyFile, but doesn't complain if the destination exists. // forceCopyFile is like cp.CopyFile, but doesn't complain if the destination exists.
func forceCopyFile(dst, src string) error { func forceCopyFile(dst, src string) error {
data, err := ioutil.ReadFile(src) data, err := os.ReadFile(src)
if err != nil { if err != nil {
return err return err
} }
return ioutil.WriteFile(dst, data, 0644) return os.WriteFile(dst, data, 0644)
} }

View file

@ -17,7 +17,6 @@
package keystore package keystore
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -41,7 +40,7 @@ func (fc *fileCache) scan(keyDir string) (mapset.Set, mapset.Set, mapset.Set, er
t0 := time.Now() t0 := time.Now()
// List all the failes from the keystore folder // List all the failes from the keystore folder
files, err := ioutil.ReadDir(keyDir) files, err := os.ReadDir(keyDir)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@ -58,14 +57,18 @@ func (fc *fileCache) scan(keyDir string) (mapset.Set, mapset.Set, mapset.Set, er
for _, fi := range files { for _, fi := range files {
// Skip any non-key files from the folder // Skip any non-key files from the folder
path := filepath.Join(keyDir, fi.Name()) path := filepath.Join(keyDir, fi.Name())
if skipKeyFile(fi) { fiInfo, err := fi.Info()
if err != nil {
log.Warn("scan get FileInfo", "err", err, "path", path)
}
if skipKeyFile(fiInfo) {
log.Trace("Ignoring file on account scan", "path", path) log.Trace("Ignoring file on account scan", "path", path)
continue continue
} }
// Gather the set of all and fresly modified files // Gather the set of all and fresly modified files
all.Add(path) all.Add(path)
modified := fi.ModTime() modified := fiInfo.ModTime()
if modified.After(fc.lastMod) { if modified.After(fc.lastMod) {
mods.Add(path) mods.Add(path)
} }

View file

@ -23,7 +23,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -188,7 +187,7 @@ func writeKeyFile(file string, content []byte) error {
} }
// Atomic write: create a temporary hidden file first // Atomic write: create a temporary hidden file first
// then move it into place. TempFile assigns mode 0600. // then move it into place. TempFile assigns mode 0600.
f, err := ioutil.TempFile(filepath.Dir(file), "."+filepath.Base(file)+".tmp") f, err := os.CreateTemp(filepath.Dir(file), "."+filepath.Base(file)+".tmp")
if err != nil { if err != nil {
return err return err
} }

View file

@ -33,7 +33,7 @@ import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -76,7 +76,7 @@ type keyStorePassphrase struct {
func (ks keyStorePassphrase) GetKey(addr common.Address, filename, auth string) (*Key, error) { func (ks keyStorePassphrase) GetKey(addr common.Address, filename, auth string) (*Key, error) {
// Load the key from the keystore and decrypt its contents // Load the key from the keystore and decrypt its contents
keyjson, err := ioutil.ReadFile(filename) keyjson, err := os.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -17,7 +17,7 @@
package keystore package keystore
import ( import (
"io/ioutil" "os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -30,7 +30,7 @@ const (
// Tests that a json key file can be decrypted and encrypted in multiple rounds. // Tests that a json key file can be decrypted and encrypted in multiple rounds.
func TestKeyEncryptDecrypt(t *testing.T) { func TestKeyEncryptDecrypt(t *testing.T) {
keyjson, err := ioutil.ReadFile("testdata/very-light-scrypt.json") keyjson, err := os.ReadFile("testdata/very-light-scrypt.json")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -20,7 +20,6 @@ import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -32,7 +31,7 @@ import (
) )
func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) { func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) {
d, err := ioutil.TempDir("", "geth-keystore-test") d, err := os.MkdirTemp("", "geth-keystore-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -17,7 +17,6 @@
package keystore package keystore
import ( import (
"io/ioutil"
"math/rand" "math/rand"
"os" "os"
"runtime" "runtime"
@ -375,7 +374,7 @@ func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
} }
func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) { func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
d, err := ioutil.TempDir("", "eth-keystore-test") d, err := os.MkdirTemp("", "eth-keystore-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -39,7 +39,6 @@ import (
"fmt" "fmt"
"go/parser" "go/parser"
"go/token" "go/token"
"io/ioutil"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@ -149,7 +148,7 @@ func doInstall(cmdline []string) {
goinstall.Args = append(goinstall.Args, packages...) goinstall.Args = append(goinstall.Args, packages...)
build.MustRun(goinstall) build.MustRun(goinstall)
if cmds, err := ioutil.ReadDir("cmd"); err == nil { if cmds, err := os.ReadDir("cmd"); err == nil {
for _, cmd := range cmds { for _, cmd := range cmds {
pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly) pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
if err != nil { if err != nil {

View file

@ -18,7 +18,7 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"github.com/XinFinOrg/XDPoSChain/accounts" "github.com/XinFinOrg/XDPoSChain/accounts"
"github.com/XinFinOrg/XDPoSChain/accounts/keystore" "github.com/XinFinOrg/XDPoSChain/accounts/keystore"
@ -340,7 +340,7 @@ func importWallet(ctx *cli.Context) error {
if len(keyfile) == 0 { if len(keyfile) == 0 {
utils.Fatalf("keyfile must be given as argument") utils.Fatalf("keyfile must be given as argument")
} }
keyJson, err := ioutil.ReadFile(keyfile) keyJson, err := os.ReadFile(keyfile)
if err != nil { if err != nil {
utils.Fatalf("Could not read wallet file: %v", err) utils.Fatalf("Could not read wallet file: %v", err)
} }

View file

@ -17,7 +17,7 @@
package main package main
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
@ -115,7 +115,7 @@ Passphrase: {{.InputLine "foo"}}
Address: {xdcd4584b5f6229b7be90727b0fc8c6b91bb427821f} Address: {xdcd4584b5f6229b7be90727b0fc8c6b91bb427821f}
`) `)
files, err := ioutil.ReadDir(filepath.Join(XDC.Datadir, "keystore")) files, err := os.ReadDir(filepath.Join(XDC.Datadir, "keystore"))
if len(files) != 1 { if len(files) != 1 {
t.Errorf("expected one key file in keystore directory, found %d files (error: %v)", len(files), err) t.Errorf("expected one key file in keystore directory, found %d files (error: %v)", len(files), err)
} }

View file

@ -20,8 +20,8 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os"
"os/exec" "os/exec"
"runtime" "runtime"
"strings" "strings"
@ -74,7 +74,7 @@ func printOSDetails(w io.Writer) {
case "openbsd", "netbsd", "freebsd", "dragonfly": case "openbsd", "netbsd", "freebsd", "dragonfly":
printCmdOut(w, "uname -v: ", "uname", "-v") printCmdOut(w, "uname -v: ", "uname", "-v")
case "solaris": case "solaris":
out, err := ioutil.ReadFile("/etc/release") out, err := os.ReadFile("/etc/release")
if err == nil { if err == nil {
fmt.Fprintf(w, "/etc/release: %s\n", out) fmt.Fprintf(w, "/etc/release: %s\n", out)
} else { } else {

View file

@ -17,13 +17,13 @@
package main package main
import ( import (
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
) )
@ -108,7 +108,7 @@ func testDAOForkBlockNewChain(t *testing.T, test int, genesis string, expectBloc
// Start a XDC instance with the requested flags set and immediately terminate // Start a XDC instance with the requested flags set and immediately terminate
if genesis != "" { if genesis != "" {
json := filepath.Join(datadir, "genesis.json") json := filepath.Join(datadir, "genesis.json")
if err := ioutil.WriteFile(json, []byte(genesis), 0600); err != nil { if err := os.WriteFile(json, []byte(genesis), 0600); err != nil {
t.Fatalf("test %d: failed to write genesis file: %v", test, err) t.Fatalf("test %d: failed to write genesis file: %v", test, err)
} }
runXDC(t, "--datadir", datadir, "init", json).WaitExit() runXDC(t, "--datadir", datadir, "init", json).WaitExit()

View file

@ -18,7 +18,6 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"testing" "testing"
@ -27,7 +26,7 @@ import (
) )
func tmpdir(t *testing.T) string { func tmpdir(t *testing.T) string {
dir, err := ioutil.TempDir("", "XDC-test") dir, err := os.MkdirTemp("", "XDC-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -20,7 +20,6 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
@ -100,7 +99,7 @@ func main() {
} }
} else { } else {
// Otherwise load up the ABI, optional bytecode and type name from the parameters // Otherwise load up the ABI, optional bytecode and type name from the parameters
abi, err := ioutil.ReadFile(*abiFlag) abi, err := os.ReadFile(*abiFlag)
if err != nil { if err != nil {
fmt.Printf("Failed to read input ABI: %v\n", err) fmt.Printf("Failed to read input ABI: %v\n", err)
os.Exit(-1) os.Exit(-1)
@ -109,7 +108,7 @@ func main() {
bin := []byte{} bin := []byte{}
if *binFlag != "" { if *binFlag != "" {
if bin, err = ioutil.ReadFile(*binFlag); err != nil { if bin, err = os.ReadFile(*binFlag); err != nil {
fmt.Printf("Failed to read input bytecode: %v\n", err) fmt.Printf("Failed to read input bytecode: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }
@ -133,7 +132,7 @@ func main() {
fmt.Printf("%s\n", code) fmt.Printf("%s\n", code)
return return
} }
if err := ioutil.WriteFile(*outFlag, []byte(code), 0600); err != nil { if err := os.WriteFile(*outFlag, []byte(code), 0600); err != nil {
fmt.Printf("Failed to write ABI binding: %v\n", err) fmt.Printf("Failed to write ABI binding: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }

View file

@ -19,7 +19,6 @@ package main
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -100,7 +99,7 @@ If you want to encrypt an existing private key, it can be specified by setting
if err := os.MkdirAll(filepath.Dir(keyfilepath), 0700); err != nil { if err := os.MkdirAll(filepath.Dir(keyfilepath), 0700); err != nil {
utils.Fatalf("Could not create directory %s", filepath.Dir(keyfilepath)) utils.Fatalf("Could not create directory %s", filepath.Dir(keyfilepath))
} }
if err := ioutil.WriteFile(keyfilepath, keyjson, 0600); err != nil { if err := os.WriteFile(keyfilepath, keyjson, 0600); err != nil {
utils.Fatalf("Failed to write keyfile to %s: %v", keyfilepath, err) utils.Fatalf("Failed to write keyfile to %s: %v", keyfilepath, err)
} }

View file

@ -19,7 +19,7 @@ package main
import ( import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil" "os"
"github.com/XinFinOrg/XDPoSChain/accounts/keystore" "github.com/XinFinOrg/XDPoSChain/accounts/keystore"
"github.com/XinFinOrg/XDPoSChain/cmd/utils" "github.com/XinFinOrg/XDPoSChain/cmd/utils"
@ -54,7 +54,7 @@ make sure to use this feature with great caution!`,
keyfilepath := ctx.Args().First() keyfilepath := ctx.Args().First()
// Read key from file. // Read key from file.
keyjson, err := ioutil.ReadFile(keyfilepath) keyjson, err := os.ReadFile(keyfilepath)
if err != nil { if err != nil {
utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err) utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
} }

View file

@ -19,7 +19,7 @@ package main
import ( import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil" "os"
"github.com/XinFinOrg/XDPoSChain/accounts/keystore" "github.com/XinFinOrg/XDPoSChain/accounts/keystore"
"github.com/XinFinOrg/XDPoSChain/cmd/utils" "github.com/XinFinOrg/XDPoSChain/cmd/utils"
@ -56,7 +56,7 @@ To sign a message contained in a file, use the --msgfile flag.
// Load the keyfile. // Load the keyfile.
keyfilepath := ctx.Args().First() keyfilepath := ctx.Args().First()
keyjson, err := ioutil.ReadFile(keyfilepath) keyjson, err := os.ReadFile(keyfilepath)
if err != nil { if err != nil {
utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err) utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
} }
@ -146,7 +146,7 @@ func getMessage(ctx *cli.Context, msgarg int) []byte {
if len(ctx.Args()) > msgarg { if len(ctx.Args()) > msgarg {
utils.Fatalf("Can't use --msgfile and message argument at the same time.") utils.Fatalf("Can't use --msgfile and message argument at the same time.")
} }
msg, err := ioutil.ReadFile(file) msg, err := os.ReadFile(file)
if err != nil { if err != nil {
utils.Fatalf("Can't read message file: %v", err) utils.Fatalf("Can't read message file: %v", err)
} }

View file

@ -17,14 +17,13 @@
package main package main
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
) )
func TestMessageSignVerify(t *testing.T) { func TestMessageSignVerify(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "ethkey-test") tmpdir, err := os.MkdirTemp("", "ethkey-test")
if err != nil { if err != nil {
t.Fatal("Can't create temporary directory:", err) t.Fatal("Can't create temporary directory:", err)
} }

View file

@ -19,7 +19,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"github.com/XinFinOrg/XDPoSChain/cmd/utils" "github.com/XinFinOrg/XDPoSChain/cmd/utils"
@ -35,7 +35,7 @@ func getPassPhrase(ctx *cli.Context, confirmation bool) string {
// Look for the --passphrase flag. // Look for the --passphrase flag.
passphraseFile := ctx.String(passphraseFlag.Name) passphraseFile := ctx.String(passphraseFlag.Name)
if passphraseFile != "" { if passphraseFile != "" {
content, err := ioutil.ReadFile(passphraseFile) content, err := os.ReadFile(passphraseFile)
if err != nil { if err != nil {
utils.Fatalf("Failed to read passphrase file '%s': %v", utils.Fatalf("Failed to read passphrase file '%s': %v",
passphraseFile, err) passphraseFile, err)
@ -64,7 +64,8 @@ func getPassPhrase(ctx *cli.Context, confirmation bool) string {
// that can be safely used to calculate a signature from. // that can be safely used to calculate a signature from.
// //
// The hash is calulcated as // The hash is calulcated as
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). //
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
// //
// This gives context to the signed message and prevents signing of transactions. // This gives context to the signed message and prevents signing of transactions.
func signHash(data []byte) []byte { func signHash(data []byte) []byte {

View file

@ -19,7 +19,7 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "os"
"github.com/XinFinOrg/XDPoSChain/cmd/evm/internal/compiler" "github.com/XinFinOrg/XDPoSChain/cmd/evm/internal/compiler"
@ -41,7 +41,7 @@ func compileCmd(ctx *cli.Context) error {
} }
fn := ctx.Args().First() fn := ctx.Args().First()
src, err := ioutil.ReadFile(fn) src, err := os.ReadFile(fn)
if err != nil { if err != nil {
return err return err
} }

View file

@ -19,7 +19,7 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"github.com/XinFinOrg/XDPoSChain/core/asm" "github.com/XinFinOrg/XDPoSChain/core/asm"
@ -39,7 +39,7 @@ func disasmCmd(ctx *cli.Context) error {
} }
fn := ctx.Args().First() fn := ctx.Args().First()
in, err := ioutil.ReadFile(fn) in, err := os.ReadFile(fn)
if err != nil { if err != nil {
return err return err
} }

View file

@ -20,12 +20,13 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/core/rawdb" "io"
"io/ioutil"
"os" "os"
"runtime/pprof" "runtime/pprof"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
goruntime "runtime" goruntime "runtime"
"github.com/XinFinOrg/XDPoSChain/cmd/evm/internal/compiler" "github.com/XinFinOrg/XDPoSChain/cmd/evm/internal/compiler"
@ -125,13 +126,13 @@ func runCmd(ctx *cli.Context) error {
// If - is specified, it means that code comes from stdin // If - is specified, it means that code comes from stdin
if ctx.GlobalString(CodeFileFlag.Name) == "-" { if ctx.GlobalString(CodeFileFlag.Name) == "-" {
//Try reading from stdin //Try reading from stdin
if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil { if hexcode, err = io.ReadAll(os.Stdin); err != nil {
fmt.Printf("Could not load code from stdin: %v\n", err) fmt.Printf("Could not load code from stdin: %v\n", err)
os.Exit(1) os.Exit(1)
} }
} else { } else {
// Codefile with hex assembly // Codefile with hex assembly
if hexcode, err = ioutil.ReadFile(ctx.GlobalString(CodeFileFlag.Name)); err != nil { if hexcode, err = os.ReadFile(ctx.GlobalString(CodeFileFlag.Name)); err != nil {
fmt.Printf("Could not load code from file: %v\n", err) fmt.Printf("Could not load code from file: %v\n", err)
os.Exit(1) os.Exit(1)
} }
@ -142,7 +143,7 @@ func runCmd(ctx *cli.Context) error {
code = common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name)) code = common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))
} else if fn := ctx.Args().First(); len(fn) > 0 { } else if fn := ctx.Args().First(); len(fn) > 0 {
// EASM-file to compile // EASM-file to compile
src, err := ioutil.ReadFile(fn) src, err := os.ReadFile(fn)
if err != nil { if err != nil {
return err return err
} }

View file

@ -20,7 +20,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/state"
@ -76,7 +75,7 @@ func stateTestCmd(ctx *cli.Context) error {
debugger = vm.NewStructLogger(config) debugger = vm.NewStructLogger(config)
} }
// Load the test content from the input file // Load the test content from the input file
src, err := ioutil.ReadFile(ctx.Args().First()) src, err := os.ReadFile(ctx.Args().First())
if err != nil { if err != nil {
return err return err
} }

View file

@ -28,7 +28,7 @@ import (
"flag" "flag"
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil" "io"
"math" "math"
"math/big" "math/big"
"net/http" "net/http"
@ -139,7 +139,7 @@ func main() {
log.Crit("Failed to render the faucet template", "err", err) log.Crit("Failed to render the faucet template", "err", err)
} }
// Load and parse the genesis block requested by the user // Load and parse the genesis block requested by the user
blob, err := ioutil.ReadFile(*genesisFlag) blob, err := os.ReadFile(*genesisFlag)
if err != nil { if err != nil {
log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err) log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
} }
@ -157,13 +157,13 @@ func main() {
} }
} }
// Load up the account key and decrypt its password // Load up the account key and decrypt its password
if blob, err = ioutil.ReadFile(*accPassFlag); err != nil { if blob, err = os.ReadFile(*accPassFlag); err != nil {
log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err) log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
} }
pass := string(blob) pass := string(blob)
ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP) ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil { if blob, err = os.ReadFile(*accJSONFlag); err != nil {
log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err) log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
} }
acc, err := ks.Import(blob, pass, pass) acc, err := ks.Import(blob, pass, pass)
@ -729,7 +729,7 @@ func authTwitter(url string) (string, string, common.Address, error) {
} }
username := parts[len(parts)-3] username := parts[len(parts)-3]
body, err := ioutil.ReadAll(res.Body) body, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", "", common.Address{}, err return "", "", common.Address{}, err
} }
@ -763,7 +763,7 @@ func authGooglePlus(url string) (string, string, common.Address, error) {
} }
defer res.Body.Close() defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body) body, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", "", common.Address{}, err return "", "", common.Address{}, err
} }
@ -797,7 +797,7 @@ func authFacebook(url string) (string, string, common.Address, error) {
} }
defer res.Body.Close() defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body) body, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", "", common.Address{}, err return "", "", common.Address{}, err
} }

View file

@ -1,15 +1,15 @@
// Code generated by go-bindata. DO NOT EDIT. // Code generated by go-bindata. DO NOT EDIT.
// sources: // sources:
// faucet.html // faucet.html (11.726kB)
package main package main
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"crypto/sha256"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -19,7 +19,7 @@ import (
func bindataRead(data []byte, name string) ([]byte, error) { func bindataRead(data []byte, name string) ([]byte, error) {
gz, err := gzip.NewReader(bytes.NewBuffer(data)) gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil { if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err) return nil, fmt.Errorf("read %q: %w", name, err)
} }
var buf bytes.Buffer var buf bytes.Buffer
@ -27,7 +27,7 @@ func bindataRead(data []byte, name string) ([]byte, error) {
clErr := gz.Close() clErr := gz.Close()
if err != nil { if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err) return nil, fmt.Errorf("read %q: %w", name, err)
} }
if clErr != nil { if clErr != nil {
return nil, err return nil, err
@ -37,8 +37,9 @@ func bindataRead(data []byte, name string) ([]byte, error) {
} }
type asset struct { type asset struct {
bytes []byte bytes []byte
info os.FileInfo info os.FileInfo
digest [sha256.Size]byte
} }
type bindataFileInfo struct { type bindataFileInfo struct {
@ -83,7 +84,7 @@ func faucetHtml() (*asset, error) {
} }
info := bindataFileInfo{name: "faucet.html", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)} info := bindataFileInfo{name: "faucet.html", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)}
a := &asset{bytes: bytes, info: info} a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x9b, 0x9e, 0x78, 0xa7, 0x98, 0x53, 0xe5, 0xcc, 0x18, 0xfc, 0x7e, 0x9a, 0xb2, 0xa6, 0xa5, 0x82, 0xbc, 0x1e, 0xb5, 0x94, 0xa5, 0x5d, 0xfe, 0x42, 0x78, 0x75, 0x6d, 0x98, 0x6d, 0x26, 0x43, 0x8d}}
return a, nil return a, nil
} }
@ -102,6 +103,12 @@ func Asset(name string) ([]byte, error) {
return nil, fmt.Errorf("Asset %s not found", name) return nil, fmt.Errorf("Asset %s not found", name)
} }
// AssetString returns the asset contents as a string (instead of a []byte).
func AssetString(name string) (string, error) {
data, err := Asset(name)
return string(data), err
}
// MustAsset is like Asset but panics when Asset would return an error. // MustAsset is like Asset but panics when Asset would return an error.
// It simplifies safe initialization of global variables. // It simplifies safe initialization of global variables.
func MustAsset(name string) []byte { func MustAsset(name string) []byte {
@ -113,6 +120,12 @@ func MustAsset(name string) []byte {
return a return a
} }
// MustAssetString is like AssetString but panics when Asset would return an
// error. It simplifies safe initialization of global variables.
func MustAssetString(name string) string {
return string(MustAsset(name))
}
// AssetInfo loads and returns the asset info for the given name. // AssetInfo loads and returns the asset info for the given name.
// It returns an error if the asset could not be found or // It returns an error if the asset could not be found or
// could not be loaded. // could not be loaded.
@ -128,6 +141,33 @@ func AssetInfo(name string) (os.FileInfo, error) {
return nil, fmt.Errorf("AssetInfo %s not found", name) return nil, fmt.Errorf("AssetInfo %s not found", name)
} }
// AssetDigest returns the digest of the file with the given name. It returns an
// error if the asset could not be found or the digest could not be loaded.
func AssetDigest(name string) ([sha256.Size]byte, error) {
canonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[canonicalName]; ok {
a, err := f()
if err != nil {
return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s can't read by error: %v", name, err)
}
return a.digest, nil
}
return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s not found", name)
}
// Digests returns a map of all known files and their checksums.
func Digests() (map[string][sha256.Size]byte, error) {
mp := make(map[string][sha256.Size]byte, len(_bindata))
for name := range _bindata {
a, err := _bindata[name]()
if err != nil {
return nil, err
}
mp[name] = a.digest
}
return mp, nil
}
// AssetNames returns the names of the assets. // AssetNames returns the names of the assets.
func AssetNames() []string { func AssetNames() []string {
names := make([]string, 0, len(_bindata)) names := make([]string, 0, len(_bindata))
@ -142,18 +182,23 @@ var _bindata = map[string]func() (*asset, error){
"faucet.html": faucetHtml, "faucet.html": faucetHtml,
} }
// AssetDebug is true if the assets were built with the debug flag enabled.
const AssetDebug = false
// AssetDir returns the file names below a certain // AssetDir returns the file names below a certain
// directory embedded in the file by go-bindata. // directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the // For example if you run go-bindata on data/... and data contains the
// following hierarchy: // following hierarchy:
// data/ //
// foo.txt // data/
// img/ // foo.txt
// a.png // img/
// b.png // a.png
// then AssetDir("data") would return []string{"foo.txt", "img"} // b.png
// AssetDir("data/img") would return []string{"a.png", "b.png"} //
// AssetDir("foo.txt") and AssetDir("notexist") would return an error // then AssetDir("data") would return []string{"foo.txt", "img"},
// AssetDir("data/img") would return []string{"a.png", "b.png"},
// AssetDir("foo.txt") and AssetDir("notexist") would return an error, and
// AssetDir("") will return []string{"data"}. // AssetDir("") will return []string{"data"}.
func AssetDir(name string) ([]string, error) { func AssetDir(name string) ([]string, error) {
node := _bintree node := _bintree
@ -186,7 +231,7 @@ var _bintree = &bintree{nil, map[string]*bintree{
"faucet.html": {faucetHtml, map[string]*bintree{}}, "faucet.html": {faucetHtml, map[string]*bintree{}},
}} }}
// RestoreAsset restores an asset under the given directory // RestoreAsset restores an asset under the given directory.
func RestoreAsset(dir, name string) error { func RestoreAsset(dir, name string) error {
data, err := Asset(name) data, err := Asset(name)
if err != nil { if err != nil {
@ -200,14 +245,14 @@ func RestoreAsset(dir, name string) error {
if err != nil { if err != nil {
return err return err
} }
err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) err = os.WriteFile(_filePath(dir, name), data, info.Mode())
if err != nil { if err != nil {
return err return err
} }
return os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) return os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
} }
// RestoreAssets restores an asset under the given directory recursively // RestoreAssets restores an asset under the given directory recursively.
func RestoreAssets(dir, name string) error { func RestoreAssets(dir, name string) error {
children, err := AssetDir(name) children, err := AssetDir(name)
// File // File

View file

@ -21,7 +21,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"os/user" "os/user"
@ -72,7 +71,7 @@ func dial(server string, pubkey []byte) (*sshClient, error) {
var auths []ssh.AuthMethod var auths []ssh.AuthMethod
path := filepath.Join(user.HomeDir, ".ssh", "id_rsa") path := filepath.Join(user.HomeDir, ".ssh", "id_rsa")
if buf, err := ioutil.ReadFile(path); err != nil { if buf, err := os.ReadFile(path); err != nil {
log.Warn("No SSH key, falling back to passwords", "path", path, "err", err) log.Warn("No SSH key, falling back to passwords", "path", path, "err", err)
} else { } else {
key, err := ssh.ParsePrivateKey(buf) key, err := ssh.ParsePrivateKey(buf)

View file

@ -20,7 +20,6 @@ import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"net" "net"
"os" "os"
@ -63,7 +62,7 @@ func (c config) flush() {
os.MkdirAll(filepath.Dir(c.path), 0755) os.MkdirAll(filepath.Dir(c.path), 0755)
out, _ := json.MarshalIndent(c.Genesis, "", " ") out, _ := json.MarshalIndent(c.Genesis, "", " ")
if err := ioutil.WriteFile(c.path, out, 0644); err != nil { if err := os.WriteFile(c.path, out, 0644); err != nil {
log.Warn("Failed to save puppeth configs", "file", c.path, "err", err) log.Warn("Failed to save puppeth configs", "file", c.path, "err", err)
} }
} }

View file

@ -20,8 +20,8 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"os"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -419,7 +419,7 @@ func (w *wizard) manageGenesis() {
fmt.Println() fmt.Println()
fmt.Printf("Which file to save the genesis into? (default = %s.json)\n", w.network) fmt.Printf("Which file to save the genesis into? (default = %s.json)\n", w.network)
out, _ := json.MarshalIndent(w.conf.Genesis, "", " ") out, _ := json.MarshalIndent(w.conf.Genesis, "", " ")
if err := ioutil.WriteFile(w.readDefaultString(fmt.Sprintf("%s.json", w.network)), out, 0644); err != nil { if err := os.WriteFile(w.readDefaultString(fmt.Sprintf("%s.json", w.network)), out, 0644); err != nil {
log.Error("Failed to save genesis file", "err", err) log.Error("Failed to save genesis file", "err", err)
} }
log.Info("Exported existing genesis block") log.Info("Exported existing genesis block")

View file

@ -20,7 +20,6 @@ import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -76,7 +75,7 @@ func (w *wizard) run() {
// Load initial configurations and connect to all live servers // Load initial configurations and connect to all live servers
w.conf.path = filepath.Join(os.Getenv("HOME"), ".puppeth", w.network) w.conf.path = filepath.Join(os.Getenv("HOME"), ".puppeth", w.network)
blob, err := ioutil.ReadFile(w.conf.path) blob, err := os.ReadFile(w.conf.path)
if err != nil { if err != nil {
log.Warn("No previous configurations found", "path", w.conf.path) log.Warn("No previous configurations found", "path", w.conf.path)
} else if err := json.Unmarshal(blob, &w.conf); err != nil { } else if err := json.Unmarshal(blob, &w.conf); err != nil {

View file

@ -19,7 +19,6 @@ package main
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"testing" "testing"
@ -67,7 +66,7 @@ func TestFailsNoBzzAccount(t *testing.T) {
} }
func TestCmdLineOverrides(t *testing.T) { func TestCmdLineOverrides(t *testing.T) {
dir, err := ioutil.TempDir("", "bzztest") dir, err := os.MkdirTemp("", "bzztest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -161,7 +160,7 @@ func TestFileOverrides(t *testing.T) {
t.Fatalf("Error creating TOML file in TestFileOverride: %v", err) t.Fatalf("Error creating TOML file in TestFileOverride: %v", err)
} }
//create file //create file
f, err := ioutil.TempFile("", "testconfig.toml") f, err := os.CreateTemp("", "testconfig.toml")
if err != nil { if err != nil {
t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
} }
@ -172,7 +171,7 @@ func TestFileOverrides(t *testing.T) {
} }
f.Sync() f.Sync()
dir, err := ioutil.TempDir("", "bzztest") dir, err := os.MkdirTemp("", "bzztest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -259,7 +258,7 @@ func TestEnvVars(t *testing.T) {
envVars = append(envVars, fmt.Sprintf("%s=%s", CorsStringFlag.EnvVar, "*")) envVars = append(envVars, fmt.Sprintf("%s=%s", CorsStringFlag.EnvVar, "*"))
envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmSyncEnabledFlag.EnvVar, "true")) envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmSyncEnabledFlag.EnvVar, "true"))
dir, err := ioutil.TempDir("", "bzztest") dir, err := os.MkdirTemp("", "bzztest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -368,7 +367,7 @@ func TestCmdLineOverridesFile(t *testing.T) {
t.Fatalf("Error creating TOML file in TestFileOverride: %v", err) t.Fatalf("Error creating TOML file in TestFileOverride: %v", err)
} }
//write file //write file
f, err := ioutil.TempFile("", "testconfig.toml") f, err := os.CreateTemp("", "testconfig.toml")
if err != nil { if err != nil {
t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
} }
@ -379,7 +378,7 @@ func TestCmdLineOverridesFile(t *testing.T) {
} }
f.Sync() f.Sync()
dir, err := ioutil.TempDir("", "bzztest") dir, err := os.MkdirTemp("", "bzztest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -19,7 +19,6 @@ package main
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/signal" "os/signal"
"runtime" "runtime"
@ -153,7 +152,7 @@ var (
} }
) )
//declare a few constant error messages, useful for later error check comparisons in test // declare a few constant error messages, useful for later error check comparisons in test
var ( var (
SWARM_ERR_NO_BZZACCOUNT = "bzzaccount option is required but not set; check your config file, command line or environment variables" SWARM_ERR_NO_BZZACCOUNT = "bzzaccount option is required but not set; check your config file, command line or environment variables"
SWARM_ERR_SWAP_SET_NO_API = "SWAP is enabled but --swap-api is not set" SWARM_ERR_SWAP_SET_NO_API = "SWAP is enabled but --swap-api is not set"
@ -504,7 +503,7 @@ func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []stri
if err != nil { if err != nil {
utils.Fatalf("Can't find swarm account key: %v - Is the provided bzzaccount(%s) from the right datadir/Path?", err, account) utils.Fatalf("Can't find swarm account key: %v - Is the provided bzzaccount(%s) from the right datadir/Path?", err, account)
} }
keyjson, err := ioutil.ReadFile(a.URL.Path) keyjson, err := os.ReadFile(a.URL.Path)
if err != nil { if err != nil {
utils.Fatalf("Can't load swarm account key: %v", err) utils.Fatalf("Can't load swarm account key: %v", err)
} }

View file

@ -18,7 +18,6 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -89,7 +88,7 @@ func newTestCluster(t *testing.T, size int) *testCluster {
} }
}() }()
tmpdir, err := ioutil.TempDir("", "swarm-test") tmpdir, err := os.MkdirTemp("", "swarm-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -21,7 +21,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"net/http" "net/http"
"os" "os"
@ -51,7 +50,7 @@ func upload(ctx *cli.Context) {
if len(args) != 1 { if len(args) != 1 {
if fromStdin { if fromStdin {
tmp, err := ioutil.TempFile("", "swarm-stdin") tmp, err := os.CreateTemp("", "swarm-stdin")
if err != nil { if err != nil {
utils.Fatalf("error create tempfile: %s", err) utils.Fatalf("error create tempfile: %s", err)
} }

View file

@ -18,7 +18,6 @@ package main
import ( import (
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"testing" "testing"
@ -33,7 +32,7 @@ func TestCLISwarmUp(t *testing.T) {
defer cluster.Shutdown() defer cluster.Shutdown()
// create a tmp file // create a tmp file
tmp, err := ioutil.TempFile("", "swarm-test") tmp, err := os.CreateTemp("", "swarm-test")
assertNil(t, err) assertNil(t, err)
defer tmp.Close() defer tmp.Close()
defer os.Remove(tmp.Name()) defer os.Remove(tmp.Name())
@ -68,7 +67,7 @@ func assertHTTPResponse(t *testing.T, res *http.Response, expectedStatus int, ex
if res.StatusCode != expectedStatus { if res.StatusCode != expectedStatus {
t.Fatalf("expected HTTP status %d, got %s", expectedStatus, res.Status) t.Fatalf("expected HTTP status %d, got %s", expectedStatus, res.Status)
} }
data, err := ioutil.ReadAll(res.Body) data, err := io.ReadAll(res.Body)
assertNil(t, err) assertNil(t, err)
if string(data) != expectedBody { if string(data) != expectedBody {
t.Fatalf("expected HTTP body %q, got %q", expectedBody, data) t.Fatalf("expected HTTP body %q, got %q", expectedBody, data)

View file

@ -20,7 +20,6 @@ package utils
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
@ -848,7 +847,7 @@ func MakePasswordList(ctx *cli.Context) []string {
if path == "" { if path == "" {
return nil return nil
} }
text, err := ioutil.ReadFile(path) text, err := os.ReadFile(path)
if err != nil { if err != nil {
Fatalf("Failed to read password file: %v", err) Fatalf("Failed to read password file: %v", err)
} }

View file

@ -1,7 +1,6 @@
package utils package utils
import ( import (
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -18,13 +17,13 @@ func TestWalkMatch(t *testing.T) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
test1Dir, _ := ioutil.TempDir(dir, "test1") test1Dir, _ := os.MkdirTemp(dir, "test1")
test2Dir, _ := ioutil.TempDir(dir, "test2") test2Dir, _ := os.MkdirTemp(dir, "test2")
err = ioutil.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm) err = os.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
err = ioutil.WriteFile(filepath.Join(test2Dir, "test2.abc"), []byte("hello"), os.ModePerm) err = os.WriteFile(filepath.Join(test2Dir, "test2.abc"), []byte("hello"), os.ModePerm)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View file

@ -28,7 +28,6 @@ import (
"encoding/hex" "encoding/hex"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -483,7 +482,7 @@ func sendFilesLoop() {
fmt.Println("Quit command received") fmt.Println("Quit command received")
return return
} }
b, err := ioutil.ReadFile(s) b, err := os.ReadFile(s)
if err != nil { if err != nil {
fmt.Printf(">>> Error: %s \n", err) fmt.Printf(">>> Error: %s \n", err)
} else { } else {
@ -513,7 +512,7 @@ func fileReaderLoop() {
fmt.Println("Quit command received") fmt.Println("Quit command received")
return return
} }
raw, err := ioutil.ReadFile(s) raw, err := os.ReadFile(s)
if err != nil { if err != nil {
fmt.Printf(">>> Error: %s \n", err) fmt.Printf(">>> Error: %s \n", err)
} else { } else {
@ -670,7 +669,7 @@ func writeMessageToFile(dir string, msg *whisper.ReceivedMessage, show bool) {
//} //}
fullpath := filepath.Join(dir, name) fullpath := filepath.Join(dir, name)
err := ioutil.WriteFile(fullpath, env.Data, 0644) err := os.WriteFile(fullpath, env.Data, 0644)
if err != nil { if err != nil {
fmt.Printf("\n%s {%x}: message received but not saved: %s\n", timestamp, address, err) fmt.Printf("\n%s {%x}: message received but not saved: %s\n", timestamp, address, err)
} else if show { } else if show {

View file

@ -22,7 +22,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "os"
"os/exec" "os/exec"
"regexp" "regexp"
"strconv" "strconv"
@ -184,7 +184,7 @@ func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, erro
func slurpFiles(files []string) (string, error) { func slurpFiles(files []string) (string, error) {
var concat bytes.Buffer var concat bytes.Buffer
for _, file := range files { for _, file := range files {
content, err := ioutil.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -19,12 +19,12 @@ package common
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
) )
// LoadJSON reads the given file and unmarshals its content. // LoadJSON reads the given file and unmarshals its content.
func LoadJSON(file string, val interface{}) error { func LoadJSON(file string, val interface{}) error {
content, err := ioutil.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
return err return err
} }

View file

@ -5,9 +5,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"time" "time"
@ -849,7 +849,7 @@ func (x *XDPoS_v1) Finalize(chain consensus.ChainReader, header *types.Header, s
if len(common.StoreRewardFolder) > 0 { if len(common.StoreRewardFolder) > 0 {
data, err := json.Marshal(rewards) data, err := json.Marshal(rewards)
if err == nil { if err == nil {
err = ioutil.WriteFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644) err = os.WriteFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644)
} }
if err != nil { if err != nil {
log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err) log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err)

View file

@ -3,8 +3,8 @@ package engine_v2
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"time" "time"
@ -385,7 +385,7 @@ func (x *XDPoS_v2) Finalize(chain consensus.ChainReader, header *types.Header, s
if len(common.StoreRewardFolder) > 0 { if len(common.StoreRewardFolder) > 0 {
data, err := json.Marshal(rewards) data, err := json.Marshal(rewards)
if err == nil { if err == nil {
err = ioutil.WriteFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644) err = os.WriteFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644)
} }
if err != nil { if err != nil {
log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err) log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err)

View file

@ -3,7 +3,6 @@ package engine_v2
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -48,7 +47,7 @@ func RandStringBytes(n int) string {
func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) { func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) {
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := ioutil.TempDir("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5)))
new := func(kd string) *keystore.KeyStore { new := func(kd string) *keystore.KeyStore {
return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP)

View file

@ -2,7 +2,7 @@ package engine_v2
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -24,7 +24,7 @@ func TestGetMasterNodes(t *testing.T) {
func TestStoreLoadSnapshot(t *testing.T) { func TestStoreLoadSnapshot(t *testing.T) {
snap := newSnapshot(1, common.Hash{0x1}, nil) snap := newSnapshot(1, common.Hash{0x1}, nil)
dir, err := ioutil.TempDir("", "snapshot-test") dir, err := os.MkdirTemp("", "snapshot-test")
if err != nil { if err != nil {
panic(fmt.Sprintf("can't create temporary directory: %v", err)) panic(fmt.Sprintf("can't create temporary directory: %v", err))
} }

View file

@ -18,7 +18,6 @@ package ethash
import ( import (
"bytes" "bytes"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"reflect" "reflect"
@ -688,7 +687,7 @@ func TestHashimoto(t *testing.T) {
// Tests that caches generated on disk may be done concurrently. // Tests that caches generated on disk may be done concurrently.
func TestConcurrentDiskCacheGeneration(t *testing.T) { func TestConcurrentDiskCacheGeneration(t *testing.T) {
// Create a temp folder to generate the caches into // Create a temp folder to generate the caches into
cachedir, err := ioutil.TempDir("", "") cachedir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("Failed to create temporary cache dir: %v", err) t.Fatalf("Failed to create temporary cache dir: %v", err)
} }

View file

@ -17,7 +17,6 @@
package ethash package ethash
import ( import (
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -46,7 +45,7 @@ func TestTestMode(t *testing.T) {
// This test checks that cache lru logic doesn't crash under load. // This test checks that cache lru logic doesn't crash under load.
// It reproduces https://github.com/XinFinOrg/XDPoSChain/issues/14943 // It reproduces https://github.com/XinFinOrg/XDPoSChain/issues/14943
func TestCacheFileEvict(t *testing.T) { func TestCacheFileEvict(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "ethash-test") tmpdir, err := os.MkdirTemp("", "ethash-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -6,7 +6,6 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -77,7 +76,7 @@ func RandStringBytes(n int) string {
func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) { func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account accounts.Account, hash []byte) ([]byte, error), error) {
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := ioutil.TempDir("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5)))
new := func(kd string) *keystore.KeyStore { new := func(kd string) *keystore.KeyStore {
return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP)

View file

@ -19,7 +19,6 @@ package console
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
@ -28,11 +27,11 @@ import (
"strings" "strings"
"syscall" "syscall"
"github.com/dop251/goja"
"github.com/XinFinOrg/XDPoSChain/internal/jsre" "github.com/XinFinOrg/XDPoSChain/internal/jsre"
"github.com/XinFinOrg/XDPoSChain/internal/jsre/deps" "github.com/XinFinOrg/XDPoSChain/internal/jsre/deps"
"github.com/XinFinOrg/XDPoSChain/internal/web3ext" "github.com/XinFinOrg/XDPoSChain/internal/web3ext"
"github.com/XinFinOrg/XDPoSChain/rpc" "github.com/XinFinOrg/XDPoSChain/rpc"
"github.com/dop251/goja"
"github.com/mattn/go-colorable" "github.com/mattn/go-colorable"
"github.com/peterh/liner" "github.com/peterh/liner"
) )
@ -137,7 +136,7 @@ func (c *Console) init(preload []string) error {
// Configure the input prompter for history and tab completion. // Configure the input prompter for history and tab completion.
if c.prompter != nil { if c.prompter != nil {
if content, err := ioutil.ReadFile(c.histPath); err != nil { if content, err := os.ReadFile(c.histPath); err != nil {
c.prompter.SetHistory(nil) c.prompter.SetHistory(nil)
} else { } else {
c.history = strings.Split(string(content), "\n") c.history = strings.Split(string(content), "\n")
@ -452,7 +451,7 @@ func (c *Console) Execute(path string) error {
// Stop cleans up the console and terminates the runtime environment. // Stop cleans up the console and terminates the runtime environment.
func (c *Console) Stop(graceful bool) error { func (c *Console) Stop(graceful bool) error {
if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil { if err := os.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil {
return err return err
} }
if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously

View file

@ -19,14 +19,14 @@ package console
import ( import (
"bytes" "bytes"
"errors" "errors"
"github.com/XinFinOrg/XDPoSChain/XDCx"
"github.com/XinFinOrg/XDPoSChain/XDCxlending"
"io/ioutil"
"os" "os"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/XDCx"
"github.com/XinFinOrg/XDPoSChain/XDCxlending"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/consensus/ethash"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
@ -86,7 +86,7 @@ type tester struct {
// Please ensure you call Close() on the returned tester to avoid leaks. // Please ensure you call Close() on the returned tester to avoid leaks.
func newTester(t *testing.T, confOverride func(*eth.Config)) *tester { func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
// Create a temporary storage for the node keys and initialize it // Create a temporary storage for the node keys and initialize it
workspace, err := ioutil.TempDir("", "console-tester-") workspace, err := os.MkdirTemp("", "console-tester-")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary keystore: %v", err) t.Fatalf("failed to create temporary keystore: %v", err)
} }

View file

@ -30,7 +30,6 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"sync" "sync"
@ -160,7 +159,7 @@ func (self *Chequebook) setBalanceFromBlockChain() {
// LoadChequebook loads a chequebook from disk (file path). // LoadChequebook loads a chequebook from disk (file path).
func LoadChequebook(path string, prvKey *ecdsa.PrivateKey, backend Backend, checkBalance bool) (self *Chequebook, err error) { func LoadChequebook(path string, prvKey *ecdsa.PrivateKey, backend Backend, checkBalance bool) (self *Chequebook, err error) {
var data []byte var data []byte
data, err = ioutil.ReadFile(path) data, err = os.ReadFile(path)
if err != nil { if err != nil {
return return
} }
@ -230,7 +229,7 @@ func (self *Chequebook) Save() (err error) {
} }
self.log.Trace("Saving chequebook to disk", self.path) self.log.Trace("Saving chequebook to disk", self.path)
return ioutil.WriteFile(self.path, data, os.ModePerm) return os.WriteFile(self.path, data, os.ModePerm)
} }
// Stop quits the autodeposit go routine to terminate // Stop quits the autodeposit go routine to terminate

View file

@ -14,6 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//go:build none
// +build none // +build none
// This program generates contract/code.go, which contains the chequebook code // This program generates contract/code.go, which contains the chequebook code
@ -22,8 +23,8 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"github.com/XinFinOrg/XDPoSChain/accounts/abi/bind" "github.com/XinFinOrg/XDPoSChain/accounts/abi/bind"
"github.com/XinFinOrg/XDPoSChain/accounts/abi/bind/backends" "github.com/XinFinOrg/XDPoSChain/accounts/abi/bind/backends"
@ -64,7 +65,7 @@ func main() {
// updated when the contract code is changed. // updated when the contract code is changed.
const ContractDeployedCode = "%#x" const ContractDeployedCode = "%#x"
`, code) `, code)
if err := ioutil.WriteFile("contract/code.go", []byte(content), 0644); err != nil { if err := os.WriteFile("contract/code.go", []byte(content), 0644); err != nil {
panic(err) panic(err)
} }
} }

View file

@ -18,12 +18,12 @@ package core
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/common/math" "github.com/XinFinOrg/XDPoSChain/common/math"
"github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/consensus/ethash"
@ -151,7 +151,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
if !disk { if !disk {
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
} else { } else {
dir, err := ioutil.TempDir("", "eth-core-bench") dir, err := os.MkdirTemp("", "eth-core-bench")
if err != nil { if err != nil {
b.Fatalf("cannot create temporary directory: %v", err) b.Fatalf("cannot create temporary directory: %v", err)
} }
@ -248,7 +248,7 @@ func makeChainForBench(db ethdb.Database, full bool, count uint64) {
func benchWriteChain(b *testing.B, full bool, count uint64) { func benchWriteChain(b *testing.B, full bool, count uint64) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
dir, err := ioutil.TempDir("", "eth-chain-bench") dir, err := os.MkdirTemp("", "eth-chain-bench")
if err != nil { if err != nil {
b.Fatalf("cannot create temporary directory: %v", err) b.Fatalf("cannot create temporary directory: %v", err)
} }
@ -263,7 +263,7 @@ func benchWriteChain(b *testing.B, full bool, count uint64) {
} }
func benchReadChain(b *testing.B, full bool, count uint64) { func benchReadChain(b *testing.B, full bool, count uint64) {
dir, err := ioutil.TempDir("", "eth-chain-bench") dir, err := os.MkdirTemp("", "eth-chain-bench")
if err != nil { if err != nil {
b.Fatalf("cannot create temporary directory: %v", err) b.Fatalf("cannot create temporary directory: %v", err)
} }

View file

@ -19,15 +19,15 @@ package core
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/consensus"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/consensus"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/state"
"github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/types"
@ -1543,7 +1543,7 @@ func testTransactionJournaling(t *testing.T, nolocals bool) {
t.Parallel() t.Parallel()
// Create a temporary file for the journal // Create a temporary file for the journal
file, err := ioutil.TempFile("", "") file, err := os.CreateTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary journal: %v", err) t.Fatalf("failed to create temporary journal: %v", err)
} }

View file

@ -20,9 +20,9 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"math/big" "math/big"
"os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/params"
@ -245,7 +245,7 @@ func TestWriteExpectedValues(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
_ = ioutil.WriteFile(fmt.Sprintf("testdata/testcases_%v.json", name), data, 0644) _ = os.WriteFile(fmt.Sprintf("testdata/testcases_%v.json", name), data, 0644)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -255,7 +255,7 @@ func TestWriteExpectedValues(t *testing.T) {
// TestJsonTestcases runs through all the testcases defined as json-files // TestJsonTestcases runs through all the testcases defined as json-files
func TestJsonTestcases(t *testing.T) { func TestJsonTestcases(t *testing.T) {
for name := range twoOpMethods { for name := range twoOpMethods {
data, err := ioutil.ReadFile(fmt.Sprintf("testdata/testcases_%v.json", name)) data, err := os.ReadFile(fmt.Sprintf("testdata/testcases_%v.json", name))
if err != nil { if err != nil {
t.Fatal("Failed to read file", err) t.Fatal("Failed to read file", err)
} }

View file

@ -4,11 +4,12 @@ import (
"crypto/rand" "crypto/rand"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/stretchr/testify/assert" "io"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestInnerProductProveLen1(t *testing.T) { func TestInnerProductProveLen1(t *testing.T) {
@ -409,7 +410,7 @@ func parseTestData(filePath string) MultiRangeProof {
defer jsonFile.Close() defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile) byteValue, _ := io.ReadAll(jsonFile)
// we initialize our Users array // we initialize our Users array
// var result map[string]interface{} // var result map[string]interface{}
@ -448,7 +449,8 @@ func parseTestData(filePath string) MultiRangeProof {
return proof return proof
} }
/** /*
*
Utils for parsing data from json Utils for parsing data from json
*/ */
func MapBigI(list []string, f func(string) *big.Int) []*big.Int { func MapBigI(list []string, f func(string) *big.Int) []*big.Int {

View file

@ -24,7 +24,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/big" "math/big"
"os" "os"
@ -175,7 +174,7 @@ func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
// restrictive permissions. The key data is saved hex-encoded. // restrictive permissions. The key data is saved hex-encoded.
func SaveECDSA(file string, key *ecdsa.PrivateKey) error { func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
k := hex.EncodeToString(FromECDSA(key)) k := hex.EncodeToString(FromECDSA(key))
return ioutil.WriteFile(file, []byte(k), 0600) return os.WriteFile(file, []byte(k), 0600)
} }
func GenerateKey() (*ecdsa.PrivateKey, error) { func GenerateKey() (*ecdsa.PrivateKey, error) {

View file

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"crypto/ecdsa" "crypto/ecdsa"
"encoding/hex" "encoding/hex"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"testing" "testing"
@ -122,7 +121,7 @@ func TestLoadECDSAFile(t *testing.T) {
} }
} }
ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600) os.WriteFile(fileName0, []byte(testPrivHex), 0600)
defer os.Remove(fileName0) defer os.Remove(fileName0)
key0, err := LoadECDSA(fileName0) key0, err := LoadECDSA(fileName0)

View file

@ -21,8 +21,8 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
@ -301,7 +301,7 @@ func (b *EthApiBackend) GetEngine() consensus.Engine {
func (s *EthApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int { func (s *EthApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
header := s.eth.blockchain.GetHeaderByHash(hash) header := s.eth.blockchain.GetHeaderByHash(hash)
if header != nil { if header != nil {
data, err := ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex())) data, err := os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
if err == nil { if err == nil {
rewards := make(map[string]map[string]map[string]*big.Int) rewards := make(map[string]map[string]map[string]*big.Int)
err = json.Unmarshal(data, &rewards) err = json.Unmarshal(data, &rewards)
@ -309,7 +309,7 @@ func (s *EthApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]
return rewards return rewards
} }
} else { } else {
data, err = ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex())) data, err = os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex()))
if err == nil { if err == nil {
rewards := make(map[string]map[string]map[string]*big.Int) rewards := make(map[string]map[string]map[string]*big.Int)
err = json.Unmarshal(data, &rewards) err = json.Unmarshal(data, &rewards)

View file

@ -21,8 +21,8 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"runtime" "runtime"
"sync" "sync"
"time" "time"
@ -393,7 +393,7 @@ func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config
// TraceBlockFromFile returns the structured logs created during the execution of // TraceBlockFromFile returns the structured logs created during the execution of
// EVM and returns them as a JSON object. // EVM and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) { func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
blob, err := ioutil.ReadFile(file) blob, err := os.ReadFile(file)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not read file: %v", err) return nil, fmt.Errorf("could not read file: %v", err)
} }

View file

@ -18,12 +18,12 @@ package filters
import ( import (
"context" "context"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/consensus/ethash"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
@ -43,7 +43,7 @@ func makeReceipt(addr common.Address) *types.Receipt {
} }
func BenchmarkFilters(b *testing.B) { func BenchmarkFilters(b *testing.B) {
dir, err := ioutil.TempDir("", "filtertest") dir, err := os.MkdirTemp("", "filtertest")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -108,7 +108,7 @@ func BenchmarkFilters(b *testing.B) {
} }
func TestFilters(t *testing.T) { func TestFilters(t *testing.T) {
dir, err := ioutil.TempDir("", "filtertest") dir, err := os.MkdirTemp("", "filtertest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

File diff suppressed because one or more lines are too long

View file

@ -20,8 +20,8 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/rand" "crypto/rand"
"encoding/json" "encoding/json"
"io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -204,7 +204,7 @@ func TestPrestateTracerCreate2(t *testing.T) {
// Iterates over all the input-output datasets in the tracer test harness and // Iterates over all the input-output datasets in the tracer test harness and
// runs the JavaScript tracers against them. // runs the JavaScript tracers against them.
func TestCallTracer(t *testing.T) { func TestCallTracer(t *testing.T) {
files, err := ioutil.ReadDir("testdata") files, err := os.ReadDir("testdata")
if err != nil { if err != nil {
t.Fatalf("failed to retrieve tracer test suite: %v", err) t.Fatalf("failed to retrieve tracer test suite: %v", err)
} }
@ -217,7 +217,7 @@ func TestCallTracer(t *testing.T) {
t.Parallel() t.Parallel()
// Call tracer test found, read if from disk // Call tracer test found, read if from disk
blob, err := ioutil.ReadFile(filepath.Join("testdata", file.Name())) blob, err := os.ReadFile(filepath.Join("testdata", file.Name()))
if err != nil { if err != nil {
t.Fatalf("failed to read testcase: %v", err) t.Fatalf("failed to read testcase: %v", err)
} }

View file

@ -21,7 +21,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@ -81,7 +80,7 @@ func RunGit(args ...string) string {
// readGitFile returns content of file in .git directory. // readGitFile returns content of file in .git directory.
func readGitFile(file string) string { func readGitFile(file string) string {
content, err := ioutil.ReadFile(path.Join(".git", file)) content, err := os.ReadFile(path.Join(".git", file))
if err != nil { if err != nil {
return "" return ""
} }
@ -114,7 +113,7 @@ func CopyFile(dst, src string, mode os.FileMode) {
// so that go commands executed by build use the same version of Go as the 'host' that runs // so that go commands executed by build use the same version of Go as the 'host' that runs
// build code. e.g. // build code. e.g.
// //
// /usr/lib/go-1.11/bin/go run build/ci.go ... // /usr/lib/go-1.11/bin/go run build/ci.go ...
// //
// runs using go 1.11 and invokes go 1.11 tools from the same GOROOT. This is also important // runs using go 1.11 and invokes go 1.11 tools from the same GOROOT. This is also important
// because runtime.Version checks on the host should match the tools that are run. // because runtime.Version checks on the host should match the tools that are run.

View file

@ -21,7 +21,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"regexp" "regexp"
@ -77,7 +76,7 @@ func (tt *TestCmd) Run(name string, args ...string) {
// InputLine writes the given text to the childs stdin. // InputLine writes the given text to the childs stdin.
// This method can also be called from an expect template, e.g.: // This method can also be called from an expect template, e.g.:
// //
// geth.expect(`Passphrase: {{.InputLine "password"}}`) // geth.expect(`Passphrase: {{.InputLine "password"}}`)
func (tt *TestCmd) InputLine(s string) string { func (tt *TestCmd) InputLine(s string) string {
io.WriteString(tt.stdin, s+"\n") io.WriteString(tt.stdin, s+"\n")
return "" return ""
@ -170,7 +169,7 @@ func (tt *TestCmd) ExpectRegexp(regex string) (*regexp.Regexp, []string) {
func (tt *TestCmd) ExpectExit() { func (tt *TestCmd) ExpectExit() {
var output []byte var output []byte
tt.withKillTimeout(func() { tt.withKillTimeout(func() {
output, _ = ioutil.ReadAll(tt.stdout) output, _ = io.ReadAll(tt.stdout)
}) })
tt.WaitExit() tt.WaitExit()
if tt.Cleanup != nil { if tt.Cleanup != nil {

View file

@ -23,7 +23,6 @@
package guide package guide
import ( import (
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
@ -37,7 +36,7 @@ import (
// Tests that the account management snippets work correctly. // Tests that the account management snippets work correctly.
func TestAccountManagement(t *testing.T) { func TestAccountManagement(t *testing.T) {
// Create a temporary folder to work with // Create a temporary folder to work with
workdir, err := ioutil.TempDir("", "") workdir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("Failed to create temporary work dir: %v", err) t.Fatalf("Failed to create temporary work dir: %v", err)
} }

File diff suppressed because one or more lines are too long

View file

@ -22,8 +22,8 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
"os"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -239,7 +239,7 @@ func (re *JSRE) Stop(waitForCallbacks bool) {
// Exec(file) loads and runs the contents of a file // Exec(file) loads and runs the contents of a file
// if a relative path is given, the jsre's assetPath is used // if a relative path is given, the jsre's assetPath is used
func (re *JSRE) Exec(file string) error { func (re *JSRE) Exec(file string) error {
code, err := ioutil.ReadFile(common.AbsolutePath(re.assetPath, file)) code, err := os.ReadFile(common.AbsolutePath(re.assetPath, file))
if err != nil { if err != nil {
return err return err
} }
@ -292,7 +292,7 @@ func (re *JSRE) Compile(filename string, src string) (err error) {
func (re *JSRE) loadScript(call Call) (goja.Value, error) { func (re *JSRE) loadScript(call Call) (goja.Value, error) {
file := call.Argument(0).ToString().String() file := call.Argument(0).ToString().String()
file = common.AbsolutePath(re.assetPath, file) file = common.AbsolutePath(re.assetPath, file)
source, err := ioutil.ReadFile(file) source, err := os.ReadFile(file)
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not read file %s: %v", file, err) return nil, fmt.Errorf("Could not read file %s: %v", file, err)
} }

View file

@ -17,7 +17,6 @@
package jsre package jsre
import ( import (
"io/ioutil"
"os" "os"
"path" "path"
"reflect" "reflect"
@ -41,12 +40,12 @@ func (no *testNativeObjectBinding) TestMethod(call goja.FunctionCall) goja.Value
} }
func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) { func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) {
dir, err := ioutil.TempDir("", "jsre-test") dir, err := os.MkdirTemp("", "jsre-test")
if err != nil { if err != nil {
t.Fatal("cannot create temporary directory:", err) t.Fatal("cannot create temporary directory:", err)
} }
if testjs != "" { if testjs != "" {
if err := ioutil.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil {
t.Fatal("cannot create test.js:", err) t.Fatal("cannot create test.js:", err)
} }
} }

View file

@ -20,8 +20,8 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
@ -227,7 +227,7 @@ func (b *LesApiBackend) GetEngine() consensus.Engine {
func (s *LesApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int { func (s *LesApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
header := s.eth.blockchain.GetHeaderByHash(hash) header := s.eth.blockchain.GetHeaderByHash(hash)
if header != nil { if header != nil {
data, err := ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex())) data, err := os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
if err == nil { if err == nil {
rewards := make(map[string]map[string]map[string]*big.Int) rewards := make(map[string]map[string]map[string]*big.Int)
err = json.Unmarshal(data, &rewards) err = json.Unmarshal(data, &rewards)
@ -235,7 +235,7 @@ func (s *LesApiBackend) GetRewardByHash(hash common.Hash) map[string]map[string]
return rewards return rewards
} }
} else { } else {
data, err = ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex())) data, err = os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex()))
if err == nil { if err == nil {
rewards := make(map[string]map[string]map[string]*big.Int) rewards := make(map[string]map[string]map[string]*big.Int)
err = json.Unmarshal(data, &rewards) err = json.Unmarshal(data, &rewards)

View file

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
) )
@ -93,7 +93,7 @@ func (self *LibratoClient) PostMetrics(batch Batch) (err error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
var body []byte var body []byte
if body, err = ioutil.ReadAll(resp.Body); err != nil { if body, err = io.ReadAll(resp.Body); err != nil {
body = []byte(fmt.Sprintf("(could not fetch response body for error: %s)", err)) body = []byte(fmt.Sprintf("(could not fetch response body for error: %s)", err))
} }
err = fmt.Errorf("Unable to post to Librato: %d %s %s", resp.StatusCode, resp.Status, string(body)) err = fmt.Errorf("Unable to post to Librato: %d %s %s", resp.StatusCode, resp.Status, string(body))

View file

@ -2,7 +2,7 @@ package metrics
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"log" "log"
"sync" "sync"
"testing" "testing"
@ -13,7 +13,7 @@ const FANOUT = 128
// Stop the compiler from complaining during debugging. // Stop the compiler from complaining during debugging.
var ( var (
_ = ioutil.Discard _ = io.Discard
_ = log.LstdFlags _ = log.LstdFlags
) )
@ -78,7 +78,7 @@ func BenchmarkMetrics(b *testing.B) {
//log.Println("done Write") //log.Println("done Write")
return return
default: default:
WriteOnce(r, ioutil.Discard) WriteOnce(r, io.Discard)
} }
} }
}() }()

View file

@ -17,7 +17,6 @@
package geth package geth
import ( import (
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -184,7 +183,7 @@ func TestAndroid(t *testing.T) {
t.Logf("initialization took %v", time.Since(start)) t.Logf("initialization took %v", time.Since(start))
} }
// Create and switch to a temporary workspace // Create and switch to a temporary workspace
workspace, err := ioutil.TempDir("", "geth-android-") workspace, err := os.MkdirTemp("", "geth-android-")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary workspace: %v", err) t.Fatalf("failed to create temporary workspace: %v", err)
} }
@ -214,14 +213,14 @@ func TestAndroid(t *testing.T) {
} }
build.CopyFile(filepath.Join("libs", "geth.aar"), "geth.aar", os.ModePerm) build.CopyFile(filepath.Join("libs", "geth.aar"), "geth.aar", os.ModePerm)
if err = ioutil.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "gethtest", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil { if err = os.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "gethtest", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil {
t.Fatalf("failed to write Android test class: %v", err) t.Fatalf("failed to write Android test class: %v", err)
} }
// Finish creating the project and run the tests via gradle // Finish creating the project and run the tests via gradle
if err = ioutil.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil { if err = os.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil {
t.Fatalf("failed to write Android manifest: %v", err) t.Fatalf("failed to write Android manifest: %v", err)
} }
if err = ioutil.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil { if err = os.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil {
t.Fatalf("failed to write gradle build file: %v", err) t.Fatalf("failed to write gradle build file: %v", err)
} }
if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil { if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil {

View file

@ -19,7 +19,6 @@ package node
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -411,7 +410,7 @@ func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
var ephemeral string var ephemeral string
if keydir == "" { if keydir == "" {
// There is no datadir. // There is no datadir.
keydir, err = ioutil.TempDir("", "go-ethereum-keystore") keydir, err = os.MkdirTemp("", "go-ethereum-keystore")
ephemeral = keydir ephemeral = keydir
} }

View file

@ -18,7 +18,6 @@ package node
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -32,7 +31,7 @@ import (
// ones or automatically generated temporary ones. // ones or automatically generated temporary ones.
func TestDatadirCreation(t *testing.T) { func TestDatadirCreation(t *testing.T) {
// Create a temporary data dir and check that it can be used by a node // Create a temporary data dir and check that it can be used by a node
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create manual data dir: %v", err) t.Fatalf("failed to create manual data dir: %v", err)
} }
@ -50,7 +49,7 @@ func TestDatadirCreation(t *testing.T) {
t.Fatalf("freshly created datadir not accessible: %v", err) t.Fatalf("freshly created datadir not accessible: %v", err)
} }
// Verify that an impossible datadir fails creation // Verify that an impossible datadir fails creation
file, err := ioutil.TempFile("", "") file, err := os.CreateTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary file: %v", err) t.Fatalf("failed to create temporary file: %v", err)
} }
@ -97,7 +96,7 @@ func TestIPCPathResolution(t *testing.T) {
// ephemeral. // ephemeral.
func TestNodeKeyPersistency(t *testing.T) { func TestNodeKeyPersistency(t *testing.T) {
// Create a temporary folder and make sure no key is present // Create a temporary folder and make sure no key is present
dir, err := ioutil.TempDir("", "node-test") dir, err := os.MkdirTemp("", "node-test")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err) t.Fatalf("failed to create temporary data directory: %v", err)
} }
@ -125,7 +124,7 @@ func TestNodeKeyPersistency(t *testing.T) {
if _, err = crypto.LoadECDSA(keyfile); err != nil { if _, err = crypto.LoadECDSA(keyfile); err != nil {
t.Fatalf("failed to load freshly persisted node key: %v", err) t.Fatalf("failed to load freshly persisted node key: %v", err)
} }
blob1, err := ioutil.ReadFile(keyfile) blob1, err := os.ReadFile(keyfile)
if err != nil { if err != nil {
t.Fatalf("failed to read freshly persisted node key: %v", err) t.Fatalf("failed to read freshly persisted node key: %v", err)
} }
@ -133,7 +132,7 @@ func TestNodeKeyPersistency(t *testing.T) {
// Configure a new node and ensure the previously persisted key is loaded // Configure a new node and ensure the previously persisted key is loaded
config = &Config{Name: "unit-test", DataDir: dir} config = &Config{Name: "unit-test", DataDir: dir}
config.NodeKey() config.NodeKey()
blob2, err := ioutil.ReadFile(filepath.Join(keyfile)) blob2, err := os.ReadFile(filepath.Join(keyfile))
if err != nil { if err != nil {
t.Fatalf("failed to read previously persisted node key: %v", err) t.Fatalf("failed to read previously persisted node key: %v", err)
} }

View file

@ -18,7 +18,6 @@ package node
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"reflect" "reflect"
"testing" "testing"
@ -77,7 +76,7 @@ func TestNodeLifeCycle(t *testing.T) {
// Tests that if the data dir is already in use, an appropriate error is returned. // Tests that if the data dir is already in use, an appropriate error is returned.
func TestNodeUsedDataDir(t *testing.T) { func TestNodeUsedDataDir(t *testing.T) {
// Create a temporary folder to use as the data directory // Create a temporary folder to use as the data directory
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err) t.Fatalf("failed to create temporary data directory: %v", err)
} }

View file

@ -18,7 +18,6 @@ package node
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -28,7 +27,7 @@ import (
// the configured service context. // the configured service context.
func TestContextDatabases(t *testing.T) { func TestContextDatabases(t *testing.T) {
// Create a temporary folder and ensure no database is contained within // Create a temporary folder and ensure no database is contained within
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err) t.Fatalf("failed to create temporary data directory: %v", err)
} }

View file

@ -18,7 +18,6 @@ package discover
import ( import (
"bytes" "bytes"
"io/ioutil"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -255,7 +254,7 @@ func TestNodeDBSeedQuery(t *testing.T) {
} }
func TestNodeDBPersistency(t *testing.T) { func TestNodeDBPersistency(t *testing.T) {
root, err := ioutil.TempDir("", "nodedb-") root, err := os.MkdirTemp("", "nodedb-")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary data folder: %v", err) t.Fatalf("failed to create temporary data folder: %v", err)
} }

View file

@ -18,7 +18,6 @@ package discv5
import ( import (
"bytes" "bytes"
"io/ioutil"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -255,7 +254,7 @@ func TestNodeDBSeedQuery(t *testing.T) {
} }
func TestNodeDBPersistency(t *testing.T) { func TestNodeDBPersistency(t *testing.T) {
root, err := ioutil.TempDir("", "nodedb-") root, err := os.MkdirTemp("", "nodedb-")
if err != nil { if err != nil {
t.Fatalf("failed to create temporary data folder: %v", err) t.Fatalf("failed to create temporary data folder: %v", err)
} }

View file

@ -21,7 +21,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"sync/atomic" "sync/atomic"
"time" "time"
@ -62,7 +61,7 @@ func (msg Msg) String() string {
// Discard reads any remaining payload data into a black hole. // Discard reads any remaining payload data into a black hole.
func (msg Msg) Discard() error { func (msg Msg) Discard() error {
_, err := io.Copy(ioutil.Discard, msg.Payload) _, err := io.Copy(io.Discard, msg.Payload)
return err return err
} }
@ -100,12 +99,11 @@ func Send(w MsgWriter, msgcode uint64, data interface{}) error {
// SendItems writes an RLP with the given code and data elements. // SendItems writes an RLP with the given code and data elements.
// For a call such as: // For a call such as:
// //
// SendItems(w, code, e1, e2, e3) // SendItems(w, code, e1, e2, e3)
// //
// the message payload will be an RLP list containing the items: // the message payload will be an RLP list containing the items:
// //
// [e1, e2, e3] // [e1, e2, e3]
//
func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error { func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error {
return Send(w, msgcode, elems) return Send(w, msgcode, elems)
} }
@ -237,7 +235,7 @@ func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
if int(msg.Size) != len(contentEnc) { if int(msg.Size) != len(contentEnc) {
return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc)) return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
} }
actualContent, err := ioutil.ReadAll(msg.Payload) actualContent, err := io.ReadAll(msg.Payload)
if err != nil { if err != nil {
return err return err
} }

View file

@ -29,7 +29,6 @@ import (
"fmt" "fmt"
"hash" "hash"
"io" "io"
"io/ioutil"
mrand "math/rand" mrand "math/rand"
"net" "net"
"sync" "sync"
@ -606,7 +605,7 @@ func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
if msg.Size > maxUint24 { if msg.Size > maxUint24 {
return errPlainMessageTooLarge return errPlainMessageTooLarge
} }
payload, _ := ioutil.ReadAll(msg.Payload) payload, _ := io.ReadAll(msg.Payload)
payload = snappy.Encode(nil, payload) payload = snappy.Encode(nil, payload)
msg.Payload = bytes.NewReader(payload) msg.Payload = bytes.NewReader(payload)
@ -700,7 +699,7 @@ func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
// if snappy is enabled, verify and decompress message // if snappy is enabled, verify and decompress message
if rw.snappy { if rw.snappy {
payload, err := ioutil.ReadAll(msg.Payload) payload, err := io.ReadAll(msg.Payload)
if err != nil { if err != nil {
return msg, err return msg, err
} }

View file

@ -22,7 +22,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"reflect" "reflect"
"strings" "strings"
@ -305,7 +304,7 @@ ba628a4ba590cb43f7848f41c4382885
if msg.Code != 8 { if msg.Code != 8 {
t.Errorf("msg code mismatch: got %d, want %d", msg.Code, 8) t.Errorf("msg code mismatch: got %d, want %d", msg.Code, 8)
} }
payload, _ := ioutil.ReadAll(msg.Payload) payload, _ := io.ReadAll(msg.Payload)
wantPayload := unhex("C401020304") wantPayload := unhex("C401020304")
if !bytes.Equal(payload, wantPayload) { if !bytes.Equal(payload, wantPayload) {
t.Errorf("msg payload mismatch:\ngot %x\nwant %x", payload, wantPayload) t.Errorf("msg payload mismatch:\ngot %x\nwant %x", payload, wantPayload)
@ -370,7 +369,7 @@ func TestRLPXFrameRW(t *testing.T) {
if msg.Code != uint64(i) { if msg.Code != uint64(i) {
t.Fatalf("msg code mismatch: got %d, want %d", msg.Code, i) t.Fatalf("msg code mismatch: got %d, want %d", msg.Code, i)
} }
payload, _ := ioutil.ReadAll(msg.Payload) payload, _ := io.ReadAll(msg.Payload)
wantPayload, _ := rlp.EncodeToBytes(wmsg) wantPayload, _ := rlp.EncodeToBytes(wmsg)
if !bytes.Equal(payload, wantPayload) { if !bytes.Equal(payload, wantPayload) {
t.Fatalf("msg payload mismatch:\ngot %x\nwant %x", payload, wantPayload) t.Fatalf("msg payload mismatch:\ngot %x\nwant %x", payload, wantPayload)

View file

@ -20,7 +20,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -141,7 +140,7 @@ const dockerImage = "p2p-node"
// when executed. // when executed.
func buildDockerImage() error { func buildDockerImage() error {
// create a directory to use as the build context // create a directory to use as the build context
dir, err := ioutil.TempDir("", "p2p-docker") dir, err := os.MkdirTemp("", "p2p-docker")
if err != nil { if err != nil {
return err return err
} }
@ -168,7 +167,7 @@ FROM ubuntu:16.04
RUN mkdir /data RUN mkdir /data
ADD self.bin /bin/p2p-node ADD self.bin /bin/p2p-node
`) `)
if err := ioutil.WriteFile(filepath.Join(dir, "Dockerfile"), dockerfile, 0644); err != nil { if err := os.WriteFile(filepath.Join(dir, "Dockerfile"), dockerfile, 0644); err != nil {
return err return err
} }

View file

@ -19,7 +19,7 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"sync/atomic" "sync/atomic"
@ -62,7 +62,7 @@ func main() {
adapter = adapters.NewSimAdapter(services) adapter = adapters.NewSimAdapter(services)
case "exec": case "exec":
tmpdir, err := ioutil.TempDir("", "p2p-example") tmpdir, err := os.MkdirTemp("", "p2p-example")
if err != nil { if err != nil {
log.Crit("error creating temp dir", "err", err) log.Crit("error creating temp dir", "err", err)
} }
@ -170,7 +170,7 @@ func (p *pingPongService) Run(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
errC <- err errC <- err
return return
} }
payload, err := ioutil.ReadAll(msg.Payload) payload, err := io.ReadAll(msg.Payload)
if err != nil { if err != nil {
errC <- err errC <- err
return return

View file

@ -23,7 +23,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@ -111,7 +110,7 @@ func (c *Client) SubscribeNetwork(events chan *Event, opts SubscribeOpts) (event
return nil, err return nil, err
} }
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
response, _ := ioutil.ReadAll(res.Body) response, _ := io.ReadAll(res.Body)
res.Body.Close() res.Body.Close()
return nil, fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response) return nil, fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response)
} }
@ -251,7 +250,7 @@ func (c *Client) Send(method, path string, in, out interface{}) error {
} }
defer res.Body.Close() defer res.Body.Close()
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
response, _ := ioutil.ReadAll(res.Body) response, _ := io.ReadAll(res.Body)
return fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response) return fmt.Errorf("unexpected HTTP status: %s: %s", res.Status, response)
} }
if out != nil { if out != nil {

View file

@ -27,7 +27,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@ -220,7 +219,7 @@ func expectMsgs(rw p2p.MsgReadWriter, exps []Expect) error {
} }
return err return err
} }
actualContent, err := ioutil.ReadAll(msg.Payload) actualContent, err := io.ReadAll(msg.Payload)
if err != nil { if err != nil {
return err return err
} }

View file

@ -21,7 +21,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/big" "math/big"
"sync" "sync"
"testing" "testing"
@ -287,7 +286,7 @@ func TestEncodeToReader(t *testing.T) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return ioutil.ReadAll(r) return io.ReadAll(r)
}) })
} }
@ -328,7 +327,7 @@ func TestEncodeToReaderReturnToPool(t *testing.T) {
go func() { go func() {
for i := 0; i < 1000; i++ { for i := 0; i < 1000; i++ {
_, r, _ := EncodeToReader("foo") _, r, _ := EncodeToReader("foo")
ioutil.ReadAll(r) io.ReadAll(r)
r.Read(buf) r.Read(buf)
r.Read(buf) r.Read(buf)
r.Read(buf) r.Read(buf)

View file

@ -23,7 +23,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"net" "net"
"net/http" "net/http"
@ -182,7 +181,7 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos
if err != nil { if err != nil {
return nil, err return nil, err
} }
req, err := http.NewRequestWithContext(ctx, "POST", hc.url, ioutil.NopCloser(bytes.NewReader(body))) req, err := http.NewRequestWithContext(ctx, "POST", hc.url, io.NopCloser(bytes.NewReader(body)))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -20,8 +20,8 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"io" "io"
"io/ioutil"
"net" "net"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@ -52,7 +52,7 @@ func TestServerRegisterName(t *testing.T) {
} }
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
files, err := ioutil.ReadDir("testdata") files, err := os.ReadDir("testdata")
if err != nil { if err != nil {
t.Fatal("where'd my testdata go?") t.Fatal("where'd my testdata go?")
} }
@ -70,7 +70,7 @@ func TestServer(t *testing.T) {
func runTestScript(t *testing.T, file string) { func runTestScript(t *testing.T, file string) {
server := newTestServer() server := newTestServer()
content, err := ioutil.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -20,7 +20,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"testing" "testing"
@ -30,7 +29,7 @@ import (
) )
func testApi(t *testing.T, f func(*Api)) { func testApi(t *testing.T, f func(*Api)) {
datadir, err := ioutil.TempDir("", "bzz-test") datadir, err := os.MkdirTemp("", "bzz-test")
if err != nil { if err != nil {
t.Fatalf("unable to create temp dir: %v", err) t.Fatalf("unable to create temp dir: %v", err)
} }

View file

@ -23,7 +23,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@ -70,7 +69,7 @@ func (c *Client) UploadRaw(r io.Reader, size int64) (string, error) {
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected HTTP status: %s", res.Status) return "", fmt.Errorf("unexpected HTTP status: %s", res.Status)
} }
data, err := ioutil.ReadAll(res.Body) data, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -401,7 +400,7 @@ func (c *Client) TarUpload(hash string, uploader Uploader) (string, error) {
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected HTTP status: %s", res.Status) return "", fmt.Errorf("unexpected HTTP status: %s", res.Status)
} }
data, err := ioutil.ReadAll(res.Body) data, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -457,7 +456,7 @@ func (c *Client) MultipartUpload(hash string, uploader Uploader) (string, error)
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected HTTP status: %s", res.Status) return "", fmt.Errorf("unexpected HTTP status: %s", res.Status)
} }
data, err := ioutil.ReadAll(res.Body) data, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -18,7 +18,7 @@ package client
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -49,7 +49,7 @@ func TestClientUploadDownloadRaw(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer res.Close() defer res.Close()
gotData, err := ioutil.ReadAll(res) gotData, err := io.ReadAll(res)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -67,7 +67,7 @@ func TestClientUploadDownloadFiles(t *testing.T) {
client := NewClient(srv.URL) client := NewClient(srv.URL)
upload := func(manifest, path string, data []byte) string { upload := func(manifest, path string, data []byte) string {
file := &File{ file := &File{
ReadCloser: ioutil.NopCloser(bytes.NewReader(data)), ReadCloser: io.NopCloser(bytes.NewReader(data)),
ManifestEntry: api.ManifestEntry{ ManifestEntry: api.ManifestEntry{
Path: path, Path: path,
ContentType: "text/plain", ContentType: "text/plain",
@ -92,7 +92,7 @@ func TestClientUploadDownloadFiles(t *testing.T) {
if file.ContentType != "text/plain" { if file.ContentType != "text/plain" {
t.Fatalf("expected downloaded file to have type %q, got %q", "text/plain", file.ContentType) t.Fatalf("expected downloaded file to have type %q, got %q", "text/plain", file.ContentType)
} }
data, err := ioutil.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -136,7 +136,7 @@ var testDirFiles = []string{
} }
func newTestDirectory(t *testing.T) string { func newTestDirectory(t *testing.T) string {
dir, err := ioutil.TempDir("", "swarm-client-test") dir, err := os.MkdirTemp("", "swarm-client-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -147,7 +147,7 @@ func newTestDirectory(t *testing.T) string {
os.RemoveAll(dir) os.RemoveAll(dir)
t.Fatalf("error creating dir for %s: %s", path, err) t.Fatalf("error creating dir for %s: %s", path, err)
} }
if err := ioutil.WriteFile(path, []byte(file), 0644); err != nil { if err := os.WriteFile(path, []byte(file), 0644); err != nil {
os.RemoveAll(dir) os.RemoveAll(dir)
t.Fatalf("error writing file %s: %s", path, err) t.Fatalf("error writing file %s: %s", path, err)
} }
@ -180,7 +180,7 @@ func TestClientUploadDownloadDirectory(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer file.Close() defer file.Close()
data, err := ioutil.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -196,7 +196,7 @@ func TestClientUploadDownloadDirectory(t *testing.T) {
checkDownloadFile("", []byte(testDirFiles[0])) checkDownloadFile("", []byte(testDirFiles[0]))
// check we can download the directory // check we can download the directory
tmp, err := ioutil.TempDir("", "swarm-client-test") tmp, err := os.MkdirTemp("", "swarm-client-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -205,7 +205,7 @@ func TestClientUploadDownloadDirectory(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, file := range testDirFiles { for _, file := range testDirFiles {
data, err := ioutil.ReadFile(filepath.Join(tmp, file)) data, err := os.ReadFile(filepath.Join(tmp, file))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -283,7 +283,7 @@ func TestClientMultipartUpload(t *testing.T) {
uploader := UploaderFunc(func(upload UploadFn) error { uploader := UploaderFunc(func(upload UploadFn) error {
for _, name := range testDirFiles { for _, name := range testDirFiles {
file := &File{ file := &File{
ReadCloser: ioutil.NopCloser(bytes.NewReader(data)), ReadCloser: io.NopCloser(bytes.NewReader(data)),
ManifestEntry: api.ManifestEntry{ ManifestEntry: api.ManifestEntry{
Path: name, Path: name,
ContentType: "text/plain", ContentType: "text/plain",
@ -311,7 +311,7 @@ func TestClientMultipartUpload(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer file.Close() defer file.Close()
gotData, err := ioutil.ReadAll(file) gotData, err := io.ReadAll(file)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -18,7 +18,6 @@ package api
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
@ -28,7 +27,7 @@ import (
"github.com/XinFinOrg/XDPoSChain/swarm/storage" "github.com/XinFinOrg/XDPoSChain/swarm/storage"
) )
var testDownloadDir, _ = ioutil.TempDir(os.TempDir(), "bzz-test") var testDownloadDir, _ = os.MkdirTemp(os.TempDir(), "bzz-test")
func testFileSystem(t *testing.T, f func(*FileSystem)) { func testFileSystem(t *testing.T, f func(*FileSystem)) {
testApi(t, func(api *Api) { testApi(t, func(api *Api) {
@ -38,7 +37,7 @@ func testFileSystem(t *testing.T, f func(*FileSystem)) {
func readPath(t *testing.T, parts ...string) string { func readPath(t *testing.T, parts ...string) string {
file := filepath.Join(parts...) file := filepath.Join(parts...)
content, err := ioutil.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
t.Fatalf("unexpected error reading '%v': %v", file, err) t.Fatalf("unexpected error reading '%v': %v", file, err)
@ -100,7 +99,7 @@ func TestApiDirUploadModify(t *testing.T) {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
return return
} }
index, err := ioutil.ReadFile(filepath.Join("testdata", "test0", "index.html")) index, err := os.ReadFile(filepath.Join("testdata", "test0", "index.html"))
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
return return

View file

@ -18,7 +18,7 @@ package http_test
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -43,7 +43,7 @@ func TestError(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if resp.StatusCode != 400 && !strings.Contains(string(respbody), "Invalid URI &#34;/this_should_fail_as_no_bzz_protocol_present&#34;: unknown scheme") { if resp.StatusCode != 400 && !strings.Contains(string(respbody), "Invalid URI &#34;/this_should_fail_as_no_bzz_protocol_present&#34;: unknown scheme") {
t.Fatalf("Response body does not match, expected: %v, to contain: %v; received code %d, expected code: %d", string(respbody), "Invalid bzz URI: unknown scheme", 400, resp.StatusCode) t.Fatalf("Response body does not match, expected: %v, to contain: %v; received code %d, expected code: %d", string(respbody), "Invalid bzz URI: unknown scheme", 400, resp.StatusCode)
@ -69,7 +69,7 @@ func Test404Page(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if resp.StatusCode != 404 || !strings.Contains(string(respbody), "404") { if resp.StatusCode != 404 || !strings.Contains(string(respbody), "404") {
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode) t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
@ -95,7 +95,7 @@ func Test500Page(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if resp.StatusCode != 404 { if resp.StatusCode != 404 {
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode) t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
@ -120,7 +120,7 @@ func Test500PageWith0xHashPrefix(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if resp.StatusCode != 404 { if resp.StatusCode != 404 {
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode) t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)
@ -155,7 +155,7 @@ func TestJsonResponse(t *testing.T) {
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if resp.StatusCode != 404 { if resp.StatusCode != 404 {
t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode) t.Fatalf("Invalid Status Code received, expected 404, got %d", resp.StatusCode)

View file

@ -17,7 +17,7 @@
package http package http
import ( import (
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -57,7 +57,7 @@ func TestRoundTripper(t *testing.T) {
} }
}() }()
content, err := ioutil.ReadAll(resp.Body) content, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Errorf("expected no error, got %v", err) t.Errorf("expected no error, got %v", err)
return return

View file

@ -25,7 +25,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@ -43,7 +42,7 @@ import (
"github.com/rs/cors" "github.com/rs/cors"
) )
//setup metrics // setup metrics
var ( var (
postRawCount = metrics.NewRegisteredCounter("api.http.post.raw.count", nil) postRawCount = metrics.NewRegisteredCounter("api.http.post.raw.count", nil)
postRawFail = metrics.NewRegisteredCounter("api.http.post.raw.fail", nil) postRawFail = metrics.NewRegisteredCounter("api.http.post.raw.fail", nil)
@ -247,7 +246,7 @@ func (s *Server) handleMultipartUpload(req *Request, boundary string, mw *api.Ma
reader = part reader = part
} else { } else {
// copy the part to a tmp file to get its size // copy the part to a tmp file to get its size
tmp, err := ioutil.TempFile("", "swarm-multipart") tmp, err := os.CreateTemp("", "swarm-multipart")
if err != nil { if err != nil {
return err return err
} }
@ -327,10 +326,10 @@ func (s *Server) HandleDelete(w http.ResponseWriter, r *Request) {
} }
// HandleGet handles a GET request to // HandleGet handles a GET request to
// - bzz-raw://<key> and responds with the raw content stored at the // - bzz-raw://<key> and responds with the raw content stored at the
// given storage key // given storage key
// - bzz-hash://<key> and responds with the hash of the content stored // - bzz-hash://<key> and responds with the hash of the content stored
// at the given storage key as a text/plain response // at the given storage key as a text/plain response
func (s *Server) HandleGet(w http.ResponseWriter, r *Request) { func (s *Server) HandleGet(w http.ResponseWriter, r *Request) {
getCount.Inc(1) getCount.Inc(1)
key, err := s.api.Resolve(r.uri) key, err := s.api.Resolve(r.uri)

View file

@ -20,7 +20,7 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"sync" "sync"
@ -88,7 +88,7 @@ func TestBzzGetPath(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if string(respbody) != testmanifest[v] { if string(respbody) != testmanifest[v] {
isexpectedfailrequest := false isexpectedfailrequest := false
@ -117,7 +117,7 @@ func TestBzzGetPath(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("Read request body: %v", err) t.Fatalf("Read request body: %v", err)
} }
@ -174,7 +174,7 @@ func TestBzzGetPath(t *testing.T) {
t.Fatalf("HTTP request: %v", err) t.Fatalf("HTTP request: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body) respbody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("Read response body: %v", err) t.Fatalf("Read response body: %v", err)
} }
@ -204,7 +204,7 @@ func TestBzzGetPath(t *testing.T) {
t.Fatalf("HTTP request: %v", err) t.Fatalf("HTTP request: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body) respbody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("Read response body: %v", err) t.Fatalf("Read response body: %v", err)
} }
@ -250,7 +250,7 @@ func TestBzzGetPath(t *testing.T) {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("ReadAll failed: %v", err) t.Fatalf("ReadAll failed: %v", err)
} }
@ -272,7 +272,7 @@ func TestBzzRootRedirect(t *testing.T) {
client := swarm.NewClient(srv.URL) client := swarm.NewClient(srv.URL)
data := []byte("data") data := []byte("data")
file := &swarm.File{ file := &swarm.File{
ReadCloser: ioutil.NopCloser(bytes.NewReader(data)), ReadCloser: io.NopCloser(bytes.NewReader(data)),
ManifestEntry: api.ManifestEntry{ ManifestEntry: api.ManifestEntry{
Path: "", Path: "",
ContentType: "text/plain", ContentType: "text/plain",
@ -310,7 +310,7 @@ func TestBzzRootRedirect(t *testing.T) {
if !redirected { if !redirected {
t.Fatal("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't") t.Fatal("expected GET /bzz:/<hash> to redirect to /bzz:/<hash>/ but it didn't")
} }
gotData, err := ioutil.ReadAll(res.Body) gotData, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -14,6 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//go:build linux || darwin || freebsd
// +build linux darwin freebsd // +build linux darwin freebsd
package fuse package fuse
@ -22,7 +23,6 @@ import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -136,7 +136,7 @@ func compareGeneratedFileWithFileInMount(t *testing.T, files map[string]fileInfo
t.Fatalf("file %v Permission mismatch source (-rwx------) vs destination(%v)", fname, dfinfo.Mode().Perm()) t.Fatalf("file %v Permission mismatch source (-rwx------) vs destination(%v)", fname, dfinfo.Mode().Perm())
} }
fileContents, err := ioutil.ReadFile(filepath.Join(mountDir, fname)) fileContents, err := os.ReadFile(filepath.Join(mountDir, fname))
if err != nil { if err != nil {
t.Fatalf("Could not readfile %v : %v", fname, err) t.Fatalf("Could not readfile %v : %v", fname, err)
} }
@ -195,8 +195,8 @@ type testAPI struct {
func (ta *testAPI) mountListAndUnmount(t *testing.T) { func (ta *testAPI) mountListAndUnmount(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "fuse-source") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "fuse-source")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "fuse-dest") testMountDir, _ := os.MkdirTemp(os.TempDir(), "fuse-dest")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["2.txt"] = fileInfo{0711, 333, 444, getRandomBtes(10)} files["2.txt"] = fileInfo{0711, 333, 444, getRandomBtes(10)}
@ -233,44 +233,44 @@ func (ta *testAPI) mountListAndUnmount(t *testing.T) {
func (ta *testAPI) maxMounts(t *testing.T) { func (ta *testAPI) maxMounts(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir1, _ := ioutil.TempDir(os.TempDir(), "max-upload1") uploadDir1, _ := os.MkdirTemp(os.TempDir(), "max-upload1")
bzzHash1 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir1) bzzHash1 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir1)
mount1, _ := ioutil.TempDir(os.TempDir(), "max-mount1") mount1, _ := os.MkdirTemp(os.TempDir(), "max-mount1")
swarmfs1 := mountDir(t, ta.api, files, bzzHash1, mount1) swarmfs1 := mountDir(t, ta.api, files, bzzHash1, mount1)
defer swarmfs1.Stop() defer swarmfs1.Stop()
files["2.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["2.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir2, _ := ioutil.TempDir(os.TempDir(), "max-upload2") uploadDir2, _ := os.MkdirTemp(os.TempDir(), "max-upload2")
bzzHash2 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir2) bzzHash2 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir2)
mount2, _ := ioutil.TempDir(os.TempDir(), "max-mount2") mount2, _ := os.MkdirTemp(os.TempDir(), "max-mount2")
swarmfs2 := mountDir(t, ta.api, files, bzzHash2, mount2) swarmfs2 := mountDir(t, ta.api, files, bzzHash2, mount2)
defer swarmfs2.Stop() defer swarmfs2.Stop()
files["3.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["3.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir3, _ := ioutil.TempDir(os.TempDir(), "max-upload3") uploadDir3, _ := os.MkdirTemp(os.TempDir(), "max-upload3")
bzzHash3 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir3) bzzHash3 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir3)
mount3, _ := ioutil.TempDir(os.TempDir(), "max-mount3") mount3, _ := os.MkdirTemp(os.TempDir(), "max-mount3")
swarmfs3 := mountDir(t, ta.api, files, bzzHash3, mount3) swarmfs3 := mountDir(t, ta.api, files, bzzHash3, mount3)
defer swarmfs3.Stop() defer swarmfs3.Stop()
files["4.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["4.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir4, _ := ioutil.TempDir(os.TempDir(), "max-upload4") uploadDir4, _ := os.MkdirTemp(os.TempDir(), "max-upload4")
bzzHash4 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir4) bzzHash4 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir4)
mount4, _ := ioutil.TempDir(os.TempDir(), "max-mount4") mount4, _ := os.MkdirTemp(os.TempDir(), "max-mount4")
swarmfs4 := mountDir(t, ta.api, files, bzzHash4, mount4) swarmfs4 := mountDir(t, ta.api, files, bzzHash4, mount4)
defer swarmfs4.Stop() defer swarmfs4.Stop()
files["5.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["5.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir5, _ := ioutil.TempDir(os.TempDir(), "max-upload5") uploadDir5, _ := os.MkdirTemp(os.TempDir(), "max-upload5")
bzzHash5 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir5) bzzHash5 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir5)
mount5, _ := ioutil.TempDir(os.TempDir(), "max-mount5") mount5, _ := os.MkdirTemp(os.TempDir(), "max-mount5")
swarmfs5 := mountDir(t, ta.api, files, bzzHash5, mount5) swarmfs5 := mountDir(t, ta.api, files, bzzHash5, mount5)
defer swarmfs5.Stop() defer swarmfs5.Stop()
files["6.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["6.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir6, _ := ioutil.TempDir(os.TempDir(), "max-upload6") uploadDir6, _ := os.MkdirTemp(os.TempDir(), "max-upload6")
bzzHash6 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir6) bzzHash6 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir6)
mount6, _ := ioutil.TempDir(os.TempDir(), "max-mount6") mount6, _ := os.MkdirTemp(os.TempDir(), "max-mount6")
os.RemoveAll(mount6) os.RemoveAll(mount6)
os.MkdirAll(mount6, 0777) os.MkdirAll(mount6, 0777)
@ -284,15 +284,15 @@ func (ta *testAPI) maxMounts(t *testing.T) {
func (ta *testAPI) remount(t *testing.T) { func (ta *testAPI) remount(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
uploadDir1, _ := ioutil.TempDir(os.TempDir(), "re-upload1") uploadDir1, _ := os.MkdirTemp(os.TempDir(), "re-upload1")
bzzHash1 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir1) bzzHash1 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir1)
testMountDir1, _ := ioutil.TempDir(os.TempDir(), "re-mount1") testMountDir1, _ := os.MkdirTemp(os.TempDir(), "re-mount1")
swarmfs := mountDir(t, ta.api, files, bzzHash1, testMountDir1) swarmfs := mountDir(t, ta.api, files, bzzHash1, testMountDir1)
defer swarmfs.Stop() defer swarmfs.Stop()
uploadDir2, _ := ioutil.TempDir(os.TempDir(), "re-upload2") uploadDir2, _ := os.MkdirTemp(os.TempDir(), "re-upload2")
bzzHash2 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir2) bzzHash2 := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir2)
testMountDir2, _ := ioutil.TempDir(os.TempDir(), "re-mount2") testMountDir2, _ := os.MkdirTemp(os.TempDir(), "re-mount2")
// try mounting the same hash second time // try mounting the same hash second time
os.RemoveAll(testMountDir2) os.RemoveAll(testMountDir2)
@ -317,8 +317,8 @@ func (ta *testAPI) remount(t *testing.T) {
func (ta *testAPI) unmount(t *testing.T) { func (ta *testAPI) unmount(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
uploadDir, _ := ioutil.TempDir(os.TempDir(), "ex-upload") uploadDir, _ := os.MkdirTemp(os.TempDir(), "ex-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "ex-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "ex-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir) bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, uploadDir)
@ -338,8 +338,8 @@ func (ta *testAPI) unmount(t *testing.T) {
func (ta *testAPI) unmountWhenResourceBusy(t *testing.T) { func (ta *testAPI) unmountWhenResourceBusy(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "ex-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "ex-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "ex-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "ex-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir) bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir)
@ -367,8 +367,8 @@ func (ta *testAPI) unmountWhenResourceBusy(t *testing.T) {
func (ta *testAPI) seekInMultiChunkFile(t *testing.T) { func (ta *testAPI) seekInMultiChunkFile(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "seek-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "seek-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "seek-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "seek-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10240)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10240)}
bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir) bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir)
@ -394,8 +394,8 @@ func (ta *testAPI) seekInMultiChunkFile(t *testing.T) {
func (ta *testAPI) createNewFile(t *testing.T) { func (ta *testAPI) createNewFile(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "create-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "create-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "create-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "create-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -431,8 +431,8 @@ func (ta *testAPI) createNewFile(t *testing.T) {
func (ta *testAPI) createNewFileInsideDirectory(t *testing.T) { func (ta *testAPI) createNewFileInsideDirectory(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "createinsidedir-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "createinsidedir-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "createinsidedir-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "createinsidedir-mount")
files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir) bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir)
@ -467,8 +467,8 @@ func (ta *testAPI) createNewFileInsideDirectory(t *testing.T) {
func (ta *testAPI) createNewFileInsideNewDirectory(t *testing.T) { func (ta *testAPI) createNewFileInsideNewDirectory(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "createinsidenewdir-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "createinsidenewdir-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "createinsidenewdir-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "createinsidenewdir-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir) bzzHash := createTestFilesAndUploadToSwarm(t, ta.api, files, testUploadDir)
@ -504,8 +504,8 @@ func (ta *testAPI) createNewFileInsideNewDirectory(t *testing.T) {
func (ta *testAPI) removeExistingFile(t *testing.T) { func (ta *testAPI) removeExistingFile(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "remove-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "remove-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "remove-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "remove-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -532,8 +532,8 @@ func (ta *testAPI) removeExistingFile(t *testing.T) {
func (ta *testAPI) removeExistingFileInsideDir(t *testing.T) { func (ta *testAPI) removeExistingFileInsideDir(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "remove-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "remove-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "remove-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "remove-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["one/five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["one/five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -561,8 +561,8 @@ func (ta *testAPI) removeExistingFileInsideDir(t *testing.T) {
func (ta *testAPI) removeNewlyAddedFile(t *testing.T) { func (ta *testAPI) removeNewlyAddedFile(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "removenew-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "removenew-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "removenew-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "removenew-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -605,8 +605,8 @@ func (ta *testAPI) removeNewlyAddedFile(t *testing.T) {
func (ta *testAPI) addNewFileAndModifyContents(t *testing.T) { func (ta *testAPI) addNewFileAndModifyContents(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "modifyfile-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "modifyfile-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "modifyfile-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "modifyfile-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -675,8 +675,8 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T) {
func (ta *testAPI) removeEmptyDir(t *testing.T) { func (ta *testAPI) removeEmptyDir(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "rmdir-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "rmdir-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "rmdir-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "rmdir-mount")
files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -699,8 +699,8 @@ func (ta *testAPI) removeEmptyDir(t *testing.T) {
func (ta *testAPI) removeDirWhichHasFiles(t *testing.T) { func (ta *testAPI) removeDirWhichHasFiles(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "rmdir-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "rmdir-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "rmdir-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "rmdir-mount")
files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["two/five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["two/five.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -728,8 +728,8 @@ func (ta *testAPI) removeDirWhichHasFiles(t *testing.T) {
func (ta *testAPI) removeDirWhichHasSubDirs(t *testing.T) { func (ta *testAPI) removeDirWhichHasSubDirs(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "rmsubdir-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "rmsubdir-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "rmsubdir-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "rmsubdir-mount")
files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["one/1.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
files["two/three/2.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)} files["two/three/2.txt"] = fileInfo{0700, 333, 444, getRandomBtes(10)}
@ -764,8 +764,8 @@ func (ta *testAPI) removeDirWhichHasSubDirs(t *testing.T) {
func (ta *testAPI) appendFileContentsToEnd(t *testing.T) { func (ta *testAPI) appendFileContentsToEnd(t *testing.T) {
files := make(map[string]fileInfo) files := make(map[string]fileInfo)
testUploadDir, _ := ioutil.TempDir(os.TempDir(), "appendlargefile-upload") testUploadDir, _ := os.MkdirTemp(os.TempDir(), "appendlargefile-upload")
testMountDir, _ := ioutil.TempDir(os.TempDir(), "appendlargefile-mount") testMountDir, _ := os.MkdirTemp(os.TempDir(), "appendlargefile-mount")
line1 := make([]byte, 10) line1 := make([]byte, 10)
rand.Read(line1) rand.Read(line1)
@ -802,7 +802,7 @@ func (ta *testAPI) appendFileContentsToEnd(t *testing.T) {
} }
func TestFUSE(t *testing.T) { func TestFUSE(t *testing.T) {
datadir, err := ioutil.TempDir("", "fuse") datadir, err := os.MkdirTemp("", "fuse")
if err != nil { if err != nil {
t.Fatalf("unable to create temp dir: %v", err) t.Fatalf("unable to create temp dir: %v", err)
} }

View file

@ -19,7 +19,6 @@ package kademlia
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"sync" "sync"
"time" "time"
@ -165,7 +164,6 @@ offline past peer)
|| (proxBin(a) < proxBin(b) && |proxBin(a)| == |proxBin(b)|) || (proxBin(a) < proxBin(b) && |proxBin(a)| == |proxBin(b)|)
|| (proxBin(a) == proxBin(b) && lastChecked(a) < lastChecked(b)) || (proxBin(a) == proxBin(b) && lastChecked(a) < lastChecked(b))
The second argument returned names the first missing slot found The second argument returned names the first missing slot found
*/ */
func (self *KadDb) findBest(maxBinSize int, binSize func(int) int) (node *NodeRecord, need bool, proxLimit int) { func (self *KadDb) findBest(maxBinSize int, binSize func(int) int) (node *NodeRecord, need bool, proxLimit int) {
@ -292,7 +290,7 @@ func (self *KadDb) save(path string, cb func(*NodeRecord, Node)) error {
if err != nil { if err != nil {
return err return err
} }
err = ioutil.WriteFile(path, data, os.ModePerm) err = os.WriteFile(path, data, os.ModePerm)
if err != nil { if err != nil {
log.Warn(fmt.Sprintf("unable to save kaddb with %v nodes to %v: %v", n, path, err)) log.Warn(fmt.Sprintf("unable to save kaddb with %v nodes to %v: %v", n, path, err))
} else { } else {
@ -307,7 +305,7 @@ func (self *KadDb) load(path string, cb func(*NodeRecord, Node) error) (err erro
self.lock.Lock() self.lock.Lock()
var data []byte var data []byte
data, err = ioutil.ReadFile(path) data, err = os.ReadFile(path)
if err != nil { if err != nil {
return return
} }

Some files were not shown because too many files have changed in this diff Show more