Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
batphonghan committed Feb 5, 2024
1 parent c507a38 commit 2526e56
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 34 deletions.
4 changes: 4 additions & 0 deletions shared/services/config/stadernode-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ func (cfg *StaderNodeConfig) GetMerkleProofApi() string {
return cfg.baseStaderBackendUrl[cfg.Network.Value.(config.Network)] + "/merklesForElRewards/proofs/%s"
}

func (cfg *StaderNodeConfig) GetNodeDiversityApi() string {
return cfg.baseStaderBackendUrl[cfg.Network.Value.(config.Network)] + "/nodeDiversity"
}

func (cfg *StaderNodeConfig) GetTxWatchUrl() string {
return cfg.txWatchUrl[cfg.Network.Value.(config.Network)]
}
Expand Down
9 changes: 7 additions & 2 deletions shared/types/stader-backend/node-diversity.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package stader_backend

type NodeDiversityRequest struct {
Signature string `json:"signature"`
Message string `json:"message"`
Signature string `json:"signature"`
Message *NodeDiversity `json:"message"`
}

type NodeDiversity struct {
Expand All @@ -12,3 +12,8 @@ type NodeDiversity struct {
NodePublicKey string `json:"nodePublicKey"`
Relays string `json:"relays"`
}

type NodeDiversityResponseType struct {
Success bool `json:"success"`
Error string `json:"error"`
}
37 changes: 37 additions & 0 deletions shared/utils/stader/node-diversity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package stader

import (
"encoding/json"
"fmt"

"github.com/stader-labs/stader-node/shared/services"
stader_backend "github.com/stader-labs/stader-node/shared/types/stader-backend"
"github.com/stader-labs/stader-node/shared/utils/net"
"github.com/urfave/cli"
)

func SendNodeDiversityResponseType(
c *cli.Context,
request *stader_backend.NodeDiversityRequest,
) (*stader_backend.NodeDiversityResponseType, error) {
config, err := services.GetConfig(c)
if err != nil {
return nil, err
}

res, err := net.MakePostRequest(config.StaderNode.GetNodeDiversityApi(), request)
if err != nil {
return nil, fmt.Errorf("request to GetNodeDiversityApi %w", err)
}
defer res.Body.Close()

var resp stader_backend.NodeDiversityResponseType
err = json.NewDecoder(res.Body).Decode(&resp)

if err != nil {
return nil, fmt.Errorf("decode NodeDiversityResponseType %w", err)
}

return &resp, nil

}
4 changes: 2 additions & 2 deletions stader-cli/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -684,8 +684,8 @@ func startService(
fmt.Printf("%sWarning: couldn't verify that the validator container can be safely restarted:\n\t%s\n", colorYellow, err.Error())
fmt.Println("If you are changing to a different ETH2 client, it may resubmit an attestation you have already submitted.")
fmt.Println("This will slash your validator!")
fmt.Println("To prevent slashing, you must wait 15 minutes from the time you stopped the clients before starting them again.\n")
fmt.Println("**If you did NOT change clients, you can safely ignore this warning.**\n")
fmt.Println("To prevent slashing, you must wait 15 minutes from the time you stopped the clients before starting them again.")
fmt.Println("**If you did NOT change clients, you can safely ignore this warning.**")
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Stader:%s", colorReset)) {
fmt.Println("Cancelled.")
return nil
Expand Down
26 changes: 19 additions & 7 deletions stader/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ package node

import (
"crypto/ecdsa"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
Expand All @@ -34,7 +35,6 @@ import (
"sync"
"time"

"github.com/ethereum/go-ethereum/accounts"
eCryto "github.com/ethereum/go-ethereum/crypto"

cfgtypes "github.com/stader-labs/stader-node/shared/types/config"
Expand Down Expand Up @@ -425,9 +425,20 @@ func run(c *cli.Context) error {
continue
}

fmt.Printf("%+v", request)
time.Sleep(nodeDiversityTracker)
response, err := stader.SendNodeDiversityResponseType(c, request)

if err != nil {
errorLog.Printlnf("Error SendNodeDiversityResponseType %+v", err)
continue
}

if response.Success {
infoLog.Println("Successfully sent the NodeDiversity message")
} else {
errorLog.Println("Failed to send the NodeDiversity message with err: %s\n", response.Error)
}

time.Sleep(nodeDiversityTracker)
}
}()

Expand Down Expand Up @@ -488,7 +499,6 @@ func makesNodeDiversityMessage(
Relays: relayString,
}

fmt.Printf("\n{%+v}\n", message)
return &message, nil
}

Expand All @@ -498,16 +508,18 @@ func makesNodeDiversityRequest(msg *stader_backend.NodeDiversity, privateKey *ec
return nil, err
}

messageHash := accounts.TextHash(msgBytes)
h := sha256.New()
h.Write(msgBytes)
msgHashed := h.Sum(nil)

rawSign, err := eCryto.Sign(messageHash, privateKey)
rawSign, err := eCryto.Sign(msgHashed, privateKey)
if err != nil {
return nil, err
}

request := stader_backend.NodeDiversityRequest{
Signature: hex.EncodeToString(rawSign[:64]),
Message: hex.EncodeToString(msgBytes),
Message: msg,
}

return &request, nil
Expand Down
40 changes: 17 additions & 23 deletions stader/node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package node
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"testing"

"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 @@ -30,12 +30,12 @@ func TestVerifySignature(t *testing.T) {
t.Error(err)
}

publickeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
pubkeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
req, err := makesNodeDiversityRequest(&stader_backend.NodeDiversity{
ExecutionClient: ExecutionClient,
ConsensusClient: ConsensusClient,
NodeAddress: crypto.PubkeyToAddress(*publicKeyECDSA).String(),
NodePublicKey: hex.EncodeToString(publickeyBytes),
NodePublicKey: hex.EncodeToString(pubkeyBytes),
}, privateKey)
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -68,59 +68,53 @@ func TestVerifySignatureFailed(t *testing.T) {
t.Error(err)
}

req, err := makesNodeDiversityRequest(&stader_backend.NodeDiversity{
msg := stader_backend.NodeDiversity{
ExecutionClient: ExecutionClient,
ConsensusClient: ConsensusClient,
NodeAddress: crypto.PubkeyToAddress(*publicKeyECDSA).String(),
NodePublicKey: hex.EncodeToString(publickeyBytes),
}, privateKeyFake)
}
req, err := makesNodeDiversityRequest(&msg, privateKeyFake)
if err != nil {
t.Error(err)
}

msgStr := req.Message
verified := verifySignature(t, msgStr, req.Signature)
verified := verifySignature(t, req.Message, req.Signature)

if verified {
t.Error("verified should failed")
}
}

func verifySignature(t *testing.T, msgStr string, sig string) bool {
// 1. Decode Hex
msgBytes, err := hex.DecodeString(msgStr)
if err != nil {
t.Error(err)
}

sign, err := hex.DecodeString(sig)
func verifySignature(t *testing.T, msg *stader_backend.NodeDiversity, signEncoded string) bool {
sign, err := hex.DecodeString(signEncoded)
if err != nil {
t.Error(err)
}

// 2. Unmarshal to get message
var msg stader_backend.NodeDiversity
err = json.Unmarshal(msgBytes, &msg)
if err != nil {
if msg.ConsensusClient != ConsensusClient {
t.Error(err)
}

if msg.ConsensusClient != ConsensusClient {
if msg.ExecutionClient != ExecutionClient {
t.Error(err)
}

if msg.ExecutionClient != ExecutionClient {
msgBytes, err := json.Marshal(msg)
if err != nil {
t.Error(err)
}

// 3. Calculate hash
messageHash := accounts.TextHash(msgBytes)
h := sha256.New()
h.Write(msgBytes)
msgHashed := h.Sum(nil)

decodePubkey, err := hex.DecodeString(msg.NodePublicKey)
if err != nil {
t.Error(err)
}

// 4. Verify
return eCryto.VerifySignature(decodePubkey, messageHash, sign)
return eCryto.VerifySignature(decodePubkey, msgHashed, sign)
}

0 comments on commit 2526e56

Please sign in to comment.