github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/abci/example/kvstore/helpers.go (about)

     1  package kvstore
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/tendermint/tendermint/abci/types"
     8  
     9  	ocabci "github.com/line/ostracon/abci/types"
    10  	"github.com/line/ostracon/crypto"
    11  	"github.com/line/ostracon/crypto/ed25519"
    12  	tmjson "github.com/line/ostracon/libs/json"
    13  	tmos "github.com/line/ostracon/libs/os"
    14  	tmrand "github.com/line/ostracon/libs/rand"
    15  	"github.com/line/ostracon/privval"
    16  )
    17  
    18  // LoadPrivValidatorKeyFile Load private key for use in an example or test.
    19  func LoadPrivValidatorKeyFile(keyFilePath string) (*privval.FilePVKey, error) {
    20  	if !tmos.FileExists(keyFilePath) {
    21  		return nil, fmt.Errorf("private validator file %s does not exist", keyFilePath)
    22  	}
    23  	keyJSONBytes, _ := os.ReadFile(keyFilePath)
    24  	pvKey := privval.FilePVKey{}
    25  	err := tmjson.Unmarshal(keyJSONBytes, &pvKey)
    26  	if err != nil {
    27  		return nil, fmt.Errorf("error reading PrivValidator key from %v: %v", keyFilePath, err)
    28  	}
    29  	return &pvKey, nil
    30  }
    31  
    32  // GenDefaultPrivKey Generates a default private key for use in an example or test.
    33  func GenDefaultPrivKey() crypto.PrivKey {
    34  	return ed25519.GenPrivKey()
    35  }
    36  
    37  // RandVal creates one random validator, with a key derived
    38  // from the input value
    39  func RandVal(i int) types.ValidatorUpdate {
    40  	pk := GenDefaultPrivKey().PubKey()
    41  	power := tmrand.Uint16() + 1
    42  	v := ocabci.NewValidatorUpdate(pk, int64(power))
    43  	return v
    44  }
    45  
    46  // RandVals returns a list of cnt validators for initializing
    47  // the application. Note that the keys are deterministically
    48  // derived from the index in the array, while the power is
    49  // random (Change this if not desired)
    50  func RandVals(cnt int) []types.ValidatorUpdate {
    51  	res := make([]types.ValidatorUpdate, cnt)
    52  	for i := 0; i < cnt; i++ {
    53  		res[i] = RandVal(i)
    54  	}
    55  	return res
    56  }
    57  
    58  // InitKVStore initializes the kvstore app with some data,
    59  // which allows tests to pass and is fine as long as you
    60  // don't make any tx that modify the validator state
    61  func InitKVStore(app *PersistentKVStoreApplication) {
    62  	app.InitChain(types.RequestInitChain{
    63  		Validators: RandVals(1),
    64  	})
    65  }