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