-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_state.go
518 lines (450 loc) · 19.1 KB
/
client_state.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package types
import (
"encoding/hex"
"fmt"
"github.com/ci123chain/ci123chain/pkg/abci/codec"
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
sdkerrors "github.com/ci123chain/ci123chain/pkg/abci/types/errors"
channeltypes "github.com/ci123chain/ci123chain/pkg/ibc/core/channel/types"
clienttypes "github.com/ci123chain/ci123chain/pkg/ibc/core/clients/types"
commitmenttypes "github.com/ci123chain/ci123chain/pkg/ibc/core/commitment/types"
connectiontypes "github.com/ci123chain/ci123chain/pkg/ibc/core/connection/types"
"github.com/ci123chain/ci123chain/pkg/ibc/core/exported"
"github.com/ci123chain/ci123chain/pkg/ibc/core/host"
ics23 "github.com/confio/ics23/go"
"github.com/pkg/errors"
"strings"
"time"
)
var _ exported.ClientState = (*ClientState)(nil)
//// ClientState from Tendermint tracks the current validator set, latest height,
//// and a possible frozen height.
//type ClientState struct {
// ChainId string `json:"chain_id,omitempty"`
// TrustLevel Fraction `json:"trust_level" yaml:"trust_level"`
// // duration of the period since the LastestTimestamp during which the
// // submitted headers are valid for upgrade
// TrustingPeriod time.Duration `json:"trusting_period" yaml:"trusting_period"`
// // duration of the staking unbonding period
// UnbondingPeriod time.Duration `json:"unbonding_period" yaml:"unbonding_period"`
// // defines how much new (untrusted) header's Time can drift into the future.
// MaxClockDrift time.Duration `json:"max_clock_drift" yaml:"max_clock_drift"`
// // Block height when the client was frozen due to a misbehaviour
// FrozenHeight clienttypes.Height `json:"frozen_height" yaml:"frozen_height"`
// // Latest height the client was updated to
// LatestHeight clienttypes.Height `json:"latest_height" yaml:"latest_height"`
// // Proof specifications used in verifying counterparty state
// ProofSpecs []*ics23.ProofSpec `json:"proof_specs,omitempty" yaml:"proof_specs"`
// // Path at which next upgraded client will be committed.
// // Each element corresponds to the key for a single CommitmentProof in the chained proof.
// // NOTE: ClientState must stored under `{upgradePath}/{upgradeHeight}/clientState`
// // ConsensusState must be stored under `{upgradepath}/{upgradeHeight}/consensusState`
// // For SDK chains using the default upgrade module, upgrade_path should be []string{"upgrade", "upgradedIBCState"}`
// UpgradePath []string `json:"upgrade_path,omitempty" yaml:"upgrade_path"`
// // This flag, when set to true, will allow governance to recover a client
// // which has expired
// AllowUpdateAfterExpiry bool `json:"allow_update_after_expiry,omitempty" yaml:"allow_update_after_expiry"`
// // This flag, when set to true, will allow governance to unfreeze a client
// // whose chain has experienced a misbehaviour event
// AllowUpdateAfterMisbehaviour bool `json:"allow_update_after_misbehaviour,omitempty" yaml:"allow_update_after_misbehaviour"`
//}
//
//func (m *ClientState) Reset() { *m = ClientState{} }
//func (m *ClientState) String() string { return proto.CompactTextString(m) }
//func (*ClientState) ProtoMessage() {}
//
//// Fraction defines the protobuf message types for tmmath.Fraction that only supports positive values.
//type Fraction struct {
// Numerator uint64 `json:"numerator,omitempty"`
// Denominator uint64 `json:"denominator,omitempty"`
//}
// NewClientState creates a new ClientState instance
func NewClientState(
chainID string, trustLevel Fraction,
trustingPeriod, ubdPeriod, maxClockDrift time.Duration,
latestHeight clienttypes.Height, specs []*ics23.ProofSpec,
upgradePath []string, allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour bool,
) *ClientState {
return &ClientState{
ChainId: chainID,
TrustLevel: trustLevel,
TrustingPeriod: trustingPeriod,
UnbondingPeriod: ubdPeriod,
MaxClockDrift: maxClockDrift,
LatestHeight: latestHeight,
FrozenHeight: clienttypes.ZeroHeight(),
ProofSpecs: specs,
UpgradePath: upgradePath,
AllowUpdateAfterExpiry: allowUpdateAfterExpiry,
AllowUpdateAfterMisbehaviour: allowUpdateAfterMisbehaviour,
}
}
// GetChainID returns the chain-id
func (cs ClientState) GetChainID() string {
return cs.ChainId
}
// ClientType is tendermint.
func (cs ClientState) ClientType() string {
return exported.Tendermint
}
// GetLatestHeight returns latest block height.
func (cs ClientState) GetLatestHeight() exported.Height {
return cs.LatestHeight
}
// IsFrozen returns true if the frozen height has been set.
func (cs ClientState) IsFrozen() bool {
return !cs.FrozenHeight.IsZero()
}
// GetFrozenHeight returns the height at which client is frozen
// NOTE: FrozenHeight is zero if client is unfrozen
func (cs ClientState) GetFrozenHeight() exported.Height {
return cs.FrozenHeight
}
// IsExpired returns whether or not the client has passed the trusting period since the last
// update (in which case no headers are considered valid).
func (cs ClientState) IsExpired(latestTimestamp, now time.Time) bool {
expirationTime := latestTimestamp.Add(cs.TrustingPeriod)
return !expirationTime.After(now)
}
// GetProofSpecs returns the format the client expects for proof verification
// as a string array specifying the proof types for each position in chained proof
func (cs ClientState) GetProofSpecs() []*ics23.ProofSpec {
return cs.ProofSpecs
}
// ZeroCustomFields returns a ClientState that is a copy of the current ClientState
// with all client customizable fields zeroed out
func (cs ClientState) ZeroCustomFields() exported.ClientState {
// copy over all chain-specified fields
// and leave custom fields empty
return &ClientState{
ChainId: cs.ChainId,
UnbondingPeriod: cs.UnbondingPeriod,
LatestHeight: cs.LatestHeight,
ProofSpecs: cs.ProofSpecs,
UpgradePath: cs.UpgradePath,
}
}
// Validate performs a basic validation of the client state fields.
func (cs ClientState) Validate() error {
if strings.TrimSpace(cs.ChainId) == "" {
return sdkerrors.Wrap(ErrInvalidChainID, "chain id cannot be empty string")
}
if cs.TrustingPeriod == 0 {
return sdkerrors.Wrap(ErrInvalidTrustingPeriod, "trusting period cannot be zero")
}
if cs.UnbondingPeriod == 0 {
return sdkerrors.Wrap(ErrInvalidUnbondingPeriod, "unbonding period cannot be zero")
}
if cs.MaxClockDrift == 0 {
return sdkerrors.Wrap(ErrInvalidMaxClockDrift, "max clock drift cannot be zero")
}
if cs.LatestHeight.RevisionHeight == 0 {
return sdkerrors.Wrapf(ErrInvalidHeaderHeight, "tendermint revision height cannot be zero")
}
if cs.TrustingPeriod >= cs.UnbondingPeriod {
return sdkerrors.Wrapf(
ErrInvalidTrustingPeriod,
"trusting period (%s) should be < unbonding period (%s)", cs.TrustingPeriod, cs.UnbondingPeriod,
)
}
if cs.ProofSpecs == nil {
return sdkerrors.Wrap(ErrInvalidProofSpecs, "proof specs cannot be nil for tm client")
}
for i, spec := range cs.ProofSpecs {
if spec == nil {
return sdkerrors.Wrapf(ErrInvalidProofSpecs, "proof spec cannot be nil at index: %d", i)
}
}
// UpgradePath may be empty, but if it isn't, each key must be non-empty
for i, k := range cs.UpgradePath {
if strings.TrimSpace(k) == "" {
return sdkerrors.Wrapf(clienttypes.ErrInvalidClient, fmt.Sprintf("key in upgrade path at index %d cannot be empty", i))
}
}
return nil
}
func (cs ClientState) Initialize(ctx sdk.Context, clientStore sdk.KVStore, consState exported.ConsensusState) error {
if _, ok := consState.(*ConsensusState); !ok {
return sdkerrors.Wrapf(clienttypes.ErrInvalidConsensus, "invalid initial consensus state. expected type: %T, got: %T",
&ConsensusState{}, consState)
}
SetProcessedTime(clientStore, cs.GetLatestHeight(), uint64(ctx.BlockHeader().Time.UnixNano()))
return nil
}
func (cs ClientState) VerifyUpgradeAndUpdateState(ctx sdk.Context,
cdc codec.BinaryMarshaler, store sdk.KVStore,
newClient exported.ClientState, proofUpgradeClient,
proofUpgradeConsState []byte) (exported.ClientState, exported.ConsensusState, error) {
return nil, nil, nil
}
func (cs ClientState) VerifyClientState(
store sdk.KVStore,
cdc codec.BinaryMarshaler,
height exported.Height,
prefix exported.Prefix,
counterpartyClientIdentifier string,
proof []byte,
clientState exported.ClientState) error {
merkleProof, provingConsensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
clientPrefixedPath := commitmenttypes.NewMerklePath(host.FullClientStatePath(counterpartyClientIdentifier))
path, err := commitmenttypes.ApplyPrefix(prefix, clientPrefixedPath)
if err != nil {
return err
}
if clientState == nil {
return sdkerrors.Wrap(clienttypes.ErrInvalidClient, "client state cannot be empty")
}
_, ok := clientState.(*ClientState)
if !ok {
return sdkerrors.Wrapf(clienttypes.ErrInvalidClient, "invalid client type %T, expected %T", clientState, &ClientState{})
}
bz, err := cdc.MarshalInterface(clientState)
if err != nil {
return err
}
return merkleProof.VerifyMembership(cs.ProofSpecs, provingConsensusState.GetRoot(), path, bz)
}
// VerifyConnectionState verifies a proof of the connection state of the
// specified connection end stored on the target machine.
func (cs ClientState) VerifyConnectionState(
store sdk.KVStore,
cdc codec.BinaryMarshaler,
height exported.Height,
prefix exported.Prefix,
proof []byte,
connectionID string,
connectionEnd exported.ConnectionI,
) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
connectionPath := commitmenttypes.NewMerklePath(host.ConnectionPath(connectionID))
path, err := commitmenttypes.ApplyPrefix(prefix, connectionPath)
if err != nil {
return err
}
connection, ok := connectionEnd.(connectiontypes.ConnectionEnd)
if !ok {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "invalid connection type %T", connectionEnd)
}
bz, err := cdc.MarshalBinaryBare(&connection)
if err != nil {
return err
}
if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil {
return err
}
return nil
}
func (cs ClientState) VerifyClientConsensusState(
store sdk.KVStore,
cdc codec.BinaryMarshaler,
height exported.Height,
counterpartyClientIdentifier string,
consensusHeight exported.Height, // todo ?
prefix exported.Prefix,
proof []byte,
consensusState exported.ConsensusState,
) error {
merkleProof, provingConsensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
clientPrefixedPath := commitmenttypes.NewMerklePath(host.FullConsensusStatePath(counterpartyClientIdentifier, consensusHeight))
path, err := commitmenttypes.ApplyPrefix(prefix, clientPrefixedPath)
if err != nil {
return err
}
if consensusState == nil {
return sdkerrors.Wrap(clienttypes.ErrInvalidConsensus, "consensus state cannot be empty")
}
_, ok := consensusState.(*ConsensusState)
if !ok {
return sdkerrors.Wrapf(clienttypes.ErrInvalidConsensus, "invalid consensus type %T, expected %T", consensusState, &ConsensusState{})
}
bz, err := cdc.MarshalInterface(consensusState)
if err != nil {
return err
}
if err := merkleProof.VerifyMembership(cs.ProofSpecs, provingConsensusState.GetRoot(), path, bz); err != nil {
return err
}
return nil
}
func (cs ClientState) VerifyChannelState(store sdk.KVStore,
cdc codec.BinaryMarshaler, height exported.Height,
prefix exported.Prefix, proof []byte,
portID, channelID string, channel exported.ChannelI) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
channelPath := commitmenttypes.NewMerklePath(host.ChannelPath(portID, channelID))
path, err := commitmenttypes.ApplyPrefix(prefix, channelPath)
if err != nil {
return err
}
channelEnd, ok := channel.(channeltypes.Channel)
if !ok {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "invalid channel type %T", channel)
}
bz, err := cdc.MarshalBinaryBare(&channelEnd)
if err != nil {
return err
}
if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil {
return err
}
return nil
}
// VerifyPacketAcknowledgement verifies a proof of an incoming packet
// acknowledgement at the specified port, specified channel, and specified sequence.
func (cs ClientState) VerifyPacketAcknowledgement(store sdk.KVStore, cdc codec.BinaryMarshaler, height exported.Height, currentTimestamp uint64, delayPeriod uint64,
prefix exported.Prefix, proof []byte, portID, channelID string, sequence uint64, acknowledgement []byte) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
// check delay period has passed
if err := verifyDelayPeriodPassed(store, height, currentTimestamp, delayPeriod); err != nil {
return err
}
ackPath := commitmenttypes.NewMerklePath(host.PacketAcknowledgementPath(portID, channelID, sequence))
path, err := commitmenttypes.ApplyPrefix(prefix, ackPath)
if err != nil {
return err
}
fmt.Println("$$$VerifyPacketAcknowledgement.proofHeight$$$:", height)
fmt.Println("$$$acknowledgementBytes$$$:", acknowledgement)
fmt.Println("$$$VerifyPacketAcknowledgement.root$$$:", hex.EncodeToString(consensusState.GetRoot().GetHash()))
if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, channeltypes.CommitAcknowledgement(acknowledgement)); err != nil {
return err
}
return nil
}
// private methods implements
// produceVerificationArgs perfoms the basic checks on the arguments that are
// shared between the verification functions and returns the unmarshalled
// merkle proof, the consensus state and an error if one occurred.
func produceVerificationArgs(
store sdk.KVStore,
cdc codec.BinaryMarshaler,
cs ClientState,
height exported.Height,
prefix exported.Prefix,
proof []byte,
) (merkleProof commitmenttypes.MerkleProof, consensusState *ConsensusState, err error) {
if cs.GetLatestHeight().LT(height) {
return commitmenttypes.MerkleProof{}, nil, sdkerrors.Wrapf(
sdkerrors.ErrInvalidHeight,
"client state height < proof height (%d < %d)", cs.GetLatestHeight(), height,
) }
if cs.IsFrozen() && !cs.FrozenHeight.GT(height) {
return commitmenttypes.MerkleProof{}, nil, clienttypes.ErrClientFrozen
}
if prefix == nil {
return commitmenttypes.MerkleProof{}, nil, sdkerrors.Wrap(commitmenttypes.ErrInvalidPrefix, "prefix cannot be empty")
}
_, ok := prefix.(*commitmenttypes.MerklePrefix)
if !ok {
return commitmenttypes.MerkleProof{}, nil, sdkerrors.Wrapf(commitmenttypes.ErrInvalidPrefix, "invalid prefix type %T, expected *MerklePrefix", prefix)
}
if err = codec.NewProtoCodec(commitmenttypes.CommitmentInterfaceRegistry).UnmarshalBinaryBare(proof, &merkleProof); err != nil {
return commitmenttypes.MerkleProof{}, nil, sdkerrors.Wrap(commitmenttypes.ErrInvalidProof, "failed to unmarshal proof into commitment merkle proof")
}
//if err = cdc.UnmarshalBinaryBare(proof, &merkleProof); err != nil {
//}
consensusState, err = GetConsensusState(store, cdc, height)
if err != nil {
return commitmenttypes.MerkleProof{}, nil, err
}
return merkleProof, consensusState, nil
}
func (cs ClientState) VerifyPacketCommitment(store sdk.KVStore, cdc codec.BinaryMarshaler, height exported.Height, currentTimestamp uint64, delayPeriod uint64, prefix exported.Prefix, proof []byte, portID, channelID string, sequence uint64, commitmentBytes []byte) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
// check delay period has passed
if err := verifyDelayPeriodPassed(store, height, currentTimestamp, delayPeriod); err != nil {
return err
}
commitmentPath := commitmenttypes.NewMerklePath(host.PacketCommitmentPath(portID, channelID, sequence))
path, err := commitmenttypes.ApplyPrefix(prefix, commitmentPath)
if err != nil {
return err
}
if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, commitmentBytes); err != nil {
return err
}
return nil
}
func (cs ClientState) VerifyPacketReceiptAbsence(store sdk.KVStore, cdc codec.BinaryMarshaler, height exported.Height, currentTimestamp uint64, delayPeriod uint64, prefix exported.Prefix, proof []byte, portID, channelID string, sequence uint64) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
// check delay period has passed
if err := verifyDelayPeriodPassed(store, height, currentTimestamp, delayPeriod); err != nil {
return err
}
receiptPath := commitmenttypes.NewMerklePath(host.PacketReceiptPath(portID, channelID, sequence))
path, err := commitmenttypes.ApplyPrefix(prefix, receiptPath)
if err != nil {
return err
}
if err := merkleProof.VerifyNonMembership(cs.ProofSpecs, consensusState.GetRoot(), path); err != nil {
return err
}
return nil
}
func (cs ClientState) VerifyNextSequenceRecv(store sdk.KVStore, cdc codec.BinaryMarshaler, height exported.Height, currentTimestamp uint64, delayPeriod uint64, prefix exported.Prefix, proof []byte, portID, channelID string, nextSequenceRecv uint64) error {
merkleProof, consensusState, err := produceVerificationArgs(store, cdc, cs, height, prefix, proof)
if err != nil {
return err
}
// check delay period has passed
if err := verifyDelayPeriodPassed(store, height, currentTimestamp, delayPeriod); err != nil {
return err
}
nextSequenceRecvPath := commitmenttypes.NewMerklePath(host.NextSequenceRecvPath(portID, channelID))
path, err := commitmenttypes.ApplyPrefix(prefix, nextSequenceRecvPath)
if err != nil {
return err
}
bz := sdk.Uint64ToBigEndian(nextSequenceRecv)
if err := merkleProof.VerifyMembership(cs.ProofSpecs, consensusState.GetRoot(), path, bz); err != nil {
return err
}
return nil
}
// verifyDelayPeriodPassed will ensure that at least delayPeriod amount of time has passed since consensus state was submitted
// before allowing verification to continue.
func verifyDelayPeriodPassed(store sdk.KVStore, proofHeight exported.Height, currentTimestamp, delayPeriod uint64) error {
// check that executing chain's timestamp has passed consensusState's processed time + delay period
processedTime, ok := GetProcessedTime(store, proofHeight)
if !ok {
return errors.Wrapf(ErrProcessedTimeNotFound, "processed time not found for height: %s", proofHeight)
}
validTime := processedTime + delayPeriod
// NOTE: delay period is inclusive, so if currentTimestamp is validTime, then we return no error
if validTime > currentTimestamp {
return errors.Wrapf(ErrDelayPeriodNotPassed, "cannot verify packet until time: %d, current time: %d",
validTime, currentTimestamp)
}
return nil
}
// GetProcessedTime gets the time (in nanoseconds) at which this chain received and processed a tendermint header.
// This is used to validate that a received packet has passed the delay period.
func GetProcessedTime(clientStore sdk.KVStore, height exported.Height) (uint64, bool) {
key := ProcessedTimeKey(height)
bz := clientStore.Get(key)
if bz == nil {
return 0, false
}
return sdk.BigEndianToUint64(bz), true
}