-
Notifications
You must be signed in to change notification settings - Fork 26
/
prover.go
241 lines (197 loc) · 7.13 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
package tendermint
import (
"bytes"
"context"
"fmt"
"time"
"github.com/cometbft/cometbft/light"
tmtypes "github.com/cometbft/cometbft/types"
"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"
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
}
}
/* LightClient implementation */
// CreateMsgCreateClient creates a CreateClientMsg to this chain
func (pr *Prover) CreateMsgCreateClient(clientID string, dstHeader core.Header, signer sdk.AccAddress) (*clienttypes.MsgCreateClient, error) {
ubdPeriod, err := pr.chain.QueryUnbondingPeriod()
if err != nil {
return nil, err
}
return createClient(
dstHeader.(*tmclient.Header),
pr.getTrustingPeriod(),
ubdPeriod,
signer,
), 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(dstChain core.ChainInfoICS02Querier, latestFinalizedHeader core.Header) ([]core.Header, error) {
srcChain := pr.chain
// make copy of header stored in mop
tmp := latestFinalizedHeader.(*tmclient.Header)
h := *tmp
dsth, err := dstChain.LatestHeight()
if err != nil {
return nil, err
}
// retrieve counterparty client from dst chain
counterpartyClientRes, err := dstChain.QueryClientState(core.NewQueryContext(context.TODO(), dsth))
if err != nil {
return nil, err
}
var cs ibcexported.ClientState
if err := srcChain.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 srcChain
valSet, err := srcChain.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() (latestFinalizedHeader core.Header, err error) {
h, err := pr.UpdateLightClient()
if err != nil {
return nil, err
}
return h, nil
}
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() (core.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)
}
sh, err := client.Update(context.Background(), time.Now())
if err != nil {
return nil, lightError(err)
}
if sh == nil {
sh, err = client.TrustedLightBlock(0)
if 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) }