Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
batphonghan committed Feb 15, 2024
1 parent bfcd331 commit 359d466
Show file tree
Hide file tree
Showing 8 changed files with 31 additions and 20 deletions.
2 changes: 1 addition & 1 deletion shared/services/gas/gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func handleEtherscanGasPrices(gasSuggestion etherscan.GasFeeSuggestion, priority

desiredPriceFloat, err := strconv.ParseFloat(desiredPrice, 64)
if err != nil {
fmt.Println("Not a valid gas price (%s), try again.", err.Error())
fmt.Printf("Not a valid gas price (%s), try again.\n", err.Error())
continue
}
if desiredPriceFloat <= 0 {
Expand Down
2 changes: 1 addition & 1 deletion shared/services/requirements.go
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ func waitBeaconClientSynced(c *cli.Context, verbose bool, timeout int64) (bool,
// Check sync status
if syncStatus.Syncing {
if verbose {
log.Println("Eth 2.0 node syncing: %.2f%%\n", syncStatus.Progress*100)
log.Printf("Eth 2.0 node syncing: %.2f%%\n", syncStatus.Progress*100)
}
} else {
return true, nil
Expand Down
3 changes: 1 addition & 2 deletions shared/services/stader/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ func (c *Client) UpdatePrometheusConfiguration(settings map[string]string) error
}
err = os.Chmod(prometheusConfigPath, 0664)
if err != nil {
return fmt.Errorf("Could not set Prometheus config file permissions: %w", shellescape.Quote(prometheusConfigPath), err)
return fmt.Errorf("Could not set Prometheus config file permissions: %s: %w", shellescape.Quote(prometheusConfigPath), err)
}

return nil
Expand Down Expand Up @@ -795,7 +795,6 @@ func (c *Client) GetDockerContainerShutdownTime(container string) (time.Time, er
}

func (c *Client) UpdateGuardianConfiguration(contents []byte) error {

guardianTemplatePath, err := homedir.Expand(fmt.Sprintf("%s/%s/%s", c.configPath, templatesDir, GuardianFileTemplate))
if err != nil {
return fmt.Errorf("error expanding Guardian template path: %w", err)
Expand Down
4 changes: 2 additions & 2 deletions stader-cli/node/claim-sp-rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ func ClaimSpRewards(c *cli.Context) error {
cycleIndexes = append(cycleIndexes, big.NewInt(cycleInfo.MerkleProofInfo.Cycle))
}

fmt.Println("Following are the unclaimed cycles, Please enter in a comma seperated string the cycles you want to claim rewards for:\n")
fmt.Println("Following are the unclaimed cycles, Please enter in a comma separated string the cycles you want to claim rewards for:")

fmt.Printf("%-18s%-14.30s%-14.10s%-10s\n", "Cycle Number", "Cycle Date", "ETH Rewards", "SD Rewards")
fmt.Printf("\n%-18s%-14.30s%-14.10s%-10s\n", "Cycle Number", "Cycle Date", "ETH Rewards", "SD Rewards")
cyclesToClaim := map[int64]bool{}
for {
for _, cycleInfo := range detailedCyclesInfo.DetailedCyclesInfo {
Expand Down
6 changes: 3 additions & 3 deletions stader-cli/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -914,7 +914,7 @@ func pruneExecutionClient(c *cli.Context) error {
}

fmt.Println("This will shut down your main execution client and prune its database, freeing up disk space.")
fmt.Println("Once pruning is complete, your execution client will restart automatically.\n")
fmt.Println("Once pruning is complete, your execution client will restart automatically.")

if selectedEc == cfgtypes.ExecutionClient_Geth {
if cfg.UseFallbackClients.Value == false {
Expand Down Expand Up @@ -1488,7 +1488,7 @@ func exportEcData(c *cli.Context, targetDir string) error {

fmt.Println("This will export your execution client's chain data to an external directory, such as a portable hard drive.")
fmt.Println("If your execution client is running, it will be shut down.")
fmt.Println("Once the export is complete, your execution client will restart automatically.\n")
fmt.Println("Once the export is complete, your execution client will restart automatically.")

// Get the container prefix
prefix, err := getContainerPrefix(staderClient)
Expand Down Expand Up @@ -1606,7 +1606,7 @@ func importEcData(c *cli.Context, sourceDir string) error {

fmt.Println("This will import execution layer chain data that you previously exported into your execution client.")
fmt.Println("If your execution client is running, it will be shut down.")
fmt.Println("Once the import is complete, your execution client will restart automatically.\n")
fmt.Println("Once the import is complete, your execution client will restart automatically.")

// Get the volume to import into
executionContainerName := prefix + ExecutionContainerSuffix
Expand Down
4 changes: 2 additions & 2 deletions stader-cli/wallet/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ func exportWallet(c *cli.Context) error {
// Check if stdout is interactive
stat, err := os.Stdout.Stat()
if err != nil {
fmt.Fprintf(os.Stderr, "An error occured while determining whether or not the output is a tty: %w\n"+
"Use \"stader-cli --secure-session wallet export\" to bypass.\n", err)
fmt.Fprintf(os.Stderr, "An error occured while determining whether or not the output is a tty: %s\n"+
"Use \"stader-cli --secure-session wallet export\" to bypass.\n", err.Error())
os.Exit(1)
}

Expand Down
15 changes: 11 additions & 4 deletions stader/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,14 +403,18 @@ func run(c *cli.Context) error {

go func() {
defer wg.Done()
privateKey, err := w.GetNodePrivateKey()

privateKey, err := w.GetNodePrivateKey()
if err != nil {
errorLog.Printlnf("Error GetNodePrivateKey %+v", err)
return
}

cfg, err := services.GetConfig(c)
if err != nil {
errorLog.Printlnf("Error getconfig %+v", err)
return
}

for {
infoLog.Printlnf("Running the node diversity tracker daemon")
Expand All @@ -419,13 +423,15 @@ func run(c *cli.Context) error {
if err != nil {
errorLog.Printlnf("Error makesNodeDiversityMessage %+v", err)
time.Sleep(nodeDiversityTrackerCooldown)

continue
}

request, err := makesNodeDiversityRequest(message, privateKey)
if err != nil {
errorLog.Printlnf("Error makesNodeDiversityRequest %+v", err)
time.Sleep(nodeDiversityTrackerCooldown)

continue
}

Expand All @@ -434,6 +440,7 @@ func run(c *cli.Context) error {
if err != nil {
errorLog.Printlnf("Error SendNodeDiversityResponseType %+v", err)
time.Sleep(nodeDiversityTrackerCooldown)

continue
}

Expand Down Expand Up @@ -484,6 +491,7 @@ func makesNodeDiversityMessage(

if cfg.EnableMevBoost.Value == true {
var relays []cfgtypes.MevRelay

relayNames := []string{}
switch cfg.MevBoost.Mode.Value.(cfgtypes.Mode) {
case cfgtypes.Mode_Local:
Expand All @@ -497,12 +505,12 @@ func makesNodeDiversityMessage(
relayString = strings.Join(relayNames, ",")
}

operatorId, err := node.GetOperatorId(pnr, nodeAccount.Address, nil)
operatorID, err := node.GetOperatorId(pnr, nodeAccount.Address, nil)
if err != nil {
return nil, err
}

totalValidatorKeys, err := node.GetTotalValidatorKeys(pnr, operatorId, nil)
totalValidatorKeys, err := node.GetTotalValidatorKeys(pnr, operatorID, nil)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -551,7 +559,6 @@ func makesNodeDiversityRequest(msg *stader_backend.NodeDiversity, privateKey *ec
}

return &request, nil

}

// Configure HTTP transport settings
Expand Down
15 changes: 10 additions & 5 deletions stader/node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/crypto"
eCryto "github.com/ethereum/go-ethereum/crypto"
stader_backend "github.com/stader-labs/stader-node/shared/types/stader-backend"
)

Expand All @@ -36,11 +35,12 @@ func TestVerifySignature(t *testing.T) {
}

pubkeyBytes := crypto.FromECDSAPub(publicKeyECDSA)

req, err := makesNodeDiversityRequest(&stader_backend.NodeDiversity{
ExecutionClient: ExecutionClient,
ConsensusClient: ConsensusClient,
ValidatorClient: ValidatorClient,
TotalNonTerminalKeys: 1,
TotalNonTerminalKeys: 10,
NodeAddress: crypto.PubkeyToAddress(*publicKeyECDSA).String(),
NodePublicKey: hex.EncodeToString(pubkeyBytes),
Relays: "ultrasound,aestus",
Expand All @@ -58,20 +58,21 @@ func TestVerifySignature(t *testing.T) {
}

func TestVerifySignatureFailed(t *testing.T) {
privateKey, err := ecdsa.GenerateKey(eCryto.S256(), rand.Reader)
privateKey, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
if err != nil {
t.Error(err)
}

publicKey := privateKey.Public()

publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
t.Error(err)
}

publickeyBytes := crypto.FromECDSAPub(publicKeyECDSA)

privateKeyFake, err := ecdsa.GenerateKey(eCryto.S256(), rand.Reader)
privateKeyFake, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
if err != nil {
t.Error(err)
}
Expand All @@ -85,6 +86,7 @@ func TestVerifySignatureFailed(t *testing.T) {
NodeAddress: crypto.PubkeyToAddress(*publicKeyECDSA).String(),
NodePublicKey: hex.EncodeToString(publickeyBytes),
}

req, err := makesNodeDiversityRequest(&msg, privateKeyFake)
if err != nil {
t.Error(err)
Expand All @@ -98,6 +100,8 @@ func TestVerifySignatureFailed(t *testing.T) {
}

func verifySignature(t *testing.T, msg *stader_backend.NodeDiversity, signEncoded string) bool {
t.Helper()

signRaw, err := hex.DecodeString(signEncoded)
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -126,6 +130,7 @@ func verifySignature(t *testing.T, msg *stader_backend.NodeDiversity, signEncode

fmt.Printf("[%s]", msgBytes)
fmt.Printf("[%s]", signEncoded)

msgHashed := accounts.TextHash(msgBytes)

decodePubkey, err := hex.DecodeString(msg.NodePublicKey)
Expand All @@ -134,5 +139,5 @@ func verifySignature(t *testing.T, msg *stader_backend.NodeDiversity, signEncode
}

// 4. Verify
return eCryto.VerifySignature(decodePubkey, msgHashed, signRaw)
return crypto.VerifySignature(decodePubkey, msgHashed, signRaw)
}

0 comments on commit 359d466

Please sign in to comment.