-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathrelay.go
262 lines (233 loc) · 9.64 KB
/
relay.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
package keeper
import (
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
channeltypes "github.com/cosmos/ibc-go/v3/modules/core/04-channel/types"
"github.com/cosmos/ibc-go/v3/modules/core/exported"
"github.com/cosmos/interchain-security/x/ccv/provider/types"
ccv "github.com/cosmos/interchain-security/x/ccv/types"
utils "github.com/cosmos/interchain-security/x/ccv/utils"
)
func removeStringFromSlice(slice []string, x string) (newSlice []string, numRemoved int) {
for _, y := range slice {
if x != y {
newSlice = append(newSlice, y)
}
}
return newSlice, len(slice) - len(newSlice)
}
// OnRecvVSCMaturedPacket handles a VSCMatured packet
func (k Keeper) OnRecvVSCMaturedPacket(
ctx sdk.Context,
packet channeltypes.Packet,
data ccv.VSCMaturedPacketData,
) exported.Acknowledgement {
// check that the channel is established
chainID, found := k.GetChannelToChain(ctx, packet.DestinationChannel)
if !found {
// VSCMatured packet was sent on a channel different than any of the established CCV channels
return utils.OnRecvPacketOnUnknownChannel(ctx, k.scopedKeeper, k.channelKeeper, packet)
}
// iterate over the unbonding operations mapped to (chainID, data.ValsetUpdateId)
unbondingOps, _ := k.GetUnbondingOpsFromIndex(ctx, chainID, data.ValsetUpdateId)
var maturedIds []uint64
for _, unbondingOp := range unbondingOps {
// remove consumer chain ID from unbonding op record
unbondingOp.UnbondingConsumerChains, _ = removeStringFromSlice(unbondingOp.UnbondingConsumerChains, chainID)
// If unbonding op is completely unbonded from all relevant consumer chains
if len(unbondingOp.UnbondingConsumerChains) == 0 {
// Store id of matured unbonding op for later completion of unbonding in staking module
maturedIds = append(maturedIds, unbondingOp.Id)
// Delete unbonding op
k.DeleteUnbondingOp(ctx, unbondingOp.Id)
} else {
k.SetUnbondingOp(ctx, unbondingOp)
}
}
k.AppendMaturedUnbondingOps(ctx, maturedIds)
// clean up index
k.DeleteUnbondingOpIndex(ctx, chainID, data.ValsetUpdateId)
ack := channeltypes.NewResultAcknowledgement([]byte{byte(1)})
return ack
}
// CompleteMaturedUnbondingOps attempts to complete all matured unbonding operations
func (k Keeper) CompleteMaturedUnbondingOps(ctx sdk.Context) {
ids, err := k.EmptyMaturedUnbondingOps(ctx)
if err != nil {
panic(fmt.Sprintf("could not get the list of matured unbonding ops: %s", err.Error()))
}
for _, id := range ids {
// Attempt to complete unbonding in staking module
err := k.stakingKeeper.UnbondingCanComplete(ctx, id)
if err != nil {
panic(fmt.Sprintf("could not complete unbonding op: %s", err.Error()))
}
}
}
// OnAcknowledgementPacket handles acknowledgments for sent VSC packets
func (k Keeper) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes.Packet, ack channeltypes.Acknowledgement) error {
if err := ack.GetError(); err != "" {
// Either the VSC packet data could not be successfully decoded
// or the VSC packet was sent on a channel other than the established
// provider channel and ChanCloseInit failed.
// Neither of these should ever happen.
if chainID, ok := k.GetChannelToChain(ctx, packet.SourceChannel); ok {
// stop consumer chain and uses the LockUnbondingOnTimeout flag
// to decide whether the unbonding operations should be released
return k.StopConsumerChain(ctx, chainID, k.GetLockUnbondingOnTimeout(ctx, chainID), false)
}
return sdkerrors.Wrapf(types.ErrUnknownConsumerChannelId, "recv ErrorAcknowledgement on unknown channel %s", packet.SourceChannel)
}
return nil
}
// OnTimeoutPacket aborts the transaction if no chain exists for the destination channel,
// otherwise it stops the chain
func (k Keeper) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet) error {
chainID, found := k.GetChannelToChain(ctx, packet.SourceChannel)
if !found {
// abort transaction
return sdkerrors.Wrap(
channeltypes.ErrInvalidChannelState,
packet.SourceChannel,
)
}
// stop consumer chain and uses the LockUnbondingOnTimeout flag
// to decide whether the unbonding operations should be released
return k.StopConsumerChain(ctx, chainID, k.GetLockUnbondingOnTimeout(ctx, chainID), false)
}
// SendValidatorUpdates sends latest validator updates to every registered consumer chain
func (k Keeper) SendValidatorUpdates(ctx sdk.Context) {
// get current ValidatorSetUpdateId
valUpdateID := k.GetValidatorSetUpdateId(ctx)
// get the validator updates from the staking module
valUpdates := k.stakingKeeper.GetValidatorUpdates(ctx)
k.IterateConsumerChains(ctx, func(ctx sdk.Context, chainID string) (stop bool) {
// check whether there is an established CCV channel to this consumer chain
if channelID, found := k.GetChainToChannel(ctx, chainID); found {
// send all the pending ValidatorSetChangePackets to the consumer chain
pendingPackets := k.EmptyPendingVSC(ctx, chainID)
for _, data := range pendingPackets {
// send packet over IBC
utils.SendIBCPacket(
ctx,
k.scopedKeeper,
k.channelKeeper,
channelID, // source channel id
types.PortID, // source port id
data.GetBytes(),
)
}
}
// check whether there are changes in the validator set;
// note that this also entails unbonding operations
// w/o changes in the voting power of the validators in the validator set
unbondingOps, _ := k.GetUnbondingOpsFromIndex(ctx, chainID, valUpdateID)
if len(valUpdates) != 0 || len(unbondingOps) != 0 {
// construct validator set change packet data
packetData := ccv.NewValidatorSetChangePacketData(valUpdates, valUpdateID, k.EmptySlashAcks(ctx, chainID))
// check whether there is an established CCV channel to this consumer chain
if channelID, found := k.GetChainToChannel(ctx, chainID); found {
// send this validator set change packet data to the consumer chain
utils.SendIBCPacket(
ctx,
k.scopedKeeper,
k.channelKeeper,
channelID, // source channel id
types.PortID, // source port id
packetData.GetBytes(),
)
} else {
// store the packet data to be sent once the CCV channel is established
k.AppendPendingVSC(ctx, chainID, packetData)
}
}
return false // do not stop the iteration
})
k.SetValsetUpdateBlockHeight(ctx, valUpdateID, uint64(ctx.BlockHeight()+1))
k.IncrementValidatorSetUpdateId(ctx)
}
// OnRecvSlashPacket slashes and jails the given validator in the packet data
func (k Keeper) OnRecvSlashPacket(ctx sdk.Context, packet channeltypes.Packet, data ccv.SlashPacketData) exported.Acknowledgement {
// check that the channel is established
chainID, found := k.GetChannelToChain(ctx, packet.DestinationChannel)
if !found {
// Slash packet was sent on a channel different than any of the established CCV channels
return utils.OnRecvPacketOnUnknownChannel(ctx, k.scopedKeeper, k.channelKeeper, packet)
}
// apply slashing
if _, err := k.HandleSlashPacket(ctx, chainID, data); err != nil {
errAck := channeltypes.NewErrorAcknowledgement(err.Error())
return &errAck
}
ack := channeltypes.NewResultAcknowledgement([]byte{byte(1)})
return ack
}
// HandleSlashPacket slash and jail a misbehaving validator according the infraction type
func (k Keeper) HandleSlashPacket(ctx sdk.Context, chainID string, data ccv.SlashPacketData) (success bool, err error) {
// map VSC ID to infraction height for the given chain ID
var infractionHeight uint64
if data.ValsetUpdateId == 0 {
infractionHeight = k.GetInitChainHeight(ctx, chainID)
} else {
infractionHeight = k.GetValsetUpdateBlockHeight(ctx, data.ValsetUpdateId)
}
// return if there isn't any initial chain height for the consumer chain
if infractionHeight == 0 {
return false, fmt.Errorf("cannot find infraction height matching the validator update id %d for chain %s", data.ValsetUpdateId, chainID)
}
// get the validator
consAddr := sdk.ConsAddress(data.Validator.Address)
validator, found := k.stakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
// make sure the validator is not yet unbonded;
// stakingKeeper.Slash() panics otherwise
if !found || validator.IsUnbonded() {
// TODO add warning log message
// fmt.Sprintf("consumer chain %s trying to slash unbonded validator %s", chainID, consAddr.String())
return false, nil
}
// tombstoned validators should not be slashed multiple times
if k.slashingKeeper.IsTombstoned(ctx, consAddr) {
return false, nil
}
// slash and jail validator according to their infraction type
// and using the provider chain parameters
var (
jailTime time.Time
slashFraction sdk.Dec
)
switch data.Infraction {
case stakingtypes.Downtime:
// set the downtime slash fraction and duration
// then append the validator address to the slash ack for its chain id
slashFraction = k.slashingKeeper.SlashFractionDowntime(ctx)
jailTime = ctx.BlockTime().Add(k.slashingKeeper.DowntimeJailDuration(ctx))
k.AppendSlashAck(ctx, chainID, consAddr.String())
case stakingtypes.DoubleSign:
// set double-signing slash fraction and infinite jail duration
// then tombstone the validator
slashFraction = k.slashingKeeper.SlashFractionDoubleSign(ctx)
jailTime = evidencetypes.DoubleSignJailEndTime
k.slashingKeeper.Tombstone(ctx, consAddr)
default:
return false, fmt.Errorf("invalid infraction type: %v", data.Infraction)
}
// slash validator
k.stakingKeeper.Slash(
ctx,
consAddr,
int64(infractionHeight),
data.Validator.Power,
slashFraction,
data.Infraction,
)
// jail validator
if !validator.IsJailed() {
k.stakingKeeper.Jail(ctx, consAddr)
}
k.slashingKeeper.JailUntil(ctx, consAddr, jailTime)
return true, nil
}