-
Notifications
You must be signed in to change notification settings - Fork 28
/
invocation.go
315 lines (266 loc) · 8.47 KB
/
invocation.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package types
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
tmbytes "github.com/cometbft/cometbft/libs/bytes"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NewRequestContext creates a new RequestContext instance
func NewRequestContext(
serviceName string,
providers []sdk.AccAddress,
consumer sdk.AccAddress,
input string,
serviceFeeCap sdk.Coins,
timeout int64,
repeated bool,
repeatedFrequency uint64,
repeatedTotal int64,
batchCounter uint64,
batchRequestCount,
batchResponseCount uint32,
batchResponseThreshold uint32,
batchState RequestContextBatchState,
state RequestContextState,
responseThreshold uint32,
moduleName string,
) RequestContext {
pds := make([]string, len(providers))
for i, provider := range providers {
pds[i] = provider.String()
}
return RequestContext{
ServiceName: serviceName,
Providers: pds,
Consumer: consumer.String(),
Input: input,
ServiceFeeCap: serviceFeeCap,
Timeout: timeout,
Repeated: repeated,
RepeatedFrequency: repeatedFrequency,
RepeatedTotal: repeatedTotal,
BatchCounter: batchCounter,
BatchRequestCount: batchRequestCount,
BatchResponseCount: batchResponseCount,
BatchResponseThreshold: batchResponseThreshold,
BatchState: batchState,
State: state,
ResponseThreshold: responseThreshold,
ModuleName: moduleName,
}
}
// Validate validates the request context
func (rc RequestContext) Validate() error {
if err := ValidateServiceName(rc.ServiceName); err != nil {
return err
}
pds := make([]sdk.AccAddress, len(rc.Providers))
for i, provider := range rc.Providers {
pd, err := sdk.AccAddressFromBech32(provider)
if err != nil {
return err
}
pds[i] = pd
}
if err := ValidateProviders(pds); err != nil {
return err
}
if err := ValidateConsumer(rc.Consumer); err != nil {
return err
}
if err := ValidateInput(rc.Input); err != nil {
return err
}
return ValidateServiceFeeCap(rc.ServiceFeeCap)
}
// Empty returns true if empty
func (rc RequestContext) Empty() bool {
// TODO: use rc.ID
return len(rc.Consumer) == 0
}
// NewCompactRequest creates a new CompactRequest instance
func NewCompactRequest(
requestContextID tmbytes.HexBytes,
batchCounter uint64,
provider sdk.AccAddress,
serviceFee sdk.Coins,
requestHeight int64,
expirationHeight int64,
) CompactRequest {
return CompactRequest{
RequestContextId: requestContextID.String(),
RequestContextBatchCounter: batchCounter,
Provider: provider.String(),
ServiceFee: serviceFee,
RequestHeight: requestHeight,
ExpirationHeight: expirationHeight,
}
}
// NewRequest creates a new Request instance
func NewRequest(
id tmbytes.HexBytes,
serviceName string,
provider,
consumer sdk.AccAddress,
input string,
serviceFee sdk.Coins,
requestHeight int64,
expirationHeight int64,
requestContextID tmbytes.HexBytes,
batchCounter uint64,
) Request {
return Request{
Id: id.String(),
ServiceName: serviceName,
Provider: provider.String(),
Consumer: consumer.String(),
Input: input,
ServiceFee: serviceFee,
RequestHeight: requestHeight,
ExpirationHeight: expirationHeight,
RequestContextId: requestContextID.String(),
RequestContextBatchCounter: batchCounter,
}
}
// Empty returns true if empty
func (r Request) Empty() bool {
return len(r.Id) == 0
}
// NewResponse creates a new Response instance
func NewResponse(
provider,
consumer sdk.AccAddress,
result,
output string,
requestContextID tmbytes.HexBytes,
batchCounter uint64,
) Response {
return Response{
Provider: provider.String(),
Consumer: consumer.String(),
Result: result,
Output: output,
RequestContextId: requestContextID.String(),
RequestContextBatchCounter: batchCounter,
}
}
// Empty returns true if empty
func (r Response) Empty() bool {
return len(r.RequestContextId) == 0
}
// ResultCode defines the type for the result code
type ResultCode uint16
const (
// ResultOK means that the request is well processed
ResultOK ResultCode = 200
// ResultBadRequest means that the request is incorrect
ResultBadRequest ResultCode = 400
// ResultServerError is the code resulting from the internal server error
ResultServerError ResultCode = 500
)
// Result defines a struct for the response result
type Result struct {
Code ResultCode `json:"code"`
Message string `json:"message"`
}
// ParseResult parses the given string to Result
func ParseResult(result string) (Result, error) {
var r Result
if err := json.Unmarshal([]byte(result), &r); err != nil {
return r, errorsmod.Wrapf(
ErrInvalidResponseResult,
"failed to unmarshal the result: %s",
err,
)
}
return r, nil
}
func RequestContextStateFromString(str string) (RequestContextState, error) {
if state, ok := RequestContextState_value[strings.ToUpper(str)]; ok {
return RequestContextState(state), nil
}
return RequestContextState(0xff), fmt.Errorf("'%s' is not a valid request context state", str)
}
// Marshal needed for protobuf compatibility
func (state RequestContextState) Marshal() ([]byte, error) {
return []byte{byte(state)}, nil
}
// Unmarshal needed for protobuf compatibility
func (state *RequestContextState) Unmarshal(data []byte) error {
*state = RequestContextState(data[0])
return nil
}
// Marshal needed for protobuf compatibility
func (state RequestContextBatchState) Marshal() ([]byte, error) {
return []byte{byte(state)}, nil
}
// Unmarshal needed for protobuf compatibility
func (state *RequestContextBatchState) Unmarshal(data []byte) error {
*state = RequestContextBatchState(data[0])
return nil
}
// ResponseCallback defines the response callback interface
type ResponseCallback func(ctx sdk.Context, requestContextID tmbytes.HexBytes, responses []string, err error)
// StateCallback defines the state callback interface
type StateCallback func(ctx sdk.Context, requestContextID tmbytes.HexBytes, cause string)
const (
RequestIDLen = 116
ContextIDLen = 80
)
// ConvertRequestID converts the given string to request ID
func ConvertRequestID(requestIDStr string) (tmbytes.HexBytes, error) {
if len(requestIDStr) != RequestIDLen {
return nil, errors.New("invalid request id")
}
requestID, err := hex.DecodeString(requestIDStr)
if err != nil {
return nil, errors.New("invalid request id")
}
return requestID, nil
}
// GenerateRequestContextID generates a unique ID for the request context from the specified params
func GenerateRequestContextID(txHash []byte, msgIndex int64) tmbytes.HexBytes {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(msgIndex))
return append(txHash, bz...)
}
// SplitRequestContextID splits the given contextID to txHash and msgIndex
func SplitRequestContextID(contextID tmbytes.HexBytes) (tmbytes.HexBytes, int64, error) {
if len(contextID) != ContextIDLen/2 {
return nil, 0, errors.New("invalid request context ID")
}
txHash := contextID[0:32]
msgIndex := int64(binary.BigEndian.Uint64(contextID[32:40]))
return txHash, msgIndex, nil
}
// GenerateRequestID generates a unique request ID from the given params
func GenerateRequestID(
requestContextID tmbytes.HexBytes,
requestContextBatchCounter uint64,
requestHeight int64,
batchRequestIndex int16,
) tmbytes.HexBytes {
contextID := make([]byte, len(requestContextID))
copy(contextID, requestContextID)
bz := make([]byte, 18)
binary.BigEndian.PutUint64(bz, requestContextBatchCounter)
binary.BigEndian.PutUint64(bz[8:], uint64(requestHeight))
binary.BigEndian.PutUint16(bz[16:], uint16(batchRequestIndex))
return append(contextID, bz...)
}
// SplitRequestID splits the given requestID to contextID, batchCounter, requestHeight, batchRequestIndex
func SplitRequestID(requestID tmbytes.HexBytes) (tmbytes.HexBytes, uint64, int64, int16, error) {
if len(requestID) != RequestIDLen/2 {
return nil, 0, 0, 0, errors.New("invalid request ID")
}
contextID := requestID[0:40]
batchCounter := binary.BigEndian.Uint64(requestID[40:48])
requestHeight := int64(binary.BigEndian.Uint64(requestID[48:56]))
batchRequestIndex := int16(binary.BigEndian.Uint16(requestID[56:]))
return contextID, batchCounter, requestHeight, batchRequestIndex, nil
}