code.vegaprotocol.io/vega@v0.79.0/vegatools/checktx/file.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package checktx
    17  
    18  import (
    19  	"encoding/base64"
    20  	"fmt"
    21  	"os"
    22  	"path/filepath"
    23  	"strings"
    24  )
    25  
    26  func GetFilesInDirectory(directory string) ([]string, error) {
    27  	files, err := os.Open(directory)
    28  	if err != nil {
    29  		return nil, fmt.Errorf("error occurred when attempting to open the given directory '%s'. \nerr: %w", directory, err)
    30  	}
    31  	defer func(files *os.File) {
    32  		err := files.Close()
    33  		if err != nil {
    34  			panic(err)
    35  		}
    36  	}(files)
    37  
    38  	fileInfo, err := files.Readdir(-1)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("an error occurred when attempting to read files in the given directory. \nerr: %w", err)
    41  	}
    42  
    43  	transactionFiles := make([]string, 0, len(fileInfo))
    44  	for _, info := range fileInfo {
    45  		dir := filepath.Join(directory, info.Name())
    46  		transactionFiles = append(transactionFiles, dir)
    47  	}
    48  
    49  	return transactionFiles, nil
    50  }
    51  
    52  func GetEncodedTransactionFromFile(filePath string) (string, error) {
    53  	fileContents, err := os.ReadFile(filePath)
    54  	if err != nil {
    55  		return "", fmt.Errorf("error reading file at %s. \nerr: %w", filePath, err)
    56  	}
    57  
    58  	_, err = base64.StdEncoding.DecodeString(string(fileContents))
    59  	if err != nil {
    60  		return "", fmt.Errorf("error occurred when attempting to decode transaction data in %s, is there  definitely base64 encoded data in your file?\nerr: %v", filePath, err)
    61  	}
    62  
    63  	data := strings.TrimSpace(string(fileContents))
    64  	return data, nil
    65  }