This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.go
266 lines (230 loc) · 7.32 KB
/
client.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package main
import (
"context"
"fmt"
"reflect"
"strconv"
"time"
sdkerrors "cosmossdk.io/errors"
abci "github.com/cometbft/cometbft/abci/types"
rpcclient "github.com/cometbft/cometbft/rpc/client"
rpchttp "github.com/cometbft/cometbft/rpc/client/http"
libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client"
"github.com/cosmos/cosmos-sdk/codec/types"
legacyerrors "github.com/cosmos/cosmos-sdk/types/errors"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/cosmos/cosmos-sdk/types/tx"
gogogrpc "github.com/cosmos/gogoproto/grpc"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/encoding"
"google.golang.org/grpc/encoding/proto"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
var _ gogogrpc.ClientConn = &Client{}
var protoCodec = encoding.GetCodec(proto.Name)
type Client struct {
ChainID string
Address string
RPCClient rpcclient.Client
AccountPrefix string
Cdc Codec
Timeout time.Duration
}
type Clients []*Client
func (c Clients) clientByChainID(chainID string) (*Client, error) {
for _, client := range c {
if client.ChainID == chainID {
return client, nil
}
}
return nil, fmt.Errorf("client with chain ID %s is not configured, check config and re-run the program", chainID)
}
func NewClient(chainID, rpcAddr, accountPrefix string, timeout time.Duration) *Client {
rpcClient, err := NewRPCClient(rpcAddr, timeout)
if err != nil {
panic(err)
}
return &Client{
ChainID: chainID,
Address: rpcAddr,
RPCClient: rpcClient,
AccountPrefix: accountPrefix,
Cdc: MakeCodec(ModuleBasics, accountPrefix, accountPrefix+"valoper"),
}
}
// Invoke implements the grpc ClientConn.Invoke method
func (c *Client) Invoke(ctx context.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) {
// Two things can happen here:
// 1. either we're broadcasting a Tx, in which call we call Tendermint's broadcast endpoint directly,
// 2. or we are querying for state, in which case we call ABCI's Querier.
// In both cases, we don't allow empty request req (it will panic unexpectedly).
if reflect.ValueOf(req).IsNil() {
return sdkerrors.Wrap(legacyerrors.ErrInvalidRequest, "request cannot be nil")
}
// Case 1. Broadcasting a Tx.
if reqProto, ok := req.(*tx.BroadcastTxRequest); ok {
if !ok {
return sdkerrors.Wrapf(legacyerrors.ErrInvalidRequest, "expected %T, got %T", (*tx.BroadcastTxRequest)(nil), req)
}
resProto, ok := reply.(*tx.BroadcastTxResponse)
if !ok {
return sdkerrors.Wrapf(legacyerrors.ErrInvalidRequest, "expected %T, got %T", (*tx.BroadcastTxResponse)(nil), req)
}
broadcastRes, err := c.TxServiceBroadcast(ctx, reqProto)
if err != nil {
return err
}
*resProto = *broadcastRes
return err
}
// Case 2. Querying state.
inMd, _ := metadata.FromOutgoingContext(ctx)
abciRes, outMd, err := c.RunGRPCQuery(ctx, method, req, inMd)
if err != nil {
return err
}
if err = protoCodec.Unmarshal(abciRes.Value, reply); err != nil {
return err
}
for _, callOpt := range opts {
header, ok := callOpt.(grpc.HeaderCallOption)
if !ok {
continue
}
*header.HeaderAddr = outMd
}
if c.Cdc.InterfaceRegistry != nil {
return types.UnpackInterfaces(reply, c.Cdc.Marshaler)
}
return nil
}
// NewStream implements the grpc ClientConn.NewStream method
func (c *Client) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) {
return nil, fmt.Errorf("streaming rpc not supported")
}
// RunGRPCQuery runs a gRPC query from the clientCtx, given all necessary
// arguments for the gRPC method, and returns the ABCI response. It is used
// to factorize code between client (Invoke) and server (RegisterGRPCServer)
// gRPC handlers.
func (c *Client) RunGRPCQuery(ctx context.Context, method string, req interface{}, md metadata.MD) (abci.ResponseQuery, metadata.MD, error) {
reqBz, err := protoCodec.Marshal(req)
if err != nil {
return abci.ResponseQuery{}, nil, err
}
// parse height header
if heights := md.Get(grpctypes.GRPCBlockHeightHeader); len(heights) > 0 {
height, err := strconv.ParseInt(heights[0], 10, 64)
if err != nil {
return abci.ResponseQuery{}, nil, err
}
if height < 0 {
return abci.ResponseQuery{}, nil, sdkerrors.Wrapf(
legacyerrors.ErrInvalidRequest,
"client.Context.Invoke: height (%d) from %q must be >= 0", height, grpctypes.GRPCBlockHeightHeader)
}
}
height, err := GetHeightFromMetadata(md)
if err != nil {
return abci.ResponseQuery{}, nil, err
}
prove, err := GetProveFromMetadata(md)
if err != nil {
return abci.ResponseQuery{}, nil, err
}
abciReq := abci.RequestQuery{
Path: method,
Data: reqBz,
Height: height,
Prove: prove,
}
abciRes, err := c.QueryABCI(ctx, abciReq)
if err != nil {
return abci.ResponseQuery{}, nil, err
}
// Create header metadata. For now the headers contain:
// - block height
// We then parse all the call options, if the call option is a
// HeaderCallOption, then we manually set the value of that header to the
// metadata.
md = metadata.Pairs(grpctypes.GRPCBlockHeightHeader, strconv.FormatInt(abciRes.Height, 10))
return abciRes, md, nil
}
// TxServiceBroadcast is a helper function to broadcast a Tx with the correct gRPC types
// from the tx service. Calls `clientCtx.BroadcastTx` under the hood.
func (c *Client) TxServiceBroadcast(ctx context.Context, req *tx.BroadcastTxRequest) (*tx.BroadcastTxResponse, error) {
if req == nil || req.TxBytes == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx")
}
//var (
// blockTimeout = defaultBroadcastWaitTimeout
// err error
// rlyResp *provider.RelayerTxResponse
// callbackErr error
// wg sync.WaitGroup
//)
//
//if cc.PCfg.BlockTimeout != "" {
// blockTimeout, err = time.ParseDuration(cc.PCfg.BlockTimeout)
// if err != nil {
// // Did you call Validate() method on CosmosProviderConfig struct
// // before coming here?
// return nil, err
// }
//}
//
//callback := func(rtr *provider.RelayerTxResponse, err error) {
// rlyResp = rtr
// callbackErr = err
// wg.Done()
//}
//
//wg.Add(1)
//
//if err := cc.broadcastTx(ctx, req.TxBytes, nil, nil, ctx, blockTimeout, []func(*provider.RelayerTxResponse, error){callback}); err != nil {
// return nil, err
//}
//
//wg.Wait()
//if callbackErr != nil {
// return nil, callbackErr
//}
//
//return &tx.BroadcastTxResponse{
// TxResponse: &sdk.TxResponse{
// Height: rlyResp.Height,
// TxHash: rlyResp.TxHash,
// Codespace: rlyResp.Codespace,
// Code: rlyResp.Code,
// Data: rlyResp.Data,
// },
//}, nil
return nil, nil
}
func GetHeightFromMetadata(md metadata.MD) (int64, error) {
height := md.Get(grpctypes.GRPCBlockHeightHeader)
if len(height) == 1 {
return strconv.ParseInt(height[0], 10, 64)
}
return 0, nil
}
func GetProveFromMetadata(md metadata.MD) (bool, error) {
prove := md.Get("x-cosmos-query-prove")
if len(prove) == 1 {
return strconv.ParseBool(prove[0])
}
return false, nil
}
func NewRPCClient(addr string, timeout time.Duration) (*rpchttp.HTTP, error) {
httpClient, err := libclient.DefaultHTTPClient(addr)
if err != nil {
return nil, err
}
httpClient.Timeout = timeout
rpcClient, err := rpchttp.NewWithClient(addr, "/websocket", httpClient)
if err != nil {
return nil, err
}
return rpcClient, nil
}