github.com/DFWallet/tendermint-cosmos@v0.0.2/statesync/messages.go (about) 1 package statesync 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/gogo/protobuf/proto" 8 9 ssproto "github.com/DFWallet/tendermint-cosmos/proto/tendermint/statesync" 10 ) 11 12 const ( 13 // snapshotMsgSize is the maximum size of a snapshotResponseMessage 14 snapshotMsgSize = int(4e6) 15 // chunkMsgSize is the maximum size of a chunkResponseMessage 16 chunkMsgSize = int(16e6) 17 ) 18 19 // mustEncodeMsg encodes a Protobuf message, panicing on error. 20 func mustEncodeMsg(pb proto.Message) []byte { 21 msg := ssproto.Message{} 22 switch pb := pb.(type) { 23 case *ssproto.ChunkRequest: 24 msg.Sum = &ssproto.Message_ChunkRequest{ChunkRequest: pb} 25 case *ssproto.ChunkResponse: 26 msg.Sum = &ssproto.Message_ChunkResponse{ChunkResponse: pb} 27 case *ssproto.SnapshotsRequest: 28 msg.Sum = &ssproto.Message_SnapshotsRequest{SnapshotsRequest: pb} 29 case *ssproto.SnapshotsResponse: 30 msg.Sum = &ssproto.Message_SnapshotsResponse{SnapshotsResponse: pb} 31 default: 32 panic(fmt.Errorf("unknown message type %T", pb)) 33 } 34 bz, err := msg.Marshal() 35 if err != nil { 36 panic(fmt.Errorf("unable to marshal %T: %w", pb, err)) 37 } 38 return bz 39 } 40 41 // decodeMsg decodes a Protobuf message. 42 func decodeMsg(bz []byte) (proto.Message, error) { 43 pb := &ssproto.Message{} 44 err := proto.Unmarshal(bz, pb) 45 if err != nil { 46 return nil, err 47 } 48 switch msg := pb.Sum.(type) { 49 case *ssproto.Message_ChunkRequest: 50 return msg.ChunkRequest, nil 51 case *ssproto.Message_ChunkResponse: 52 return msg.ChunkResponse, nil 53 case *ssproto.Message_SnapshotsRequest: 54 return msg.SnapshotsRequest, nil 55 case *ssproto.Message_SnapshotsResponse: 56 return msg.SnapshotsResponse, nil 57 default: 58 return nil, fmt.Errorf("unknown message type %T", msg) 59 } 60 } 61 62 // validateMsg validates a message. 63 func validateMsg(pb proto.Message) error { 64 if pb == nil { 65 return errors.New("message cannot be nil") 66 } 67 switch msg := pb.(type) { 68 case *ssproto.ChunkRequest: 69 if msg.Height == 0 { 70 return errors.New("height cannot be 0") 71 } 72 case *ssproto.ChunkResponse: 73 if msg.Height == 0 { 74 return errors.New("height cannot be 0") 75 } 76 if msg.Missing && len(msg.Chunk) > 0 { 77 return errors.New("missing chunk cannot have contents") 78 } 79 if !msg.Missing && msg.Chunk == nil { 80 return errors.New("chunk cannot be nil") 81 } 82 case *ssproto.SnapshotsRequest: 83 case *ssproto.SnapshotsResponse: 84 if msg.Height == 0 { 85 return errors.New("height cannot be 0") 86 } 87 if len(msg.Hash) == 0 { 88 return errors.New("snapshot has no hash") 89 } 90 if msg.Chunks == 0 { 91 return errors.New("snapshot has no chunks") 92 } 93 default: 94 return fmt.Errorf("unknown message type %T", msg) 95 } 96 return nil 97 }