-
Notifications
You must be signed in to change notification settings - Fork 5
/
prover.go
338 lines (295 loc) · 11.5 KB
/
prover.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
package relay
import (
"bytes"
"context"
"fmt"
"log"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported"
"github.com/datachainlab/ethereum-ibc-relay-chain/pkg/client"
"github.com/datachainlab/ethereum-ibc-relay-chain/pkg/relay/ethereum"
"github.com/datachainlab/ethereum-ibc-relay-prover/beacon"
lctypes "github.com/datachainlab/ethereum-ibc-relay-prover/light-clients/ethereum/types"
"github.com/hyperledger-labs/yui-relayer/core"
)
type Prover struct {
chain *ethereum.Chain
config ProverConfig
executionClient *client.ETHClient
beaconClient beacon.Client
codec codec.ProtoCodecMarshaler
}
func NewProver(chain *ethereum.Chain, config ProverConfig) *Prover {
beaconClient := beacon.NewClient(config.BeaconEndpoint)
return &Prover{chain: chain, config: config, executionClient: chain.Client(), beaconClient: beaconClient}
}
//--------- Prover implementation ---------//
var _ core.Prover = (*Prover)(nil)
// Init initializes the chain
func (pr *Prover) Init(homePath string, timeout time.Duration, codec codec.ProtoCodecMarshaler, debug bool) error {
pr.codec = codec
return nil
}
// SetRelayInfo sets source's path and counterparty's info to the chain
func (pr *Prover) SetRelayInfo(path *core.PathEnd, counterparty *core.ProvableChain, counterpartyPath *core.PathEnd) error {
return nil
}
// SetupForRelay performs chain-specific setup before starting the relay
func (pr *Prover) SetupForRelay(ctx context.Context) error {
return nil
}
//--------- LightClient implementation ---------//
var _ core.LightClient = (*Prover)(nil)
// CreateMsgCreateClient creates a CreateClientMsg to this chain
func (pr *Prover) CreateMsgCreateClient(clientID string, dstHeader core.Header, signer sdk.AccAddress) (*clienttypes.MsgCreateClient, error) {
// NOTE: `dstHeader` generated by GetLatestFinalizedHeader doesn't have the next sync committe
// So, we don't use it here, use the result of `light_client_update` to create an initial state instead.
_ = dstHeader.(*lctypes.Header)
genesis, err := pr.beaconClient.GetGenesis()
if err != nil {
return nil, err
}
bootstrap, err := pr.getLightClientBootstrap()
if err != nil {
return nil, err
}
accountUpdate, err := pr.buildAccountUpdate(bootstrap.Header.Execution.BlockNumber)
if err != nil {
return nil, err
}
clientState := pr.newClientState()
clientState.GenesisValidatorsRoot = genesis.GenesisValidatorsRoot[:]
clientState.GenesisTime = genesis.GenesisTimeSeconds
clientState.LatestSlot = uint64(bootstrap.Header.Beacon.Slot)
clientState.LatestExecutionBlockNumber = bootstrap.Header.Execution.BlockNumber
consensusState := &lctypes.ConsensusState{
Slot: clientState.LatestSlot,
StorageRoot: accountUpdate.AccountStorageRoot,
Timestamp: bootstrap.Header.Execution.Timestamp,
CurrentSyncCommittee: bootstrap.CurrentSyncCommittee.AggregatePubKey,
}
return clienttypes.NewMsgCreateClient(clientState, consensusState, signer.String())
}
// SetupHeadersForUpdate returns the finalized header and any intermediate headers needed to apply it to the client on the counterpaty chain
// The order of the returned header slice should be as: [<intermediate headers>..., <update header>]
// if the header slice's length == 0 and err == nil, the relayer should skips the update-client
func (pr *Prover) SetupHeadersForUpdate(dstChain core.ChainInfoICS02Querier, latestFinalizedHeader core.Header) ([]core.Header, error) {
finalizedHeader := latestFinalizedHeader.(*lctypes.Header)
latestHeight, err := dstChain.LatestHeight()
if err != nil {
return nil, err
}
// retrieve counterparty client from dst chain
counterpartyClientRes, err := dstChain.QueryClientState(core.NewQueryContext(context.TODO(), latestHeight))
if err != nil {
return nil, err
}
var cs ibcexported.ClientState
if err := pr.codec.UnpackAny(counterpartyClientRes.ClientState, &cs); err != nil {
return nil, err
}
if cs.GetLatestHeight().GetRevisionHeight() == finalizedHeader.ExecutionUpdate.BlockNumber {
return nil, nil
} else if cs.GetLatestHeight().GetRevisionHeight() > finalizedHeader.ExecutionUpdate.BlockNumber {
return nil, fmt.Errorf("the latest finalized header is older than the latest height of client state: finalized_block_number=%v client_latest_height=%v", finalizedHeader.ExecutionUpdate.BlockNumber, cs.GetLatestHeight().GetRevisionHeight())
}
latestPeriod := pr.computeSyncCommitteePeriod(pr.computeEpoch(finalizedHeader.ConsensusUpdate.FinalizedHeader.Slot))
statePeriod, err := pr.findLCPeriodByHeight(cs.GetLatestHeight(), latestPeriod)
if err != nil {
return nil, err
}
log.Printf("try to setup headers for updating the light-client: lc_latest_height=%v lc_latest_height_period=%v latest_period=%v", cs.GetLatestHeight(), statePeriod, latestPeriod)
if statePeriod > latestPeriod {
return nil, fmt.Errorf("the light-client server's response is old: client_state_period=%v latest_finalized_period=%v", statePeriod, latestPeriod)
} else if statePeriod == latestPeriod {
latestHeight := cs.GetLatestHeight().(clienttypes.Height)
res, err := pr.beaconClient.GetLightClientUpdate(statePeriod)
if err != nil {
return nil, err
}
root, err := res.Data.FinalizedHeader.Beacon.HashTreeRoot()
if err != nil {
return nil, err
}
bootstrapRes, err := pr.beaconClient.GetBootstrap(root[:])
if err != nil {
return nil, err
}
finalizedHeader.TrustedSyncCommittee = &lctypes.TrustedSyncCommittee{
TrustedHeight: &latestHeight,
SyncCommittee: bootstrapRes.Data.CurrentSyncCommittee.ToProto(),
IsNext: false,
}
return []core.Header{finalizedHeader}, nil
}
//--------- In case statePeriod < latestPeriod ---------//
var (
headers []core.Header
trustedSyncCommittee *lctypes.SyncCommittee
trustedHeight = cs.GetLatestHeight().(clienttypes.Height)
)
for p := statePeriod; p < latestPeriod; p++ {
var header *lctypes.Header
if p == statePeriod {
header, err = pr.buildNextSyncCommitteeUpdateForCurrent(statePeriod, trustedHeight)
if err != nil {
return nil, err
}
} else {
header, err = pr.buildNextSyncCommitteeUpdateForNext(p, trustedHeight)
if err != nil {
return nil, err
}
}
headers = append(headers, header)
trustedHeight = clienttypes.NewHeight(0, header.ExecutionUpdate.BlockNumber)
trustedSyncCommittee = header.ConsensusUpdate.NextSyncCommittee
}
finalizedHeader.TrustedSyncCommittee = &lctypes.TrustedSyncCommittee{
TrustedHeight: &trustedHeight,
SyncCommittee: trustedSyncCommittee,
IsNext: true,
}
headers = append(headers, finalizedHeader)
return headers, nil
}
// GetLatestFinalizedHeader returns the latest finalized header on this chain
// The returned header is expected to be the latest one of headers that can be verified by the light client
func (pr *Prover) GetLatestFinalizedHeader() (headers core.Header, err error) {
res, err := pr.beaconClient.GetLightClientFinalityUpdate()
if err != nil {
return nil, err
}
lcUpdate := res.Data.ToProto()
executionHeader := res.Data.FinalizedHeader.Execution
executionUpdate, err := pr.buildExecutionUpdate(executionHeader)
if err != nil {
return nil, err
}
executionRoot, err := executionHeader.HashTreeRoot()
if err != nil {
return nil, err
}
if !bytes.Equal(executionRoot[:], lcUpdate.FinalizedExecutionRoot) {
return nil, fmt.Errorf("execution root mismatch: %X != %X", executionRoot, lcUpdate.FinalizedExecutionRoot)
}
accountUpdate, err := pr.buildAccountUpdate(executionHeader.BlockNumber)
if err != nil {
return nil, err
}
return &lctypes.Header{
ConsensusUpdate: lcUpdate,
ExecutionUpdate: executionUpdate,
AccountUpdate: accountUpdate,
Timestamp: executionHeader.Timestamp,
}, nil
}
func (pr *Prover) newClientState() *lctypes.ClientState {
var commitmentsSlot [32]byte
ibcAddress := pr.chain.Config().IBCAddress()
return &lctypes.ClientState{
ForkParameters: pr.config.getForkParameters(),
SecondsPerSlot: pr.config.getSecondsPerSlot(),
SlotsPerEpoch: pr.config.getSlotsPerEpoch(),
EpochsPerSyncCommitteePeriod: pr.config.getEpochsPerSyncCommitteePeriod(),
MinSyncCommitteeParticipants: 1,
IbcAddress: ibcAddress.Bytes(),
IbcCommitmentsSlot: commitmentsSlot[:],
TrustLevel: &lctypes.Fraction{
Numerator: 2,
Denominator: 3,
},
TrustingPeriod: 0,
}
}
func (pr *Prover) buildNextSyncCommitteeUpdateForCurrent(period uint64, trustedHeight clienttypes.Height) (*lctypes.Header, error) {
res, err := pr.beaconClient.GetLightClientUpdate(period)
if err != nil {
return nil, err
}
lcUpdate := res.Data.ToProto()
executionHeader := res.Data.FinalizedHeader.Execution
executionUpdate, err := pr.buildExecutionUpdate(executionHeader)
if err != nil {
return nil, err
}
executionRoot, err := executionHeader.HashTreeRoot()
if err != nil {
return nil, err
}
if !bytes.Equal(executionRoot[:], lcUpdate.FinalizedExecutionRoot) {
return nil, fmt.Errorf("execution root mismatch: %X != %X", executionRoot, lcUpdate.FinalizedExecutionRoot)
}
accountUpdate, err := pr.buildAccountUpdate(executionHeader.BlockNumber)
if err != nil {
return nil, err
}
root, err := res.Data.FinalizedHeader.Beacon.HashTreeRoot()
if err != nil {
return nil, err
}
bootstrapRes, err := pr.beaconClient.GetBootstrap(root[:])
if err != nil {
return nil, err
}
return &lctypes.Header{
TrustedSyncCommittee: &lctypes.TrustedSyncCommittee{
TrustedHeight: &trustedHeight,
SyncCommittee: bootstrapRes.Data.CurrentSyncCommittee.ToProto(),
IsNext: false,
},
ConsensusUpdate: lcUpdate,
ExecutionUpdate: executionUpdate,
AccountUpdate: accountUpdate,
Timestamp: executionHeader.Timestamp,
}, nil
}
func (pr *Prover) buildNextSyncCommitteeUpdateForNext(period uint64, trustedHeight clienttypes.Height) (*lctypes.Header, error) {
res, err := pr.beaconClient.GetLightClientUpdate(period)
if err != nil {
return nil, err
}
lcUpdate := res.Data.ToProto()
executionHeader := res.Data.FinalizedHeader.Execution
executionUpdate, err := pr.buildExecutionUpdate(executionHeader)
if err != nil {
return nil, err
}
executionRoot, err := executionHeader.HashTreeRoot()
if err != nil {
return nil, err
}
if !bytes.Equal(executionRoot[:], lcUpdate.FinalizedExecutionRoot) {
return nil, fmt.Errorf("execution root mismatch: %X != %X", executionRoot, lcUpdate.FinalizedExecutionRoot)
}
accountUpdate, err := pr.buildAccountUpdate(executionHeader.BlockNumber)
if err != nil {
return nil, err
}
return &lctypes.Header{
TrustedSyncCommittee: &lctypes.TrustedSyncCommittee{
TrustedHeight: &trustedHeight,
SyncCommittee: lcUpdate.NextSyncCommittee,
IsNext: true,
},
ConsensusUpdate: lcUpdate,
ExecutionUpdate: executionUpdate,
AccountUpdate: accountUpdate,
Timestamp: executionHeader.Timestamp,
}, nil
}
//--------- StateProver implementation ---------//
var _ core.StateProver = (*Prover)(nil)
// ProveState returns the proof of an IBC state specified by `path` and `value`
func (pr *Prover) ProveState(ctx core.QueryContext, path string, value []byte) ([]byte, clienttypes.Height, error) {
proofHeight := int64(ctx.Height().GetRevisionHeight())
height := pr.newHeight(proofHeight)
proof, err := pr.buildStateProof([]byte(path), proofHeight)
return proof, height, err
}
func (pr *Prover) newHeight(blockNumber int64) clienttypes.Height {
return clienttypes.NewHeight(0, uint64(blockNumber))
}