/
client.go
288 lines (240 loc) · 8.17 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package client
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/rs/zerolog/log"
"github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/forbole/flowJuno/types"
"google.golang.org/grpc"
"github.com/onflow/flow-go-sdk"
"github.com/onflow/flow-go-sdk/client"
)
// Proxy implements a wrapper around both a Tendermint RPC client and a
// Cosmos Sdk REST client that allows for essential data queries.
type Proxy struct {
ctx context.Context
encodingConfig *params.EncodingConfig
contract Contracts
flowClient client.Client
grpConnection *grpc.ClientConn
txServiceClient tx.ServiceClient
genesisHeight uint64
}
// NewClientProxy allows to build a new Proxy instance
func NewClientProxy(cfg types.Config, encodingConfig *params.EncodingConfig) (*Proxy, error) {
flowClient, err := client.New(cfg.GetRPCConfig().GetAddress(), grpc.WithInsecure())
if err != nil {
return nil, err
}
ctx := context.Background()
var contracts Contracts
if cfg.GetRPCConfig().GetContracts() == "Mainnet" {
contracts = MainnetContracts()
} else if cfg.GetRPCConfig().GetContracts() == "Testnet" {
contracts = TestnetContracts()
}
return &Proxy{
encodingConfig: encodingConfig,
ctx: ctx,
flowClient: *flowClient,
grpConnection: nil,
txServiceClient: nil,
contract: contracts,
genesisHeight: cfg.GetCosmosConfig().GetGenesisHeight(),
}, nil
}
// GetGeneisisBlock parse the specific block as genesis block
func (cp *Proxy) GetGenesisHeight() uint64 {
return cp.genesisHeight
}
// LatestHeight returns the latest block height on the active chain. An error
// is returned if the query fails.
func (cp *Proxy) LatestHeight() (int64, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
block, err := cp.flowClient.GetLatestBlock(ctx, true)
if err != nil {
return -1, err
}
height := int64(block.Height)
return height, nil
}
// Block queries for a block by height. An error is returned if the query fails.
func (cp *Proxy) Block(height int64) (*flow.Block, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
block, err := cp.flowClient.GetBlockByHeight(ctx, uint64(height))
if err != nil {
return nil, err
}
return block, nil
}
// GetTransaction queries for a transaction by hash. An error is returned if the
// query fails.
func (cp *Proxy) GetTransaction(hash string) (*flow.Transaction, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
transaction, err := cp.flowClient.GetTransaction(ctx, flow.HashToID([]byte(hash)))
if err != nil {
return nil, err
}
return transaction, nil
}
func (cp *Proxy) Client() *client.Client {
return &cp.flowClient
}
func (cp *Proxy) Ctx() context.Context {
return cp.ctx
}
func (cp *Proxy) Contract() Contracts {
return cp.contract
}
func (cp *Proxy) GetChainID() string {
// There is GetNetworkParameters rpc method that not implenment yet in flow-go-sdk.
return cp.contract.ChainID
}
// Collections get all the collection from block
func (cp *Proxy) Collections(block *flow.Block) []types.Collection {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
collectionsID := block.CollectionGuarantees
collections := make([]types.Collection, len(block.CollectionGuarantees))
for i, c := range collectionsID {
collection, err := cp.flowClient.GetCollection(ctx, c.CollectionID)
// When it do not have a collection transaction yet at that block. It do not have a transaction ID
// Retry until collection is produced
sleeptime := 1
for err != nil && strings.Contains(err.Error(), "please retry for collection in finalized block") {
// It is not because block not finalized. Just unprocessable block
if sleeptime >= 16 {
break
}
time.Sleep(time.Duration(sleeptime) * time.Second)
collection, err = cp.flowClient.GetCollection(ctx, c.CollectionID)
sleeptime = sleeptime * 2
}
if err != nil {
collections[i] = types.NewCollection(block.Height, c.CollectionID.String(), false, nil)
continue
}
collections[i] = types.NewCollection(block.Height, c.CollectionID.String(), true, collection.TransactionIDs)
}
return collections
}
// Txs queries for all the transactions in a block. Transactions are returned
// in the TransactionResult format which internally contains an array of Transactions. An error is
// returned if any query fails.
func (cp *Proxy) Txs(block *flow.Block) (types.Txs, error) {
var transactionIDs []flow.Identifier
collections := cp.Collections(block)
for _, collection := range collections {
transactionIDs = append(transactionIDs, (collection.TransactionIds)...)
}
txResponses := make([]types.Tx, len(transactionIDs))
for i, txID := range transactionIDs {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
transaction, err := cp.flowClient.GetTransaction(ctx, txID)
cancel()
if err != nil {
return nil, err
}
authoriser := make([]string, len(transaction.Authorizers))
for i, auth := range transaction.Authorizers {
authoriser[i] = auth.String()
}
payloadSignitures, err := json.Marshal(transaction.PayloadSignatures)
if err != nil {
return nil, err
}
envelopeSigniture, err := json.Marshal(transaction.EnvelopeSignatures)
if err != nil {
return nil, err
}
tx := types.NewTx(block.Height, txID.String(), transaction.Script, transaction.Arguments,
transaction.ReferenceBlockID.String(), transaction.GasLimit, transaction.ProposalKey.Address.String(), transaction.Payer.String(),
authoriser, payloadSignitures, envelopeSigniture)
txResponses[i] = tx
}
return txResponses, nil
}
func (cp *Proxy) TransactionResult(transactionIds []flow.Identifier) ([]types.TransactionResult, error) {
if len(transactionIds) == 0 {
return nil, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
txResults := make([]types.TransactionResult, len(transactionIds))
for i, txid := range transactionIds {
result, err := cp.flowClient.GetTransactionResult(ctx, txid)
if err != nil {
return nil, err
}
errStr := ""
if result.Error != nil {
errStr = result.Error.Error()
}
txResults[i] = types.NewTransactionResult(txid.String(), result.Status.String(), errStr)
}
return txResults, nil
}
func (cp *Proxy) EventsInBlock(block *flow.Block) ([]types.Event, error) {
txs, err := cp.Txs(block)
if err != nil {
return nil, err
}
var event []types.Event
for _, tx := range txs {
ev, err := cp.Events(tx.TransactionID, int(tx.Height))
if err != nil {
return []types.Event{}, err
}
event = append(event, ev...)
}
return event, nil
}
func (cp *Proxy) EventsInTransaction(tx types.Tx) ([]types.Event, error) {
var event []types.Event
ev, err := cp.Events(tx.TransactionID, int(tx.Height))
if err != nil {
return nil, err
}
event = append(event, ev...)
return event, nil
}
// Events get events from a transaction ID
func (cp *Proxy) Events(transactionID string, height int) ([]types.Event, error) {
sleeptime := 1
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(sleeptime)*time.Second)
transactionResult, err := cp.flowClient.GetTransactionResult(ctx, flow.HexToID(transactionID))
cancel()
for err != nil && strings.Contains(err.Error(), "context deadline exceeded") {
if sleeptime >= 16 {
// fail
return nil, err
}
sleeptime = sleeptime * 2
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(sleeptime)*time.Second)
transactionResult, err = cp.flowClient.GetTransactionResult(ctx, flow.HexToID(transactionID))
cancel()
}
if err != nil {
return nil, fmt.Errorf("Error:%s,TxID:%s",err,transactionID)
}
ev := make([]types.Event, len(transactionResult.Events))
for i, event := range transactionResult.Events {
ev[i] = types.NewEvent(height, event.Type, event.TransactionID.String(), event.TransactionIndex,
event.EventIndex, event.Value)
}
return ev, nil
}
// Stop defers the node stop execution to the RPC client.
func (cp *Proxy) Stop() {
err := cp.flowClient.Close()
if err != nil {
log.Fatal().Str("module", "client proxy").Err(err).Msg("error while stopping proxy")
}
}