-
Notifications
You must be signed in to change notification settings - Fork 9
/
client_state.go
313 lines (271 loc) · 8.41 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
package types
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/light"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types"
commitmenttypes "github.com/bianjieai/tibc-go/modules/tibc/core/23-commitment/types"
"github.com/bianjieai/tibc-go/modules/tibc/core/exported"
)
var _ exported.ClientState = (*ClientState)(nil)
func (m ClientState) ClientType() string {
return exported.ETH
}
func (m ClientState) GetLatestHeight() exported.Height {
return m.Header.Height
}
func (m ClientState) Validate() error {
return m.Header.ValidateBasic()
}
func (m ClientState) GetDelayTime() uint64 {
return m.TimeDelay
}
func (m ClientState) GetDelayBlock() uint64 {
return m.BlockDelay
}
func (m ClientState) GetPrefix() exported.Prefix {
return commitmenttypes.MerklePrefix{KeyPrefix: m.ContractAddress}
}
func (m ClientState) Initialize(
ctx sdk.Context,
cdc codec.BinaryCodec,
store sdk.KVStore,
state exported.ConsensusState,
) error {
header := m.Header
headerBytes, err := cdc.MarshalInterface(&header)
if err != nil {
return sdkerrors.Wrap(ErrInvalidGenesisBlock, "marshal consensus to interface failed")
}
SetEthHeaderIndex(store, header, headerBytes)
SetEthConsensusRoot(store, header.Height.RevisionHeight, header.ToEthHeader().Root, header.Hash())
return nil
}
func (m ClientState) Status(
ctx sdk.Context,
store sdk.KVStore,
cdc codec.BinaryCodec,
) exported.Status {
onsState, err := GetConsensusState(store, cdc, m.GetLatestHeight())
if err != nil {
return exported.Unknown
}
if onsState.Timestamp+m.TrustingPeriod < uint64(ctx.BlockTime().Nanosecond()) {
return exported.Expired
}
return exported.Active
}
func (m ClientState) ExportMetadata(store sdk.KVStore) []exported.GenesisMetadata {
gm := make([]exported.GenesisMetadata, 0)
callback := func(key, val []byte) bool {
gm = append(gm, clienttypes.NewGenesisMetadata(key, val))
return false
}
IteratorEthMetaDataByPrefix(store, KeyIndexEthHeaderPrefix, callback)
IteratorEthMetaDataByPrefix(store, KeyMainRootPrefix, callback)
if len(gm) == 0 {
return nil
}
return gm
}
func (m ClientState) VerifyPacketCommitment(
ctx sdk.Context,
store sdk.KVStore,
cdc codec.BinaryCodec,
height exported.Height,
proof []byte,
sourceChain, destChain string,
sequence uint64,
commitment []byte,
) error {
ethProof, consensusState, err := produceVerificationArgs(store, cdc, m, height, proof)
if err != nil {
return err
}
// check delay period has passed
delayBlock := m.Header.Height.RevisionHeight - height.GetRevisionHeight()
if delayBlock < m.GetDelayBlock() {
return sdkerrors.Wrapf(
sdkerrors.ErrInvalidHeight,
"delay block (%d) < client state delay block (%d)",
delayBlock, m.GetDelayBlock(),
)
}
constructor := NewProofKeyConstructor(sourceChain, destChain, sequence)
// verify that the provided commitment has been stored
return verifyMerkleProof(ethProof, consensusState, m.ContractAddress, commitment, constructor.GetPacketCommitmentProofKey())
}
func (m ClientState) VerifyPacketAcknowledgement(
ctx sdk.Context,
store sdk.KVStore,
cdc codec.BinaryCodec,
height exported.Height,
proof []byte,
sourceChain, destChain string,
sequence uint64,
ackBytes []byte,
) error {
ethProof, consensusState, err := produceVerificationArgs(store, cdc, m, height, proof)
if err != nil {
return err
}
delayBlock := m.Header.Height.RevisionHeight - height.GetRevisionHeight()
if delayBlock < m.GetDelayBlock() {
return sdkerrors.Wrapf(
sdkerrors.ErrInvalidHeight,
"delay block (%d) < client state delay block (%d)",
delayBlock, m.GetDelayBlock(),
)
}
constructor := NewProofKeyConstructor(sourceChain, destChain, sequence)
return verifyMerkleProof(ethProof, consensusState, m.ContractAddress, ackBytes, constructor.GetAckProofKey())
}
func (m ClientState) VerifyPacketCleanCommitment(
ctx sdk.Context,
store sdk.KVStore,
cdc codec.BinaryCodec,
height exported.Height,
proof []byte,
sourceChain, destChain string,
sequence uint64,
) error {
ethProof, consensusState, err := produceVerificationArgs(store, cdc, m, height, proof)
if err != nil {
return err
}
delayBlock := m.Header.Height.RevisionHeight - height.GetRevisionHeight()
if delayBlock < m.GetDelayBlock() {
return sdkerrors.Wrapf(
sdkerrors.ErrInvalidHeight,
"delay block (%d) < client state delay block (%d)",
delayBlock, m.GetDelayBlock(),
)
}
constructor := NewProofKeyConstructor(sourceChain, destChain, sequence)
return verifyMerkleProof(ethProof, consensusState, m.ContractAddress, sdk.Uint64ToBigEndian(sequence), constructor.GetCleanPacketCommitmentProofKey())
}
// produceVerificationArgs performs the basic checks on the arguments that are
// shared between the verification functions and returns the unmarshal
// merkle proof, the consensus state and an error if one occurred.
func produceVerificationArgs(
store sdk.KVStore,
cdc codec.BinaryCodec,
cs ClientState,
height exported.Height,
proof []byte,
) (
merkleProof Proof,
consensusState *ConsensusState,
err error,
) {
if cs.GetLatestHeight().LT(height) {
return Proof{}, nil, sdkerrors.Wrapf(
sdkerrors.ErrInvalidHeight,
"client state height < proof height (%d < %d)",
cs.GetLatestHeight(), height,
)
}
if proof == nil {
return Proof{}, nil, sdkerrors.Wrap(ErrInvalidProof, "proof cannot be empty")
}
if err = json.Unmarshal(proof, &merkleProof); err != nil {
return Proof{}, nil, sdkerrors.Wrap(ErrInvalidProof, "failed to unmarshal proof into proof")
}
consensusState, err = GetConsensusState(store, cdc, height)
if err != nil {
return Proof{}, nil, err
}
return merkleProof, consensusState, nil
}
func verifyMerkleProof(
ethProof Proof,
consensusState *ConsensusState,
contractAddr []byte,
commitment []byte,
proofKey []byte,
) error {
//1. prepare verify account
nodeList := new(light.NodeList)
for _, s := range ethProof.AccountProof {
_ = nodeList.Put(nil, common.FromHex(s))
}
ns := nodeList.NodeSet()
addr := common.FromHex(ethProof.Address)
if !bytes.Equal(addr, contractAddr) {
return fmt.Errorf(
"verifyMerkleProof, contract address is error, proof address: %s, side chain address: %s",
ethProof.Address, hex.EncodeToString(contractAddr),
)
}
acctKey := crypto.Keccak256(addr)
//2. verify account proof
root := common.BytesToHash(consensusState.Root)
acctVal, err := trie.VerifyProof(root, acctKey, ns)
if err != nil {
return fmt.Errorf("verifyMerkleProof, verify account proof error:%s", err)
}
storageHash := common.HexToHash(ethProof.StorageHash)
codeHash := common.HexToHash(ethProof.CodeHash)
nonce := common.HexToHash(ethProof.Nonce).Big()
balance := common.HexToHash(ethProof.Balance).Big()
acct := &ProofAccount{
Nonce: nonce,
Balance: balance,
Storage: storageHash,
Codehash: codeHash,
}
accRlp, err := rlp.EncodeToBytes(acct)
if err != nil {
return err
}
if !bytes.Equal(accRlp, acctVal) {
return fmt.Errorf("verifyMerkleProof, verify account proof failed, wanted:%v, get:%v", accRlp, acctVal)
}
//3.verify storage proof
nodeList = new(light.NodeList)
if len(ethProof.StorageProof) != 1 {
return fmt.Errorf("verifyMerkleProof, invalid storage proof format")
}
sp := ethProof.StorageProof[0]
if !bytes.Equal(common.HexToHash(sp.Key).Bytes(), proofKey) {
return fmt.Errorf("verifyMerkleProof, storageKey is error, storage key: %s, Key path: %s", common.HexToHash(sp.Key), proofKey)
}
storageKey := crypto.Keccak256(common.HexToHash(sp.Key).Bytes())
for _, prf := range sp.Proof {
_ = nodeList.Put(nil, common.FromHex(prf))
}
ns = nodeList.NodeSet()
val, err := trie.VerifyProof(storageHash, storageKey, ns)
if err != nil {
return fmt.Errorf("verifyMerkleProof, verify storage proof error:%s", err)
}
if !checkProofResult(val, commitment) {
return fmt.Errorf("verifyMerkleProof, verify storage result failed")
}
return nil
}
func checkProofResult(result, value []byte) bool {
var tempBytes []byte
err := rlp.DecodeBytes(result, &tempBytes)
if err != nil {
return false
}
//
var s []byte
for i := len(tempBytes); i < 32; i++ {
s = append(s, 0)
}
s = append(s, tempBytes...)
// TODO
//hash := crypto.Keccak256(value)
return bytes.Equal(s, value)
}