|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" |
| 7 | + cmttypes "github.com/cometbft/cometbft/types" |
| 8 | + "github.com/oasisprotocol/oasis-core/go/common/cbor" |
| 9 | +) |
| 10 | + |
| 11 | +// BlockMeta is the CometBFT-specific per-block metadata. |
| 12 | +type BlockMeta struct { |
| 13 | + // Header is the CometBFT block header. |
| 14 | + Header *cmttypes.Header `json:"header"` |
| 15 | + // LastCommit is the CometBFT last commit info. |
| 16 | + LastCommit *cmttypes.Commit `json:"last_commit"` |
| 17 | +} |
| 18 | + |
| 19 | +// TryUnmarshal attempts to unmarshal the given data into a BlockMeta. |
| 20 | +// |
| 21 | +// It first tries to unmarshal into V1, and if that fails, it tries to |
| 22 | +// unmarshal into V2. |
| 23 | +// |
| 24 | +// We only try to unmarshal into the version of the metadata structure |
| 25 | +// starting at Oasis-Core Eden (V1), and into V2 (starting at #6235). |
| 26 | +// This may fail on blocks from an incompatible earlier version. |
| 27 | +func (b *BlockMeta) TryUnmarshal(data []byte) error { |
| 28 | + // Try to unmarshal into V1 first. |
| 29 | + switch err := cbor.Unmarshal(data, &b); { |
| 30 | + case err == nil: |
| 31 | + return nil |
| 32 | + default: |
| 33 | + // Continue below. |
| 34 | + } |
| 35 | + |
| 36 | + // Try unmarshal into V2. |
| 37 | + var metaV2 blockMetaV2 |
| 38 | + if err := cbor.Unmarshal(data, &metaV2); err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + |
| 42 | + // V2 uses protobuf encoding. Try decoding into BlockMeta. |
| 43 | + var lastCommitProto cmtproto.Commit |
| 44 | + if err := lastCommitProto.Unmarshal(metaV2.LastCommit); err != nil { |
| 45 | + return fmt.Errorf("malformed V2 block meta last commit: %w", err) |
| 46 | + } |
| 47 | + lastCommit, err := cmttypes.CommitFromProto(&lastCommitProto) |
| 48 | + if err != nil { |
| 49 | + return fmt.Errorf("malformed V2 block meta last commit: %w", err) |
| 50 | + } |
| 51 | + |
| 52 | + var lastHeaderProto cmtproto.Header |
| 53 | + if err := lastHeaderProto.Unmarshal(metaV2.Header); err != nil { |
| 54 | + return fmt.Errorf("malformed V2 block meta last header: %w", err) |
| 55 | + } |
| 56 | + header, err := cmttypes.HeaderFromProto(&lastHeaderProto) |
| 57 | + if err != nil { |
| 58 | + return fmt.Errorf("malformed V2 block meta last header: %w", err) |
| 59 | + } |
| 60 | + |
| 61 | + b.Header = &header |
| 62 | + b.LastCommit = lastCommit |
| 63 | + return nil |
| 64 | +} |
| 65 | + |
| 66 | +// blockMetaV2 is the CometBFT-specific per-block metadata used in: |
| 67 | +// https://github.com/oasisprotocol/oasis-core/pull/6235 |
| 68 | +type blockMetaV2 struct { |
| 69 | + // Header is the CometBFT block header. |
| 70 | + Header []byte `json:"header"` |
| 71 | + // LastCommit is the CometBFT last commit info. |
| 72 | + LastCommit []byte `json:"last_commit"` |
| 73 | +} |
0 commit comments