-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchain_id.go
More file actions
67 lines (53 loc) · 1.94 KB
/
Copy pathchain_id.go
File metadata and controls
67 lines (53 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"context"
"fmt"
"time"
rpchttp "github.com/cometbft/cometbft/rpc/client/http"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/cosmos/cosmos-sdk/client/grpc/cmtservice"
)
// detectChainID queries both the gRPC endpoint and the CometBFT RPC endpoint
// for the chain ID, validates that they agree, and returns the chain ID.
// Returns an error if either endpoint is unreachable or if they return
// different chain IDs.
func detectChainID(ctx context.Context, grpcAddr, nodeRPCAddr string) (string, error) {
detectCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
grpcChainID, err := chainIDFromGRPC(detectCtx, grpcAddr)
if err != nil {
return "", fmt.Errorf("failed to detect chain ID via gRPC (%s): %w", grpcAddr, err)
}
rpcChainID, err := chainIDFromRPC(detectCtx, nodeRPCAddr)
if err != nil {
return "", fmt.Errorf("failed to detect chain ID via node RPC (%s): %w", nodeRPCAddr, err)
}
if grpcChainID != rpcChainID {
return "", fmt.Errorf("chain ID mismatch: gRPC returned %q, node RPC returned %q", grpcChainID, rpcChainID)
}
return grpcChainID, nil
}
func chainIDFromGRPC(ctx context.Context, grpcAddr string) (string, error) {
conn, err := grpc.DialContext(ctx, grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return "", fmt.Errorf("dial: %w", err)
}
defer conn.Close()
resp, err := cmtservice.NewServiceClient(conn).GetNodeInfo(ctx, &cmtservice.GetNodeInfoRequest{})
if err != nil {
return "", fmt.Errorf("GetNodeInfo: %w", err)
}
return resp.DefaultNodeInfo.Network, nil
}
func chainIDFromRPC(ctx context.Context, nodeRPCAddr string) (string, error) {
rpcClient, err := rpchttp.New(nodeRPCAddr, "/websocket")
if err != nil {
return "", fmt.Errorf("create client: %w", err)
}
status, err := rpcClient.Status(ctx)
if err != nil {
return "", fmt.Errorf("status: %w", err)
}
return status.NodeInfo.Network, nil
}