Skip to content

Commit

Permalink
fix example
Browse files Browse the repository at this point in the history
  • Loading branch information
sukantoraymond committed Aug 20, 2024
1 parent bf6aa31 commit e258762
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 56 deletions.
2 changes: 1 addition & 1 deletion cloud/gcp/gcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ func (c *GcpCloud) SetupInstances(
}
instances := make([]*compute.Instance, numNodes)
instancesChan := make(chan *compute.Instance, numNodes)
sshKey := fmt.Sprintf("%s:%s", constants.AnsibleSSHUser, strings.TrimSuffix(sshPublicKey, "\n"))
sshKey := fmt.Sprintf("%s:%s", constants.RemoteHostUser, strings.TrimSuffix(sshPublicKey, "\n"))
automaticRestart := true

instancePrefix := utils.RandomString(5)
Expand Down
4 changes: 2 additions & 2 deletions constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const (
SSHFileOpsTimeout = 100 * time.Second
SSHPOSTTimeout = 10 * time.Second
SSHScriptTimeout = 2 * time.Minute
AnsibleSSHUser = "ubuntu"
RemoteHostUser = "ubuntu"

// node
CloudNodeCLIConfigBasePath = "/home/ubuntu/.avalanche-cli/"
Expand All @@ -52,7 +52,7 @@ const (
CloudNodeConfigPath = "/home/ubuntu/.avalanchego/configs/"
ServicesDir = "services"
DashboardsDir = "dashboards"

LocalTmpDir = ".avalanche-tooling-sdk-go"
// services
ServiceAvalanchego = "avalanchego"
ServicePromtail = "promtail"
Expand Down
116 changes: 85 additions & 31 deletions node/add_validator_primary.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ package node

import (
"fmt"
"github.com/ava-labs/avalanche-tooling-sdk-go/subnet"
"os"
"os/user"
"path/filepath"
"time"

"github.com/ava-labs/avalanche-tooling-sdk-go/constants"
"github.com/ava-labs/avalanche-tooling-sdk-go/subnet"

"github.com/ava-labs/avalanche-tooling-sdk-go/avalanche"
"github.com/ava-labs/avalanche-tooling-sdk-go/utils"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
Expand All @@ -27,37 +31,22 @@ type PrimaryNetworkValidatorParams struct {
// NodeID is the unique identifier of the node to be added as a validator on the Primary Network.
NodeID ids.NodeID

// Duration is how long the node will be staking the Primary Network
// Duration has to be greater than or equal to minimum duration for the specified network
// (Fuji / Mainnet)
Duration time.Duration

Weight uint64
// StakeAmount is the amount of Avalanche tokens (AVAX) to stake in this validator
// StakeAmount is in the amount of nAVAX
// StakeAmount has to be greater than or equal to minimum stake required for the specified network
StakeAmount uint64

// DelegationFee is the percent fee this validator will charge when others delegate stake to it
// When DelegationFee is not set, the minimum delegation fee for the specified network will be set
// For more information on delegation fee, please head to https://docs.avax.network/nodes/validate/node-validator#delegation-fee-rate
DelegationFee uint32
}

func GetMinStakingAmount(network avalanche.Network) (uint64, error) {
pClient := platformvm.NewClient(network.Endpoint)
ctx, cancel := utils.GetAPIContext()
defer cancel()
minValStake, _, err := pClient.GetMinStake(ctx, ids.Empty)
if err != nil {
return 0, err
}
return minValStake, nil
}

func (h *Node) SetNodeBLSKey(signingKeyPath string) error {
blsKeyBytes, err := os.ReadFile(signingKeyPath)
if err != nil {
return err
}
blsSk, err := bls.SecretKeyFromBytes(blsKeyBytes)
if err != nil {
return err
}
h.BlsSecretKey = blsSk
return nil
}

// ValidatePrimaryNetwork adds node as primary network validator.
// It adds the node in the specified network (Fuji / Mainnet / Devnet)
// and uses the wallet provided in the argument to pay for the transaction fee
Expand All @@ -69,19 +58,27 @@ func (h *Node) ValidatePrimaryNetwork(
if validator.NodeID == ids.EmptyNodeID {
return ids.Empty, subnet.ErrEmptyValidatorNodeID
}

if validator.Duration == 0 {
return ids.Empty, subnet.ErrEmptyValidatorDuration
}

minValStake, err := GetMinStakingAmount(network)
if err != nil {
return ids.Empty, err
}

if validator.Weight < minValStake {
return ids.Empty, fmt.Errorf("invalid weight, must be greater than or equal to %d: %d", minValStake, validator.Weight)
if validator.StakeAmount < minValStake {
return ids.Empty, fmt.Errorf("invalid weight, must be greater than or equal to %d: %d", minValStake, validator.StakeAmount)
}

delegationFee := network.GenesisParams().MinDelegationFee
if validator.DelegationFee == 0 {
validator.DelegationFee = network.GenesisParams().MinDelegationFee
}

if err = h.HandleBLSKey(); err != nil {
return ids.Empty, fmt.Errorf("unable to set BLS key of node due to %w", err)
}

wallet.SetSubnetAuthMultisig([]ids.ShortID{})

Expand All @@ -103,15 +100,15 @@ func (h *Node) ValidatePrimaryNetwork(
Validator: txs.Validator{
NodeID: nodeID,
End: uint64(time.Now().Add(validator.Duration).Unix()),
Wght: validator.Weight,
Wght: validator.StakeAmount,
},
Subnet: ids.Empty,
},
proofOfPossession,
wallet.P().Builder().Context().AVAXAssetID,
owner,
owner,
delegationFee,
validator.DelegationFee,
)
if err != nil {
return ids.Empty, fmt.Errorf("error building tx: %w", err)
Expand Down Expand Up @@ -140,3 +137,60 @@ func (h *Node) ValidatePrimaryNetwork(

return tx.ID(), nil
}

func GetMinStakingAmount(network avalanche.Network) (uint64, error) {
pClient := platformvm.NewClient(network.Endpoint)
ctx, cancel := utils.GetAPIContext()
defer cancel()
minValStake, _, err := pClient.GetMinStake(ctx, ids.Empty)
if err != nil {
return 0, err
}
return minValStake, nil
}

func (h *Node) SetNodeBLSKey(signingKeyPath string) error {
blsKeyBytes, err := os.ReadFile(signingKeyPath)
if err != nil {
return err
}
blsSk, err := bls.SecretKeyFromBytes(blsKeyBytes)
if err != nil {
return err
}
h.BlsSecretKey = blsSk
return nil
}

func RemoveTmpSDKDir() error {
usr, err := user.Current()
if err != nil {
return fmt.Errorf("unable to get system user %s", err)

Check failure on line 168 in node/add_validator_primary.go

View workflow job for this annotation

GitHub Actions / Lint

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}
return os.RemoveAll(filepath.Join(usr.HomeDir, constants.LocalTmpDir))
}

func (h *Node) GetBLSKeyFromRemoteHost() error {
usr, err := user.Current()
if err != nil {
return fmt.Errorf("unable to get system user %s", err)

Check failure on line 176 in node/add_validator_primary.go

View workflow job for this annotation

GitHub Actions / Lint

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}
filePath := filepath.Join(constants.CloudNodeStakingPath, constants.BLSKeyFileName)
localFilePath := filepath.Join(usr.HomeDir, constants.LocalTmpDir, h.NodeID, constants.BLSKeyFileName)
return h.Download(filePath, localFilePath, constants.SSHFileOpsTimeout)
}

// HandleBLSKey gets BLS information from remote host and sets the BlsSecretKey value in Node object
func (h *Node) HandleBLSKey() error {
if err := h.GetBLSKeyFromRemoteHost(); err != nil {
return err
}
usr, err := user.Current()
if err != nil {
return fmt.Errorf("unable to get system user %s", err)

Check failure on line 190 in node/add_validator_primary.go

View workflow job for this annotation

GitHub Actions / Lint

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}
if err := h.SetNodeBLSKey(filepath.Join(usr.HomeDir, constants.LocalTmpDir, h.NodeID, constants.BLSKeyFileName)); err != nil {
return err
}
return RemoveTmpSDKDir()
}
30 changes: 11 additions & 19 deletions node/add_validator_primary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ package node
import (
"context"
"fmt"
"testing"
"time"

"github.com/ava-labs/avalanche-tooling-sdk-go/avalanche"
"github.com/ava-labs/avalanche-tooling-sdk-go/constants"
"github.com/ava-labs/avalanche-tooling-sdk-go/keychain"
"github.com/ava-labs/avalanche-tooling-sdk-go/wallet"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/units"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
"github.com/ava-labs/avalanchego/wallet/subnet/primary"
"testing"
"time"
)

func TestNodesValidatePrimaryNetwork(_ *testing.T) {
Expand All @@ -26,13 +28,13 @@ func TestNodesValidatePrimaryNetwork(_ *testing.T) {

node := Node{
// NodeID is Avalanche Node ID of the node
NodeID: "NodeID-F63677rCUsAzGWVfwqYBdtVcgNGTXs2Vj",
NodeID: "NODE_ID",
// IP address of the node
IP: "54.67.114.200",
IP: "NODE_IP_ADDRESS",
// SSH configuration for the node
SSHConfig: SSHConfig{
User: constants.AnsibleSSHUser,
PrivateKeyPath: "/Users/raymondsukanto/.ssh/rs_key_pair_sdk.pem",
User: constants.RemoteHostUser,
PrivateKeyPath: "NODE_KEYPAIR_PRIVATE_KEY_PATH",
},
// Cloud is the cloud service that the node is on
Cloud: AWSCloud,
Expand All @@ -42,11 +44,6 @@ func TestNodesValidatePrimaryNetwork(_ *testing.T) {
Roles: []SupportedRole{Validator},
}

err = node.ProvideStakingFiles(fmt.Sprintf("/Users/raymondsukanto/.avalanche-cli/nodes/%s", node.NodeID))
if err != nil {
panic(err)
}

nodeID, err := ids.NodeIDFromString(node.NodeID)
if err != nil {
panic(err)
Expand All @@ -56,13 +53,13 @@ func TestNodesValidatePrimaryNetwork(_ *testing.T) {
NodeID: nodeID,
// Validate Primary Network for 48 hours
Duration: 48 * time.Hour,
// 1 billion in weight is equivalent to 1 AVAX
Weight: 2000000000,
// Stake 2 AVAX
StakeAmount: 2 * units.Avax,
}

network := avalanche.FujiNetwork()

keychain, err := keychain.NewKeychain(network, "/Users/raymondsukanto/.avalanche-cli/key/newTestKeyNew.pk", nil)
keychain, err := keychain.NewKeychain(network, "PRIVATE_KEY_FILEPATH", nil)
if err != nil {
panic(err)
}
Expand All @@ -80,11 +77,6 @@ func TestNodesValidatePrimaryNetwork(_ *testing.T) {
panic(err)
}

err = node.SetNodeBLSKey(fmt.Sprintf("/Users/raymondsukanto/.avalanche-cli/nodes/%s/signer.key", node.NodeID))
if err != nil {
panic(err)
}

txID, err := node.ValidatePrimaryNetwork(avalanche.FujiNetwork(), validator, wallet)
if err != nil {
panic(err)
Expand Down
4 changes: 2 additions & 2 deletions node/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ func createCloudInstances(ctx context.Context, cp CloudParams, count int, useSta
Cloud: cp.Cloud(),
CloudConfig: cp,
SSHConfig: SSHConfig{
User: constants.AnsibleSSHUser,
User: constants.RemoteHostUser,
PrivateKeyPath: sshPrivateKeyPath,
},
Roles: nil,
Expand Down Expand Up @@ -233,7 +233,7 @@ func createCloudInstances(ctx context.Context, cp CloudParams, count int, useSta
Cloud: cp.Cloud(),
CloudConfig: cp,
SSHConfig: SSHConfig{
User: constants.AnsibleSSHUser,
User: constants.RemoteHostUser,
PrivateKeyPath: sshPrivateKeyPath,
},
Roles: nil,
Expand Down
2 changes: 1 addition & 1 deletion utils/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func GetSCPTargetPath(ip, path string) string {
if ip == "" {
return path
}
return fmt.Sprintf("%s@%s:%s", constants.AnsibleSSHUser, ip, path)
return fmt.Sprintf("%s@%s:%s", constants.RemoteHostUser, ip, path)
}

// SplitSCPPath splits the given path into node and path.
Expand Down

0 comments on commit e258762

Please sign in to comment.