github.com/vipernet-xyz/tm@v0.34.24/blockchain/msgs.go (about) 1 package blockchain 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/gogo/protobuf/proto" 8 9 "github.com/vipernet-xyz/tm/p2p" 10 bcproto "github.com/vipernet-xyz/tm/proto/tendermint/blockchain" 11 "github.com/vipernet-xyz/tm/types" 12 ) 13 14 const ( 15 // NOTE: keep up to date with bcproto.BlockResponse 16 BlockResponseMessagePrefixSize = 4 17 BlockResponseMessageFieldKeySize = 1 18 MaxMsgSize = types.MaxBlockSizeBytes + 19 BlockResponseMessagePrefixSize + 20 BlockResponseMessageFieldKeySize 21 ) 22 23 // ValidateMsg validates a message. 24 func ValidateMsg(pb proto.Message) error { 25 if pb == nil { 26 return errors.New("message cannot be nil") 27 } 28 29 switch msg := pb.(type) { 30 case *bcproto.BlockRequest: 31 if msg.Height < 0 { 32 return errors.New("negative Height") 33 } 34 case *bcproto.BlockResponse: 35 _, err := types.BlockFromProto(msg.Block) 36 if err != nil { 37 return err 38 } 39 case *bcproto.NoBlockResponse: 40 if msg.Height < 0 { 41 return errors.New("negative Height") 42 } 43 case *bcproto.StatusResponse: 44 if msg.Base < 0 { 45 return errors.New("negative Base") 46 } 47 if msg.Height < 0 { 48 return errors.New("negative Height") 49 } 50 if msg.Base > msg.Height { 51 return fmt.Errorf("base %v cannot be greater than height %v", msg.Base, msg.Height) 52 } 53 case *bcproto.StatusRequest: 54 return nil 55 default: 56 return fmt.Errorf("unknown message type %T", msg) 57 } 58 return nil 59 } 60 61 // EncodeMsg encodes a Protobuf message 62 // 63 // Deprecated: Will be removed in v0.37. 64 func EncodeMsg(pb proto.Message) ([]byte, error) { 65 if um, ok := pb.(p2p.Wrapper); ok { 66 pb = um.Wrap() 67 } 68 bz, err := proto.Marshal(pb) 69 if err != nil { 70 return nil, fmt.Errorf("unable to marshal %T: %w", pb, err) 71 } 72 73 return bz, nil 74 } 75 76 // DecodeMsg decodes a Protobuf message. 77 // 78 // Deprecated: Will be removed in v0.37. 79 func DecodeMsg(bz []byte) (proto.Message, error) { 80 pb := &bcproto.Message{} 81 82 err := proto.Unmarshal(bz, pb) 83 if err != nil { 84 return nil, err 85 } 86 return pb.Unwrap() 87 }