-
Notifications
You must be signed in to change notification settings - Fork 26
/
prover.go
260 lines (212 loc) · 8 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
package tendermint
import (
"bytes"
"context"
"fmt"
"time"
"github.com/cometbft/cometbft/light"
"github.com/cometbft/cometbft/types"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/codec"
clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
ibcclient "github.com/cosmos/ibc-go/v7/modules/core/client"
ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported"
tmclient "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint"
"github.com/hyperledger-labs/yui-relayer/core"
)
type Prover struct {
chain *Chain
config ProverConfig
}
var _ core.Prover = (*Prover)(nil)
func NewProver(chain *Chain, config ProverConfig) *Prover {
return &Prover{chain: chain, config: config}
}
func (pr *Prover) Init(homePath string, timeout time.Duration, codec codec.ProtoCodecMarshaler, debug bool) error {
return nil
}
// SetRelayInfo sets source's path and counterparty's info to the chain
func (pr *Prover) SetRelayInfo(_ *core.PathEnd, _ *core.ProvableChain, _ *core.PathEnd) error {
return nil // prover uses chain's path instead
}
func (pr *Prover) SetupForRelay(ctx context.Context) error {
return 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) {
clientCtx := pr.chain.CLIContext(int64(ctx.Height().GetRevisionHeight()))
if v, proof, proofHeight, err := ibcclient.QueryTendermintProof(clientCtx, []byte(path)); err != nil {
return nil, clienttypes.Height{}, err
} else if !bytes.Equal(v, value) {
return nil, clienttypes.Height{}, fmt.Errorf("value unmatch: %x != %x", v, value)
} else {
return proof, proofHeight, nil
}
}
// ProveHostConsensusState returns the existence proof of the consensus state at `height`
// ibc-go doesn't use this proof, so it returns nil
func (pr *Prover) ProveHostConsensusState(ctx core.QueryContext, height ibcexported.Height, consensusState ibcexported.ConsensusState) ([]byte, error) {
return nil, nil
}
/* LightClient implementation */
// CreateInitialLightClientState creates a pair of ClientState and ConsensusState submitted to the counterparty chain as MsgCreateClient
func (pr *Prover) CreateInitialLightClientState(height ibcexported.Height) (ibcexported.ClientState, ibcexported.ConsensusState, error) {
var tmHeight int64
if height != nil {
tmHeight = int64(height.GetRevisionHeight())
}
selfHeader, err := pr.UpdateLightClient(tmHeight)
if err != nil {
return nil, nil, fmt.Errorf("failed to update the local light client and get the header@%d: %v", tmHeight, err)
}
ubdPeriod, err := pr.chain.QueryUnbondingPeriod()
if err != nil {
return nil, nil, fmt.Errorf("failed to query for the unbonding period: %v", err)
}
cs := createClient(
selfHeader,
pr.getTrustingPeriod(),
ubdPeriod,
)
cons := selfHeader.ConsensusState()
return cs, cons, nil
}
// SetupHeadersForUpdate returns the finalized header and any intermediate headers needed to apply it to the client on the counterpaty chain
func (pr *Prover) SetupHeadersForUpdate(counterparty core.FinalityAwareChain, latestFinalizedHeader core.Header) ([]core.Header, error) {
self := pr.chain
// make copy of header stored in mop
tmp := latestFinalizedHeader.(*tmclient.Header)
h := *tmp
cph, err := counterparty.LatestHeight()
if err != nil {
return nil, err
}
// retrieve the client state from the counterparty chain
counterpartyClientRes, err := counterparty.QueryClientState(core.NewQueryContext(context.TODO(), cph))
if err != nil {
return nil, err
}
var cs ibcexported.ClientState
if err := self.codec.UnpackAny(counterpartyClientRes.ClientState, &cs); err != nil {
return nil, err
}
// inject TrustedHeight as latest height stored on counterparty client
h.TrustedHeight = cs.GetLatestHeight().(clienttypes.Height)
// query TrustedValidators at Trusted Height from the self chain
valSet, err := self.QueryValsetAtHeight(h.TrustedHeight)
if err != nil {
return nil, err
}
// inject TrustedValidators into header
h.TrustedValidators = valSet
return []core.Header{&h}, nil
}
// GetLatestFinalizedHeader returns the latest finalized header
func (pr *Prover) GetLatestFinalizedHeader() (core.Header, error) {
return pr.UpdateLightClient(0)
}
func (pr *Prover) CheckRefreshRequired(counterparty core.ChainInfoICS02Querier) (bool, error) {
cpQueryHeight, err := counterparty.LatestHeight()
if err != nil {
return false, fmt.Errorf("failed to get the latest height of the counterparty chain: %v", err)
}
cpQueryCtx := core.NewQueryContext(context.TODO(), cpQueryHeight)
resCs, err := counterparty.QueryClientState(cpQueryCtx)
if err != nil {
return false, fmt.Errorf("failed to query the client state on the counterparty chain: %v", err)
}
var cs ibcexported.ClientState
if err := pr.chain.codec.UnpackAny(resCs.ClientState, &cs); err != nil {
return false, fmt.Errorf("failed to unpack Any into tendermint client state: %v", err)
}
resCons, err := counterparty.QueryClientConsensusState(cpQueryCtx, cs.GetLatestHeight())
if err != nil {
return false, fmt.Errorf("failed to query the consensus state on the counterparty chain: %v", err)
}
var cons ibcexported.ConsensusState
if err := pr.chain.codec.UnpackAny(resCons.ConsensusState, &cons); err != nil {
return false, fmt.Errorf("failed to unpack Any into tendermint consensus state: %v", err)
}
lcLastTimestamp := time.Unix(0, int64(cons.GetTimestamp()))
selfQueryHeight, err := pr.chain.LatestHeight()
if err != nil {
return false, fmt.Errorf("failed to get the latest height of the self chain: %v", err)
}
selfTimestamp, err := pr.chain.Timestamp(selfQueryHeight)
if err != nil {
return false, fmt.Errorf("failed to get timestamp of the self chain: %v", err)
}
elapsedTime := selfTimestamp.Sub(lcLastTimestamp)
durationMulByFraction := func(d time.Duration, f *Fraction) time.Duration {
nsec := d.Nanoseconds() * int64(f.Numerator) / int64(f.Denominator)
return time.Duration(nsec) * time.Nanosecond
}
needsRefresh := elapsedTime > durationMulByFraction(pr.config.GetTrustingPeriod(), pr.config.RefreshThresholdRate)
return needsRefresh, nil
}
/* Local LightClient implementation */
// GetLatestLightHeight uses the CLI utilities to pull the latest height from a given chain
func (pr *Prover) GetLatestLightHeight() (int64, error) {
db, df, err := pr.NewLightDB()
if err != nil {
return -1, err
}
defer df()
client, err := pr.LightClient(db)
if err != nil {
return -1, err
}
return client.LastTrustedHeight()
}
func (pr *Prover) UpdateLightClient(height int64) (*tmclient.Header, error) {
// create database connection
db, df, err := pr.NewLightDB()
if err != nil {
return nil, lightError(err)
}
defer df()
client, err := pr.LightClient(db)
if err != nil {
return nil, lightError(err)
}
var sh *types.LightBlock
if height == 0 {
if sh, err = client.Update(context.Background(), time.Now()); err != nil {
return nil, lightError(err)
} else if sh == nil {
sh, err = client.TrustedLightBlock(0)
if err != nil {
return nil, lightError(err)
}
}
} else {
if sh, err = client.VerifyLightBlockAtHeight(context.Background(), height, time.Now()); err != nil {
return nil, lightError(err)
}
}
valSet := tmtypes.NewValidatorSet(sh.ValidatorSet.Validators)
protoVal, err := valSet.ToProto()
if err != nil {
return nil, err
}
protoVal.TotalVotingPower = valSet.TotalVotingPower()
return &tmclient.Header{
SignedHeader: sh.SignedHeader.ToProto(),
ValidatorSet: protoVal,
}, nil
}
// TrustOptions returns light.TrustOptions given a height and hash
func (pr *Prover) TrustOptions(height int64, hash []byte) light.TrustOptions {
return light.TrustOptions{
Period: pr.getTrustingPeriod(),
Height: height,
Hash: hash,
}
}
/// internal method ///
// getTrustingPeriod returns the trusting period for the chain
func (pr *Prover) getTrustingPeriod() time.Duration {
tp, _ := time.ParseDuration(pr.config.TrustingPeriod)
return tp
}
func lightError(err error) error { return fmt.Errorf("light client: %w", err) }