consensus.gno
1.95 Kb · 76 lines
1package ics23_mpt
2
3import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7
8 "gno.land/p/onbloc/verifier/evm/storage"
9)
10
11var (
12 ErrConsensusStateTooShort = errors.New("ics23mpt: l2 consensus state too short")
13 ErrInvalidCommitmentKey = errors.New("ics23mpt: invalid commitment key")
14)
15
16// ExtractConsensusState parses the L2 consensus state bytes into a
17// ConsensusState using the byte offsets recorded in this client state. The
18// state-lens client trusts the counterparty's opaque L2 consensus blob and
19// reads timestamp / state root / storage root from fixed offsets.
20func (cs ClientState) ExtractConsensusState(data []byte) (ConsensusState, error) {
21 timestamp, err := extractUint64(data, int(cs.TimestampOffset))
22 if err != nil {
23 return ConsensusState{}, err
24 }
25
26 stateRoot, err := extractBytes32(data, int(cs.StateRootOffset))
27 if err != nil {
28 return ConsensusState{}, err
29 }
30
31 storageRoot, err := extractBytes32(data, int(cs.StorageRootOffset))
32 if err != nil {
33 return ConsensusState{}, err
34 }
35
36 return ConsensusState{
37 Timestamp: timestamp,
38 StateRoot: stateRoot,
39 StorageRoot: storageRoot,
40 }, nil
41}
42
43func extractUint64(data []byte, offset int) (uint64, error) {
44 if offset < 0 || offset+8 > len(data) {
45 return 0, ErrConsensusStateTooShort
46 }
47
48 return binary.BigEndian.Uint64(data[offset : offset+8]), nil
49}
50
51func extractBytes32(data []byte, offset int) ([]byte, error) {
52 if offset < 0 || offset+32 > len(data) {
53 return nil, ErrConsensusStateTooShort
54 }
55
56 out := make([]byte, 32)
57 copy(out, data[offset:offset+32])
58
59 return out, nil
60}
61
62// VerifyCommitmentKey checks that proofKey matches the IBC commitment key
63// derived from path. It rejects proofs whose key does not bind to the
64// expected commitment path.
65func VerifyCommitmentKey(path []byte, proofKey []byte) error {
66 expected, err := storage.IBCCommitmentKey(path)
67 if err != nil {
68 return ErrInvalidCommitmentKey
69 }
70
71 if !bytes.Equal(expected[:], proofKey) {
72 return ErrInvalidCommitmentKey
73 }
74
75 return nil
76}