-
Notifications
You must be signed in to change notification settings - Fork 48
/
relay_app_links.go
260 lines (219 loc) · 7.43 KB
/
relay_app_links.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
package keeper
import (
"encoding/hex"
"fmt"
"strings"
"github.com/armon/go-metrics"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
clienttypes "github.com/cosmos/ibc-go/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/modules/core/04-channel/types"
host "github.com/cosmos/ibc-go/modules/core/24-host"
"github.com/desmos-labs/desmos/pkg/obi"
"github.com/desmos-labs/desmos/x/profiles/types"
oracletypes "github.com/desmos-labs/desmos/x/oracle/types"
)
// oracleScriptCallData represents the data that should be OBI-encoded and sent to perform an oracle request
type oracleScriptCallData struct {
Application string `obi:"application"`
CallData string `obi:"call_data"`
}
// resultData represents the data that is returned by the oracle script
type resultData struct {
Signature string `obi:"signature"`
Value string `obi:"value"`
}
// StartProfileConnection creates and sends an IBC packet containing the proper data allowing to call
// the Band Protocol oracle script so that the sender account can be verified using the given verification data.
// nolint:interfacer
func (k Keeper) StartProfileConnection(
ctx sdk.Context,
applicationData types.Data,
dataSourceCallData string,
sender sdk.AccAddress,
sourcePort,
sourceChannel string,
timeoutHeight clienttypes.Height,
timeoutTimestamp uint64,
) error {
sourceChannelEnd, found := k.channelKeeper.GetChannel(ctx, sourcePort, sourceChannel)
if !found {
return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", sourcePort, sourceChannel)
}
destinationPort := sourceChannelEnd.GetCounterparty().GetPortID()
destinationChannel := sourceChannelEnd.GetCounterparty().GetChannelID()
// Get the next sequence
sequence, found := k.channelKeeper.GetNextSequenceSend(ctx, sourcePort, sourceChannel)
if !found {
return sdkerrors.Wrapf(
channeltypes.ErrSequenceSendNotFound,
"source port: %s, source channel: %s", sourcePort, sourceChannel,
)
}
// Begin createOutgoingPacket logic
channelCap, ok := k.scopedKeeper.GetCapability(ctx, host.ChannelCapabilityPath(sourcePort, sourceChannel))
if !ok {
return sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability")
}
// Create the call data to be used
data := oracleScriptCallData{
Application: strings.ToLower(applicationData.Application),
CallData: dataSourceCallData,
}
params := k.GetParams(ctx)
oraclePrams := params.Oracle
// Serialize the call data using the OBI encoding
callDataBz, err := obi.Encode(data)
if err != nil {
return err
}
// Create the Oracle request packet data
clientID := sender.String() + "-" + applicationData.Application + "-" + applicationData.Username
packetData := oracletypes.NewOracleRequestPacketData(
clientID,
oracletypes.OracleScriptID(oraclePrams.ScriptID),
callDataBz,
oraclePrams.AskCount,
oraclePrams.MinCount,
oraclePrams.FeeAmount,
oraclePrams.PrepareGas,
oraclePrams.ExecuteGas,
)
// Create the IBC packet
packet := channeltypes.NewPacket(
packetData.GetBytes(),
sequence,
sourcePort,
sourceChannel,
destinationPort,
destinationChannel,
timeoutHeight,
timeoutTimestamp,
)
// Send the IBC packet
err = k.channelKeeper.SendPacket(ctx, channelCap, packet)
if err != nil {
return err
}
// Store the connection
err = k.SaveApplicationLink(ctx, types.NewApplicationLink(
sender.String(),
applicationData,
types.ApplicationLinkStateInitialized,
types.NewOracleRequest(
0,
oraclePrams.ScriptID,
types.NewOracleRequestCallData(applicationData.Application, dataSourceCallData),
clientID,
),
nil,
ctx.BlockTime(),
))
if err != nil {
return err
}
labels := []metrics.Label{
telemetry.NewLabel("destination-port", destinationPort),
telemetry.NewLabel("destination-channel", destinationChannel),
}
defer func() {
telemetry.IncrCounterWithLabels(
[]string{"ibc", types.ModuleName, "connect-profile"},
1,
labels,
)
}()
return nil
}
func (k Keeper) OnRecvApplicationLinkPacketData(
ctx sdk.Context,
data oracletypes.OracleResponsePacketData,
) error {
// Get the request by the client ID
link, err := k.GetApplicationLinkByClientID(ctx, data.ClientID)
if err != nil {
return err
}
switch data.ResolveStatus {
case oracletypes.RESOLVE_STATUS_EXPIRED:
link.State = types.AppLinkStateVerificationError
link.Result = types.NewErrorResult(types.ErrRequestExpired)
case oracletypes.RESOLVE_STATUS_FAILURE:
link.State = types.AppLinkStateVerificationError
link.Result = types.NewErrorResult(types.ErrRequestFailed)
case oracletypes.RESOLVE_STATUS_SUCCESS:
var result resultData
err = obi.Decode(data.Result, &result)
if err != nil {
return fmt.Errorf("error while decoding request result: %s", err)
}
// Verify the application username to make sure it's the same that is returned (avoid replay attacks)
if !strings.EqualFold(result.Value, link.Data.Username) {
link.State = types.AppLinkStateVerificationError
link.Result = types.NewErrorResult(types.ErrInvalidAppUsername)
return k.SaveApplicationLink(ctx, link)
}
// Verify the signature to make sure it's from the same user (avoid identity theft)
addr, err := sdk.AccAddressFromBech32(link.User)
if err != nil {
return err
}
acc := k.ak.GetAccount(ctx, addr)
sigBz, err := hex.DecodeString(result.Signature)
if err != nil {
return err
}
if !acc.GetPubKey().VerifySignature([]byte(result.Value), sigBz) {
link.State = types.AppLinkStateVerificationError
link.Result = types.NewErrorResult(types.ErrInvalidSignature)
return k.SaveApplicationLink(ctx, link)
}
link.State = types.AppLinkStateVerificationSuccess
link.Result = types.NewSuccessResult(result.Value, result.Signature)
}
return k.SaveApplicationLink(ctx, link)
}
func (k Keeper) OnOracleRequestAcknowledgementPacket(
ctx sdk.Context,
data oracletypes.OracleRequestPacketData,
ack channeltypes.Acknowledgement,
) error {
// Get the request by the client ID
link, err := k.GetApplicationLinkByClientID(ctx, data.ClientID)
if err != nil {
return err
}
switch res := ack.Response.(type) {
case *channeltypes.Acknowledgement_Error:
// The acknowledgment failed on the receiving chain.
// Update the state to ERROR and the result to an error one
link.State = types.AppLinkStateVerificationError
link.Result = types.NewErrorResult(res.Error)
case *channeltypes.Acknowledgement_Result:
// The acknowledgement succeeded on the receiving chain
// Set the state to STARTED
link.State = types.AppLinkStateVerificationStarted
var packetAck oracletypes.OracleRequestPacketAcknowledgement
err = types.ModuleCdc.UnmarshalJSON(res.Result, &packetAck)
if err != nil {
return fmt.Errorf("cannot unmarshal oracle request packet acknowledgment: %s", err)
}
// Set the oracle request ID returned from BAND
link.OracleRequest.ID = uint64(packetAck.RequestID)
}
return k.SaveApplicationLink(ctx, link)
}
// OnOracleRequestTimeoutPacket handles the OracleRequestPacketData instance that is sent when a request times out
func (k Keeper) OnOracleRequestTimeoutPacket(
ctx sdk.Context,
data oracletypes.OracleRequestPacketData,
) error {
// Get the request by the client ID
connection, err := k.GetApplicationLinkByClientID(ctx, data.ClientID)
if err != nil {
return err
}
connection.State = types.AppLinkStateVerificationTimedOut
return k.SaveApplicationLink(ctx, connection)
}