-
Notifications
You must be signed in to change notification settings - Fork 412
/
Copy pathtechnical_specification.md
2132 lines (1952 loc) · 91.5 KB
/
technical_specification.md
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- omit in toc -->
# CCV: Technical Specification
[↑ Back to main document](./README.md)
<!-- omit in toc -->
## Outline
- [Placing CCV within an ABCI Application](#placing-ccv-within-an-abci-application)
- [Data Structures](#data-structures)
- [External Data Structures](#external-data-structures)
- [CCV Data Structures](#ccv-data-structures)
- [CCV Packets](#ccv-packets)
- [CCV State](#ccv-state)
- [Sub-protocols](#sub-protocols)
- [Initialization](#initialization)
- [Channel Closing Handshake](#channel-closing-handshake)
- [Packet Relay](#packet-relay)
- [Validator Set Update](#validator-set-update)
- [Consumer Initiated Slashing](#consumer-initiated-slashing)
- [Reward Distribution](#reward-distribution)
## Placing CCV within an ABCI Application
[↑ Back to Outline](#outline)
Before describing the data structures and sub-protocols of the CCV protocol, we provide a short overview of the interfaces the CCV module implements and the interactions with the other ABCI application modules.
<!-- omit in toc -->
### Implemented Interfaces
- CCV is an **ABCI application module**, which means it MUST implement the logic to handle some of the messages received from the consensus engine via ABCI,
e.g., `InitChain`, `BeginBlock`, `EndBlock` (for more details, take a look at the [ABCI specification](https://github.com/tendermint/spec/tree/v0.7.1/spec/abci)).
In this specification we define the following methods that handle messages that are of particular interest to the CCV protocol:
- `InitGenesis()` -- Called when the chain is first started, on receiving an `InitChain` message from the consensus engine.
This is also where the application can inform the underlying consensus engine of the initial validator set.
- `BeginBlock()` -- Contains logic that is automatically triggered at the beginning of each block.
- `EndBlock()` -- Contains logic that is automatically triggered at the end of each block.
This is also where the application can inform the underlying consensus engine of changes in the validator set.
- CCV is an **IBC module**, which means it MUST implement the module callbacks interface defined in [ICS 26](../../core/ics-026-routing-module/README.md#module-callback-interface). The interface consists of a set of callbacks for
- channel opening handshake, which we describe in the [Initialization](#initialization) section;
- channel closing handshake, which we describe in the [Channel Closing Handshake](#channel-closing-handshake) section;
- and packet relay, which we describe in the [Packet Relay](#packet-relay) section.
<!-- omit in toc -->
### Interfacing Other Modules
- As an ABCI application module, the CCV module interacts with the underlying consensus engine through ABCI:
- On the provider chain,
- it initializes the application (e.g., binds to the expected IBC port) in the `InitGenesis()` method.
- On the consumer chain,
- it initializes the application (e.g., binds to the expected IBC port, creates a client of the provider chain) in the `InitGenesis()` method;
- it provides the validator updates in the `EndBlock()` method.
- As an IBC module, the CCV module interacts with Core IBC for functionalities regarding
- port allocation ([ICS 5](../../core/ics-005-port-allocation)) via `portKeeper`;
- channels and packet semantics ([ICS 4](../../core/ics-004-channel-and-packet-semantics)) via `channelKeeper`;
- connection semantics ([ICS 3](../../core/ics-003-connection-semantics)) via `connectionKeeper`;
- client semantics ([ICS 2](../../core/ics-002-client-semantics)) via `clientKeeper`.
- The consumer CCV module interacts with the IBC Token Transfer module ([ICS 20](../ics-020-fungible-token-transfer/README.md)) via `transferKeeper`.
- For the [Initialization sub-protocol](#initialization), the provider CCV module interacts with a Governance module by handling governance proposals to spawn new consumer chains.
If such proposals pass, then all validators on the provider chain MUST validate the consumer chain at spawn time;
otherwise they get slashed.
For an example of how governance proposals work, take a look at the [Governance module documentation](https://docs.cosmos.network/v0.44/modules/gov/) of Cosmos SDK.
- The provider CCV module interacts with a Staking module on the provider chain.
For an example of how staking works, take a look at the [Staking module documentation](https://docs.cosmos.network/v0.44/modules/staking/) of Cosmos SDK.
The interaction is defined by the following interface:
```typescript
interface StakingKeeper {
// get UnbondingPeriod from the provider Staking module
UnbondingTime(): Duration
// get validator updates from the provider Staking module
GetValidatorUpdates(): [ValidatorUpdate]
// request the Staking module to put on hold
// the completion of an unbonding operation
PutUnbondingOnHold(id: uint64)
// notify the Staking module of an unboding operation that
// has matured from the perspective of the consumer chains
UnbondingCanComplete(id: uint64)
}
```
- The provider CCV module interacts with a Slashing module on the provider chain.
For an example of how slashing works, take a look at the [Slashing module documentation](https://docs.cosmos.network/v0.44/modules/slashing/) of Cosmos SDK.
The interaction is defined by the following interface:
```typescript
interface SlashingKeeper {
// query the Slashing module for the slashing factor,
// which may be different for downtime infractions
GetSlashFactor(downtime: Bool): int64
// request the Slashing module to slash a validator
Slash(valAddress: string,
infractionHeight: int64,
power: int64,
slashFactor: int64)
// query the Slashing module for the jailing time,
// which may be different for downtime infractions
GetJailTime(downtime: Bool): int64
// request the Slashing module to jail a validator until time
JailUntil(valAddress: string, time: uint64)
}
```
- The following hook enables the provider CCV module to register operations to be execute when certain events occur within the provider Staking module:
```typescript
// invoked by the Staking module after
// initiating an unbonding operation
function AfterUnbondingInitiated(opId: uint64);
```
- The consumer CCV module defines the following hooks that enable other modules to register operations to execute when certain events have occurred within CCV:
```typescript
// invoked after a new validator is added to the validator set
function AfterCCValidatorBonded(valAddress: string);
// invoked after a validator is removed from the validator set
function AfterCCValidatorBeginUnbonding(valAddress: string);
```
## Data Structures
### External Data Structures
[↑ Back to Outline](#outline)
This section describes external data structures used by the CCV module.
The CCV module uses the ABCI `ValidatorUpdate` data structure, which consists of a validator and its power (for more details, take a look at the [ABCI specification](https://github.com/tendermint/spec/blob/v0.7.1/spec/abci/abci.md#data-types)), i.e.,
```typescript
interface ValidatorUpdate {
pubKey: PublicKey
power: int64
}
```
The provider chain sends to the consumer chain a list of `ValidatorUpdate`s, containing an entry for every validator that had its power updated.
The data structures required for creating clients (i.e., `ClientState`, `ConsensusState`) are defined in [ICS 2](../../core/ics-002-client-semantics).
In the context of CCV, every chain is uniquely defined by their chain ID and the validator set.
Thus, CCV requires the `ClientState` to contain the chain ID and the `ConsensusState` for a particular height to contain the validator set at that height.
In addition, the `ClientState` should contain the `UnbondingPeriod`.
For an example, take a look at the `ClientState` and `ConsensusState` defined in [ICS 7](../../client/ics-007-tendermint-client).
### CCV Data Structures
[↑ Back to Outline](#outline)
The CCV module is initialized through the `InitGenesis` method when the chain is first started. The initialization is done from a genesis state. This is the case for both provider and consumer chains:
- On the provider chain, the genesis state is described by the following interface:
```typescript
interface ProviderGenesisState {
// a list of existing consumer chains
consumerStates: [ConsumerState]
}
```
with `ConsumerState` defined as
```typescript
interface ConsumerState {
chainId: string
channelId: Identifier
}
```
- On the consumer chain, the genesis state is described by the following interface:
```typescript
interface ConsumerGenesisState {
providerClientState: ClientState
providerConsensusState: ConsensusState
initialValSet: [ValidatorUpdate]
}
```
The provider CCV module handles governance proposals to spawn new consumer chains and to stop existing consumer chains.
While the structure of governance proposals is specific to every ABCI application (for an example, see the `Proposal` interface in the [Governance module documentation](https://docs.cosmos.network/v0.44/modules/gov/) of Cosmos SDK),
this specification expects the following fields to be part of the proposals to spawn new consumer chains (i.e., `SpawnConsumerChainProposal`) and to stop existing ones (i.e., `StopConsumerChainProposal`):
```typescript
interface SpawnConsumerChainProposal {
chainId: string
initialHeight: Height
spawnTime: Timestamp
lockUnbondingOnTimeout: Bool
}
```
- `chainId` is the proposed chain ID of the new consumer chain. It must be different from all other consumer chain IDs of the executing provider chain.
- `initialHeight` is the proposed initial height of new consumer chain.
For an example, take a look at the `Height` defined in [ICS 7](../../client/ics-007-tendermint-client).
- `spawnTime` is the time on the provider chain at which the consumer chain genesis is finalized and all validators are responsible to start their consumer chain validator node.
- `lockUnbondingOnTimeout` is a boolean value that indicates whether the funds corresponding to the outstanding unbonding operations are to be released in case of a timeout. In case `lockUnbondingOnTimeout == true`, a governance proposal to stop the timed out consumer chain would be necessary to release the locked funds.
```typescript
interface StopConsumerChainProposal {
chainId: string
stopTime: Timestamp
}
```
- `chainId` is the chain ID of the consumer chain to be removed. It must be the ID of an existing consumer chain of the executing provider chain.
- `stopTime` is the time on the provider chain at which all validators are responsible to stop their consumer chain validator node.
During the CCV channel opening handshake, the provider chain adds the address of its distribution module account to the channel version as metadata (as described in [ICS 4](../../core/ics-004-channel-and-packet-semantics/README.md#definitions)).
The metadata structure is described by the following interface:
```typescript
interface CCVHandshakeMetadata {
providerDistributionAccount: string // the account's address
version: string
}
```
This specification assumes that the provider CCV module has access to the address of the distribution module account through the `GetDistributionAccountAddress()` method. For an example, take a look at the [auth module](https://docs.cosmos.network/v0.44/modules/auth/) of Cosmos SDK.
During the CCV channel opening handshake, the provider chain adds the address of its distribution module account to the channel version as metadata (as described in [ICS 4](../../core/ics-004-channel-and-packet-semantics/README.md#definitions)).
The metadata structure is described by the following interface:
```typescript
interface CCVHandshakeMetadata {
providerDistributionAccount: string // the account's address
version: string
}
```
This specification assumes that the provider CCV module has access to the address of the distribution module account through the `GetDistributionAccountAddress()` method. For an example, take a look at the [auth module](https://docs.cosmos.network/v0.44/modules/auth/) of Cosmos SDK.
### CCV Packets
[↑ Back to Outline](#outline)
The structure of the packets sent through the CCV channel is defined by the `Packet` interface in [ICS 4](../../core/ics-004-channel-and-packet-semantics).
The following packet data types are required by the CCV module:
- `VSCPacketData` contains a list of validator updates, i.e.,
```typescript
interface VSCPacketData {
// the id of this VSC
id: uint64
// validator updates
updates: [ValidatorUpdate]
// slash requests acknowledgements,
// i.e., list of validator addresses
slashAcks: [string]
}
```
- `VSCMaturedPacketData` contains the ID of the VSC that reached maturity, i.e.,
```typescript
interface VSCMaturedPacketData {
id: uint64 // the id of the VSC that reached maturity
}
```
- `SlashPacketData` contains a request to slash a validator, i.e.,
```typescript
interface SlashPacketData {
valAddress: string // validator address, i.e., the hash of its public key
valPower: int64
vscId: uint64
downtime: Bool
}
```
> Note that for brevity we use e.g., `VSCPacket` to refer to a packet with `VSCPacketData` as its data.
Packets are acknowledged by the remote side by sending back an `Acknowledgement` that contains either a result (in case of success) or an error (as defined in [ICS 4](../../core/ics-004-channel-and-packet-semantics/README.md#acknowledgement-envelope)).
The following acknowledgement types are required by the CCV module:
```typescript
type VSCPacketAcknowledgement = VSCPacketSuccess | VSCPacketError;
type VSCMaturedPacketAcknowledgement = VSCMaturedPacketSuccess | VSCMaturedPacketError;
type SlashPacketAcknowledgement = SlashPacketSuccess | SlashPacketError;
type PacketAcknowledgement = PacketSuccess | PacketError; // general ack
```
### CCV State
[↑ Back to Outline](#outline)
This section describes the internal state of the CCV module. For simplicity, the state is described by a set of variables; for each variable, both the type and a brief description is provided. In practice, all the state (except for hardcoded constants, e.g., `ProviderPortId`) is stored in a key/value store (KVS). The host state machine provides a KVS interface with three functions, i.e., `get()`, `set()`, and `delete()` (as defined in [ICS 24](../../core/ics-024-host-requirements)).
- `ccvVersion = "ccv-1"` is the CCV expected version. Both the provider and the consumer chains need to agree on this version.
- `zeroTimeoutHeight = {0,0}` is the `timeoutHeight` (as defined in [ICS 4](../../core/ics-004-channel-and-packet-semantics)) used by CCV for sending packets. Note that CCV uses `ccvTimeoutTimestamp` for sending CCV packets and `transferTimeoutTimestamp` for transferring tokens.
- `ccvTimeoutTimestamp: uint64` is the `timeoutTimestamp` (as defined in [ICS 4](../../core/ics-004-channel-and-packet-semantics)) for sending CCV packets. The CCV protocol is responsible of setting `ccvTimeoutTimestamp` such that the *Correct Relayer* assumption is feasible.
- `transferTimeoutTimestamp: uint64` is the `timeoutTimestamp` (as defined in [ICS 4](../../core/ics-004-channel-and-packet-semantics)) for transferring tokens.
<!-- omit in toc -->
#### State on the provider chain
- `ProviderPortId = "provider"` is the port ID the provider CCV module is expected to bind to.
- `pendingSpawnProposals: [SpawnConsumerChainProposal]` is a list of pending governance proposals to spawn new consumer chains.
- `pendingStopProposals: [StopConsumerChainProposal]` is a list of pending governance proposals to stop existing consumer chains.
Both lists of pending governance proposals expose the following interface:
```typescript
interface [Proposal] {
// append a proposal to the list; the list is modified
Append(p: Proposal)
// remove a proposal from the list; the list is modified
Remove(p: Proposal)
}
```
- `lockUnbondingOnTimeout: Map<string, Bool>` is a mapping from consumer chain IDs to the boolean values indicating whether the funds corresponding to the in progress unbonding operations are to be released in case of a timeout.
- `chainToClient: Map<string, Identifier>` is a mapping from consumer chain IDs to the associated client IDs.
- `chainToChannel: Map<string, Identifier>` is a mapping from consumer chain IDs to the CCV channel IDs.
- `channelToChain: Map<Identifier, string>` is a mapping from CCV channel IDs to consumer chain IDs.
- `pendingVSCPackets: Map<string, [VSCPacketData]>` is a mapping from consumer chain IDs to a list of pending `VSCPacketData`s that must be sent to the consumer chain once the CCV channel is established. The map exposes the following interface:
```typescript
interface Map<string, [VSCPacketData]> {
// append a VSCPacketData to the list mapped to chainId;
// the list is modified
Append(chainId: string, data: VSCPacketData)
// remove all the VSCPacketData mapped to chainId;
// the list is modified
Remove(chainId: string)
}
- `vscId: uint64` is a monotonic strictly increasing and positive ID that is used to uniquely identify the VSCs sent to the consumer chains.
Note that `0` is used as a special ID for the mapping from consumer heights to provider heights.
- `initialHeights: Map<string, Height>` is a mapping from consumer chain IDs to the heights on the provider chain.
For every consumer chain, the mapping stores the height when the CCV channel to that consumer chain is established.
Note that the provider validator set at this height matches the validator set at the height when the first VSC is provided to that consumer chain.
It enables the mapping from consumer heights to provider heights.
- `VSCtoH: Map<uint64, Height>` is a mapping from VSC IDs to heights on the provider chain. It enables the mapping from consumer heights to provider heights,
i.e., the voting power at height `VSCtoH[id]` on the provider chain was last updated by the validator updates contained in the VSC with ID `id`.
- `unbondingOps: Map<uint64, UnbondingOperation>` is a mapping that enables accessing for every unbonding operation the list of consumer chains that are still unbonding. When unbonding operations are initiated, the Staking module calls the `AfterUnbondingInitiated()` [hook](#ccv-pcf-hook-afubopcr1); this leads to the creation of a new `UnbondingOperation`, which is defined as
```typescript
interface UnbondingOperation {
id: uint64
// list of consumer chain IDs that are still unbonding
unbondingChainIds: [string]
}
```
- `vscToUnbondingOps: Map<(string, uint64), [uint64]>` is a mapping from `(chainId, vscId)` tuples to a list of unbonding operation IDs.
It enables the provider CCV module to match a `VSCMaturedPacket{vscId}`, received from a consumer chain with `chainId`, with the corresponding unbonding operations.
As a result, `chainId` can be removed from the list of consumer chains that are still unbonding these operations.
For more details see how received `VSCMaturedPacket`s [are handled](#ccv-pcf-rcvmat1).
- `slashRequests: Map<string, [string]>` is a mapping from `chainId`s to lists of validator addresses,
i.e., `slashRequests[chainId]` contains all the validator addresses for which the provider chain received slash requests from the consumer chain with `chainId`.
<!-- omit in toc -->
#### State on the consumer chain
- `ConsumerPortId = "consumer"` is the port ID the consumer CCV module is expected to bind to.
- `providerClient: Identifier` identifies the client of the provider chain (on the consumer chain) that the CCV channel is build upon.
- `providerChannel: Identifier` identifies the consumer's channel end of the CCV channel.
- `validatorSet: <string, CrossChainValidator>` is a mapping that stores the validators in the validator set of the consumer chain. Each validator is described by a `CrossChainValidator` data structure, which is defined as
```typescript
interface CrossChainValidator {
address: string // validator address, i.e., the hash of its public key
power: int64
}
```
- `pendingChanges: [ValidatorUpdate]` is a list of `ValidatorUpdate`s received, but not yet applied to the validator set.
It is emptied on every `EndBlock()`. The list exposes the following interface:
```typescript
interface [ValidatorUpdate] {
// append updates to the list;
// the list is modified
Append(updates: [ValidatorUpdate])
// return an aggregated list of updates, i.e.,
// keep only the latest update per validator;
// the original list is not modified
Aggregate(): [ValidatorUpdate]
// remove all the updates from the list;
// the list is modified
RemoveAll()
}
```
- `HtoVSC: Map<Height, uint64>` is a mapping from consumer chain heights to VSC IDs. It enables the mapping from consumer heights to provider heights., i.e.,
- if `HtoVSC[h] == 0`, then the voting power on the consumer chain at height `h` was setup at genesis during Channel Initialization;
- otherwise, the voting power on the consumer chain at height `h` was updated by the VSC with ID `HtoVSC[h]`.
- `maturingVSCs: [(uint64, uint64)]` is a list of `(id, ts)` tuples, where `id` is the ID of a VSC received via a `VSCPacket` and `ts` is the timestamp at which the VSC reaches maturity on the consumer chain.
The list is used to keep track of when unbonding operations are matured on the consumer chain. It exposes the following interface:
```typescript
interface [(uint64, uint64)] {
// add a VSC id with its maturity timestamp to the list;
// the list is modified
Add(id: uint64, ts: uint64)
// return the list sorted by the maturity timestamps;
// the original list is not modified
SortedByMaturityTime(): [(uint64, uint64)]
// remove (id, ts) from the list;
// the list is modified
Remove(id: uint64, ts: uint64)
}
```
- `pendingSlashRequests: [SlashRequest]` is a list of pending `SlashRequest`s that must be sent to the provider chain once the CCV channel is established. A `SlashRequest` consist of a `SlashPacketData` and a flag indicating whether the request is for downtime slashing. The list exposes the following interface:
```typescript
interface SlashRequest {
data: SlashPacketData
downtime: Bool
}
interface [SlashRequest] {
// append a SlashRequest to the list;
// the list is modified
Append(data: SlashRequest)
// return the reverse list, i.e., latest SlashRequest first;
// the original list is not modified
Reverse(): [SlashRequest]
// remove all the SlashRequest;
// the list is modified
RemoveAll()
}
```
- `outstandingDowntime: <string, Bool>` is a mapping from validator addresses to boolean values.
`outstandingDowntime[valAddr] == TRUE` entails that the consumer chain sent a request to slash for downtime the validator with address `valAddr`.
`outstandingDowntime[valAddr]` is set to false once the consumer chain receives a confirmation that the slash request was received by the provider chain, i.e., a `VSCPacket` that contains `valAddr` in `slashAcks`.
The mapping enables the consumer CCV module to avoid sending to the provider chain multiple slashing requests for the same downtime infraction.
- `providerDistributionAccount: string` is the address of the distribution module account on the provider chain. It enables the consumer chain to transfer rewards to the provider chain.
- `distributionChannelId: Identifier` is the ID of the distribution token transfer channel used for sending rewards to the provider chain.
- `BlocksPerDistributionTransfer: int64` is the interval (in number of blocks) between two distribution token transfers.
- `lastDistributionTransferHeight: Height` is the block height of the last distribution token transfer.
- `ccvAccount: string` is the address of the CCV module account where a fraction of the consumer chain rewards are collected before being transferred to the provider chain.
## Sub-protocols
To express the error conditions, the following specification of the sub-protocols uses the exception system of the host state machine, which is exposed through two functions (as defined in [ICS 24](../../core/ics-024-host-requirements)): `abortTransactionUnless` and `abortSystemUnless`.
### Initialization
[↑ Back to Outline](#outline)
The *initialization* sub-protocol enables a provider chain and a consumer chain to create a CCV channel -- a unique, ordered IBC channel for exchanging packets. As a prerequisite, the initialization sub-protocol MUST create two IBC clients, one on the provider chain to the consumer chain and one on the consumer chain to the provider chain. This is necessary to verify the identity of the two chains (as long as the clients are trusted).
<!-- omit in toc -->
#### **[CCV-PCF-INITG.1]**
```typescript
// PCF: Provider Chain Function
// implements the AppModule interface
function InitGenesis(state: ProviderGenesisState): [ValidatorUpdate] {
// bind to ProviderPortId port
err = portKeeper.BindPort(ProviderPortId)
// check whether the capability for the port can be claimed
abortSystemUnless(err == nil)
foreach cs in state.consumerStates {
abortSystemUnless(validateChannelIdentifier(cs.channelId))
chainToChannel[cs.chainId] = cs.channelId
channelToChain[cs.channelId] = cc.chainId
}
// do not return anything to the consensus engine
return []
}
```
- **Caller**
- The ABCI application.
- **Trigger Event**
- An `InitChain` message is received from the consensus engine; the `InitChain` message is sent when the provider chain is first started.
- **Precondition**
- The provider CCV module is in the initial state.
- **Postcondition**
- The capability for the port `ProviderPortId` is claimed.
- For each consumer state in the `ProviderGenesisState`, the initial state is set, i.e., the following mappings `chainToChannel`, `channelToChain` are set.
- **Error Condition**
- The capability for the port `ProviderPortId` cannot be claimed.
- For any consumer state in the `ProviderGenesisState`, the channel ID is not valid (cf. the validation function defined in [ICS 4](../../core/ics-004-channel-and-packet-semantics)).
<!-- omit in toc -->
#### **[CCV-PCF-SPCCPROP.1]**
```typescript
// PCF: Provider Chain Function
// implements governance proposal Handler
function SpawnConsumerChainProposalHandler(p: SpawnConsumerChainProposal) {
if currentTimestamp() > p.spawnTime {
CreateConsumerClient(p)
}
else {
// store the proposal as a pending spawn proposal
pendingSpawnProposals.Append(p)
}
}
```
- **Caller**
- `EndBlock()` method of Governance module.
- **Trigger Event**
- A governance proposal `SpawnConsumerChainProposal` has passed (i.e., it got the necessary votes).
- **Precondition**
- True.
- **Postcondition**
- If the spawn time has already passed, `CreateConsumerClient(p)` is invoked, with `p` the `SpawnConsumerChainProposal`.
- Otherwise, the proposal is appended to the list of pending spawn proposals, i.e., `pendingSpawnProposals`.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-PCF-CRCLIENT.1]**
```typescript
// PCF: Provider Chain Function
// Utility method
function CreateConsumerClient(p: SpawnConsumerChainProposal) {
// create client state
clientState = ClientState{
chainId: p.chainId,
// get UnbondingPeriod from provider Staking module
// TODO governance and CCV params
// see https://github.com/cosmos/ibc/issues/673
unbondingPeriod: stakingKeeper.UnbondingTime(),
// the height when the client was last updated
latestHeight: p.initialHeight,
}
// create consensus state;
// the validator set is the same as the validator set
// from own consensus state at current height
ownConsensusState = getConsensusState(getCurrentHeight())
consensusState = ConsensusState{
validatorSet: ownConsensusState.validatorSet,
}
// create consumer chain client and store it
clientId = clientKeeper.CreateClient(clientState, consensusState)
chainToClient[p.chainId] = clientId
// store lockUnbondingOnTimeout flag
lockUnbondingOnTimeout[p.chainId] = p.lockUnbondingOnTimeout
}
```
- **Caller**
- Either `SpawnConsumerChainProposalHandler` (see [CCV-PCF-SPCCPROP.1](#ccv-pcf-spccprop1)) or `BeginBlock()` (see [CCV-PCF-BBLOCK.1](#ccv-pcf-bblock1)).
- **Trigger Event**
- A governance proposal `SpawnConsumerChainProposal` `p` has passed (i.e., it got the necessary votes).
- **Precondition**
- `currentTimestamp() > p.spawnTime`.
- **Postcondition**
- A client state is created with `chainId = p.chainId` and `unbondingPeriod` set to the `UnbondingPeriod` obtained from the provider Staking module.
- A consensus state is created with `validatorSet` set to the validator set the provider chain own consensus state at current height.
- A client of the consumer chain is created and the client ID is added to `chainToClient`.
- `lockUnbondingOnTimeout[p.chainId]` is set to `p.lockUnbondingOnTimeout`.
- **Error Condition**
- None.
> **Note:** Creating a client of a remote chain requires a `ClientState` and a `ConsensusState` (for an example, take a look at [ICS 7](../../client/ics-007-tendermint-client)).
> `ConsensusState` requires setting a validator set of the remote chain.
> The provider chain uses the fact that the validator set of the consumer chain is the same as its own validator set.
> The rest of information to create a `ClientState` it receives through the governance proposal.
<!-- omit in toc -->
#### **[CCV-PCF-STCCPROP.1]**
> TODO Move function to another place, i.e., restructuring.
```typescript
// PCF: Provider Chain Function
// implements governance proposal Handler
function StopConsumerChainProposalHandler(p: StopConsumerChainProposal) {
if currentTimestamp() > p.stopTime {
// stop the consumer chain and do not lock the unbonding
StopConsumerChain(p.chainId, false)
}
else {
// store the proposal as a pending stop proposal
pendingStopProposals.Append(p)
}
}
```
- **Caller**
- `EndBlock()` method of Governance module.
- **Trigger Event**
- A governance proposal `StopConsumerChainProposal` has passed (i.e., it got the necessary votes).
- **Precondition**
- True.
- **Postcondition**
- If the spawn time has already passed, `StopConsumerChain(p.chainId, false)` is invoked, with `p` the `StopConsumerChainProposal`.
- Otherwise, the proposal is appended to the list of pending stop proposals, i.e., `pendingStopProposals`.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-PCF-STCC.1]**
```typescript
// PCF: Provider Chain Function
function StopConsumerChain(chainId: string, lockUnbonding: Bool) {
// cleanup state
chainToClient.Remove(chainId)
lockUnbondingOnTimeout.Remove(chainId)
if chainId IN chainToChannel.Keys() {
// CCV channel is established
channelToChain.Remove(chainToChannel[chainId])
channelKeeper.ChanCloseInit(chainToChannel[chainId])
chainToChannel.Remove(chainId)
}
pendingVSCPackets.Remove(chainId)
initH.Remove(chainId)
slashRequests.Remove(chainId)
if !lockUnbonding {
// remove chainId form all outstanding unbonding operations
foreach id IN vscToUnbondingOps[(chainId, _)] {
unbondingOps[id].unbondingChainIds.Remove(chainId)
}
// clean up vscToUnbondingOps mapping
vscToUnbondingOps.Remove((chainId, _))
}
}
```
- **Caller**
- `StopConsumerChainProposalHandler` (see [CCV-PCF-STCCPROP.1](#ccv-pcf-stccprop1))
or `BeginBlock()` (see [CCV-PCF-BBLOCK.1](#ccv-pcf-bblock1))
or `onTimeoutVSCPacket()` (see [CCV-PCF-TOVSC.1](#ccv-pcf-tovsc1)).
- **Trigger Event**
- Either a governance proposal to stop the consumer chain with `chainId` has passed (i.e., it got the necessary votes) or a packet sent on the CCV channel to the consumer chain with `chainId` has timed out.
- **Precondition**
- True.
- **Postcondition**
- The client ID mapped to `chainId` in `chainToClient` is removed.
- The value mapped to `chainId` in `lockUnbondingOnTimeout` is removed.
- If the CCV channel to the consumer chain with `chainId` is established, then
- the chain ID mapped to `chainToChannel[chainId]` in `channelToChain` is removed;
- the channel closing handshake is initiated for the CCV channel;
- the channel ID mapped to `chainId` in `chainToChannel` is removed.
- All the `VSCPacketData` mapped to `chainId` in `pendingVSCPackets` are removed.
- The height mapped to `chainId` in `initH` is removed.
- `slashRequests[chainId]` is emptied.
- If `lockUnbonding == false`, then
- `chainId` is removed from all outstanding unbonding operations;
- all the entries with `chainId` are removed from the `vscToUnbondingOps` mapping.
- **Error Condition**
- None
> **Note**: Invoking `StopConsumerChain(chainId, lockUnbonding)` with `lockUnbonding == FALSE` entails that all outstanding unbonding operations can complete before the `UnbondingPeriod` elapses on the consumer chain with `chainId`.
> Thus, invoking `StopConsumerChain(chainId, false)` for any `chainId` MAY violate the *Bond-Based Consumer Voting Power* and *Slashable Consumer Misbehavior* properties (see the [System Properties](./system_model_and_properties.md#system-properties) section).
>
> `StopConsumerChain(chainId, false)` is invoked in two scenarios (see Trigger Event above).
> - In the first scenario (i.e., a governance proposal to stop the consumer chain with `chainId`), the validators on the provider chain MUST make sure that it is safe to stop the consumer chain.
> Since a governance proposal needs a majority of the voting power to pass, the safety of invoking `StopConsumerChain(chainId, false)` is ensured by the *Safe Blockchain* assumption (see the [Assumptions](./system_model_and_properties.md#assumptions) section).
>
> - The second scenario (i.e., a timeout) is only possible if the *Correct Relayer* assumption is violated (see the [Assumptions](./system_model_and_properties.md#assumptions) section),
> which is necessary to guarantee both the *Bond-Based Consumer Voting Power* and *Slashable Consumer Misbehavior* properties (see the [Assumptions](./system_model_and_properties.md#correctness-reasoning) section).
<!-- omit in toc -->
#### **[CCV-PCF-COINIT.1]**
```typescript
// PCF: Provider Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenInit(
order: ChannelOrder,
connectionHops: [Identifier],
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyPortIdentifier: Identifier,
counterpartyChannelIdentifier: Identifier,
version: string): string {
// the channel handshake MUST be initiated by consumer chain
abortTransactionUnless(FALSE)
}
```
- **Caller**
- The provider IBC routing module.
- **Trigger Event**
- The provider IBC routing module receives a `ChanOpenInit` message on a port the provider CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is always aborted; hence, the state is not changed.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-PCF-COTRY.1]**
```typescript
// PCF: Provider Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenTry(
order: ChannelOrder,
connectionHops: [Identifier],
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyPortIdentifier: Identifier,
counterpartyChannelIdentifier: Identifier,
counterpartyVersion: string): string {
// validate parameters:
// - only ordered channels allowed
abortTransactionUnless(order == ORDERED)
// - require the portIdentifier to be the port ID the CCV module is bound to
abortTransactionUnless(portIdentifier == ProviderPortId)
// assert that the counterpartyPortIdentifier matches
// the expected consumer port ID
abortTransactionUnless(counterpartyPortIdentifier == ConsumerPortId)
// assert that the counterpartyVersion matches the expected version
abortTransactionUnless(counterpartyVersion == ccvVersion)
// get the client state associated with this client ID in order
// to get access to the consumer chain ID
clientId = getClient(channelIdentifier)
clientState = clientKeeper.GetClientState(clientId)
// require the CCV channel to be built on top
// of the expected client of the consumer chain
abortTransactionUnless(chainToClient[clientState.chainId] == clientId)
// require that no other CCV channel exists for this consumer chain
abortTransactionUnless(clientState.chainId NOTIN chainToChannel.Keys())
return CCVHandshakeMetadata{
providerDistributionAccount: GetDistributionAccountAddress(),
version: ccvVersion
}
}
```
- **Caller**
- The provider IBC routing module.
- **Trigger Event**
- The provider IBC routing module receives a `ChanOpenTry` message on a port the provider CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is aborted if any of the following conditions are true:
- the channel is not ordered;
- `portIdentifier != ProviderPortId`;
- `counterpartyPortIdentifier != ConsumerPortId`;
- `counterpartyVersion != ccvVersion`;
- the channel is not built on top of the client created for this consumer chain;
- another CCV channel for this consumer chain already exists.
- A `CCVHandshakeMetadata` is returned, with `providerDistributionAccount` set to the the address of the distribution module account on the provider chain and `version` set to `ccvVersion`.
- The state is not changed.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-PCF-COACK.1]**
```typescript
// PCF: Provider Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenAck(
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyVersion: string) {
// the channel handshake MUST be initiated by consumer chain
abortTransactionUnless(FALSE)
}
```
- **Caller**
- The provider IBC routing module.
- **Trigger Event**
- The provider IBC routing module receives a `ChanOpenAck` message on a port the provider CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is always aborted; hence, the state is not changed.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-PCF-COCONFIRM.1]**
```typescript
// PCF: Provider Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenConfirm(
portIdentifier: Identifier,
channelIdentifier: Identifier) {
// get the client state associated with this client ID in order
// to get access to the consumer chain ID
clientId = getClient(channelIdentifier)
clientState = clientKeeper.GetClientState(clientId)
// Verify that there isn't already a CCV channel for the consumer chain
// If there is, then close the channel.
if clientState.chainId IN chainToChannel {
channelKeeper.ChanCloseInit(channelIdentifier)
abortTransactionUnless(FALSE)
}
// set channel mappings
chainToChannel[clientState.chainId] = channelIdentifier
channelToChain[channelIdentifier] = clientState.chainId
// set initialHeights for this consumer chain
initialHeights[chainId] = getCurrentHeight()
}
```
- **Caller**
- The provider IBC routing module.
- **Trigger Event**
- The provider IBC routing module receives a `ChanOpenConfirm` message on a port the provider CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- If a CCV channel for this consumer chain already exists, then
- the channel closing handshake is initiated for the underlying channel;
- the transaction is aborted.
- Otherwise,
- the channel mappings are set, i.e., `chainToChannel` and `channelToChain`;
- `initialHeights[chainId]` is set to the current height.
- **Error Condition**
- None.
---
<!-- omit in toc -->
#### **[CCV-CCF-INITG.1]**
```typescript
// CCF: Consumer Chain Function
// implements the AppModule interface
function InitGenesis(gs: ConsumerGenesisState): [ValidatorUpdate] {
// ValidateGenesis
// - contains a valid providerClientState
abortSystemUnless(gs.providerClientState != nil AND gs.providerClientState.Valid())
// - contains a valid providerConsensusState
abortSystemUnless(gs.providerConsensusState != nil AND gs.providerConsensusState.Valid())
// - contains a non-empty initial validator set
abortSystemUnless(gs.initialValSet NOT empty)
// - contains an initial validator set that matches
// the validator set in the providerConsensusState (e.g., ICS 7)
abortSystemUnless(gs.initialValSet == gs.providerConsensusState.validatorSet)
// bind to ConsumerPortId port
err = portKeeper.BindPort(ConsumerPortId)
// check whether the capability for the port can be claimed
abortSystemUnless(err == nil)
// create client of the provider chain
clientId = clientKeeper.CreateClient(gs.providerClientState, gs.providerConsensusState)
// store the ID of the client of the provider chain
providerClient = clientId
// set default value for HtoVSC
HtoVSC[getCurrentHeight()] = 0
// set the initial validator set for the consumer chain
foreach val IN gs.initialValSet {
ccVal := CrossChainValidator{
address: hash(val.pubKey),
power: val.power
}
validatorSet[ccVal.address] = ccVal
}
return gs.initialValSet
}
```
- **Caller**
- The ABCI application.
- **Trigger Event**
- An `InitChain` message is received from the consensus engine; the `InitChain` message is sent when the consumer chain is first started.
- **Precondition**
- The consumer CCV module is in the initial state.
- **Postcondition**
- The capability for the port `ConsumerPortId` is claimed.
- A client of the provider chain is created and the client ID is stored into `providerClient`.
- `HtoVSC` for the current block is set to `0`.
- The `validatorSet` mapping is populated with the initial validator set.
- The initial validator set is returned to the consensus engine.
- **Error Condition**
- The genesis state contains no valid provider client state, where the validity is defined in the corresponding client specification (e.g., [ICS 7](../../client/ics-007-tendermint-client)).
- The genesis state contains no valid provider consensus state, where the validity is defined in the corresponding client specification (e.g., [ICS 7](../../client/ics-007-tendermint-client))..
- The genesis state contains an empty initial validator set.
- The genesis state contains an initial validator set that does not match the validator set in the provider consensus state.
- The capability for the port `ConsumerPortId` cannot be claimed.
> **Note**: CCV assumes that all the correct validators in the initial validator set of the consumer chain receive the _same_ consumer chain binary and consumer chain genesis state.
> Although the mechanism of disseminating the binary and the genesis state is outside the scope of this specification, a possible approach would entail including this information in the governance proposal on the provider chain.
<!-- omit in toc -->
#### **[CCV-CCF-COINIT.1]**
```typescript
// CCF: Consumer Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenInit(
order: ChannelOrder,
connectionHops: [Identifier],
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyPortIdentifier: Identifier,
counterpartyChannelIdentifier: Identifier,
version: string): string {
// ensure provider channel hasn't already been created
abortTransactionUnless(providerChannel == "")
// validate parameters:
// - only ordered channels allowed
abortTransactionUnless(order == ORDERED)
// - require the portIdentifier to be the port ID the CCV module is bound to
abortTransactionUnless(portIdentifier == ConsumerPortId)
// - require the version to be the expected version
abortTransactionUnless(version == "" OR version == ccvVersion)
// assert that the counterpartyPortIdentifier matches
// the expected consumer port ID
abortTransactionUnless(counterpartyPortIdentifier == ProviderPortId)
// require that the client ID of the client associated
// with this channel matches the expected provider client id
clientId = getClient(channelIdentifier)
abortTransactionUnless(providerClient != clientId)
return ccvVersion
}
```
- **Caller**
- The consumer IBC routing module.
- **Trigger Event**
- The consumer IBC routing module receives a `ChanOpenInit` message on a port the consumer CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is aborted if any of the following conditions are true:
- `providerChannel` is already set;
- `portIdentifier != ConsumerPortId`;
- `version` is set but not to the expected version;
- `counterpartyPortIdentifier != ProviderPortId`;
- the client associated with this channel is not the expected provider client.
- `ccvVersion` is returned.
- The state is not changed.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-CCF-COTRY.1]**
```typescript
// CCF: Consumer Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenTry(
order: ChannelOrder,
connectionHops: [Identifier],
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyPortIdentifier: Identifier,
counterpartyChannelIdentifier: Identifier,
counterpartyVersion: string): string {
// the channel handshake MUST be initiated by consumer chain
abortTransactionUnless(FALSE)
}
```
- **Caller**
- The consumer IBC routing module.
- **Trigger Event**
- The consumer IBC routing module receives a `ChanOpenTry` message on a port the consumer CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is always aborted; hence, the state is not changed.
- **Error Condition**
- None.
<!-- omit in toc -->
#### **[CCV-CCF-COACK.1]**
```typescript
// CCF: Consumer Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenAck(
portIdentifier: Identifier,
channelIdentifier: Identifier,
counterpartyVersion: string) {
// ensure provider channel hasn't already been created
abortTransactionUnless(providerChannel == "")
// the version must be encoded in JSON format (as defined in ICS4)
md = UnmarshalJSON(counterpartyVersion)
// assert that the counterpartyVersion matches the expected version
abortTransactionUnless(md.version == ccvVersion)
// set the address of the distribution module account on the provider chain
providerDistributionAccount = md.providerDistributionAccount
// initiate opening handshake for the distribution token transfer channel
// over the same connection as the CCV channel
// i.e., ChanOpenInit (as required by ICS20)
distributionChannelId = channelKeeper.ChanOpenInit(
UNORDERED, // order
channelKeeper.GetConnectionHops(channelIdentifier), // connectionHops: same as the CCV channel
"transfer", // portIdentifier
"transfer", // counterpartyPortIdentifier
"ics20-1" // version
)
}
```
- **Caller**
- The consumer IBC routing module.
- **Trigger Event**
- The consumer IBC routing module receives a `ChanOpenAck` message on a port the consumer CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- `counterpartyVersion` is unmarshaled into a `CCVHandshakeMetadata` structure `md`.
- The transaction is aborted if any of the following conditions are true:
- `providerChannel` is already set;
- `md.version != ccvVersion`.
- The address of the distribution module account on the provider chain is set to `md.providerDistributionAccount`.
- The distribution token transfer channel opening handshake is initiated and `distributionChannelId` is set to the resulting channel ID.
- **Error Condition**
- None.
> **Note:** The initialization sub-protocol on the consumer chain finalizes on receiving the first `VSCPacket` and setting `providerChannel` to the ID of the channel on which it receives the packet (see `onRecvVSCPacket` method).
<!-- omit in toc -->
#### **[CCV-CCF-COCONFIRM.1]**
```typescript
// CCF: Consumer Chain Function
// implements the ModuleCallbacks interface defined in ICS26
function onChanOpenConfirm(
portIdentifier: Identifier,
channelIdentifier: Identifier) {
// the channel handshake MUST be initiated by consumer chain
abortTransactionUnless(FALSE)
}
```
- **Caller**
- The consumer IBC routing module.
- **Trigger Event**
- The consumer IBC routing module receives a `ChanOpenConfirm` message on a port the consumer CCV module is bounded to.
- **Precondition**
- True.
- **Postcondition**
- The transaction is always aborted; hence, the state is not changed.
- **Error Condition**
- None.