github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/ibc-go/modules/core/24-host/parse.go (about) 1 package host 2 3 import ( 4 "strconv" 5 "strings" 6 7 sdkerrors "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/errors" 8 ) 9 10 // ParseIdentifier parses the sequence from the identifier using the provided prefix. This function 11 // does not need to be used by counterparty chains. SDK generated connection and channel identifiers 12 // are required to use this format. 13 func ParseIdentifier(identifier, prefix string) (uint64, error) { 14 if !strings.HasPrefix(identifier, prefix) { 15 return 0, sdkerrors.Wrapf(ErrInvalidID, "identifier doesn't contain prefix `%s`", prefix) 16 } 17 18 splitStr := strings.Split(identifier, prefix) 19 if len(splitStr) != 2 { 20 return 0, sdkerrors.Wrapf(ErrInvalidID, "identifier must be in format: `%s{N}`", prefix) 21 } 22 23 // sanity check 24 if splitStr[0] != "" { 25 return 0, sdkerrors.Wrapf(ErrInvalidID, "identifier must begin with prefix %s", prefix) 26 } 27 28 sequence, err := strconv.ParseUint(splitStr[1], 10, 64) 29 if err != nil { 30 return 0, sdkerrors.Wrap(err, "failed to parse identifier sequence") 31 } 32 return sequence, nil 33 } 34 35 // ParseConnectionPath returns the connection ID from a full path. It returns 36 // an error if the provided path is invalid. 37 func ParseConnectionPath(path string) (string, error) { 38 split := strings.Split(path, "/") 39 if len(split) != 2 { 40 return "", sdkerrors.Wrapf(ErrInvalidPath, "cannot parse connection path %s", path) 41 } 42 43 return split[1], nil 44 } 45 46 // ParseChannelPath returns the port and channel ID from a full path. It returns 47 // an error if the provided path is invalid. 48 func ParseChannelPath(path string) (string, string, error) { 49 split := strings.Split(path, "/") 50 if len(split) < 5 { 51 return "", "", sdkerrors.Wrapf(ErrInvalidPath, "cannot parse channel path %s", path) 52 } 53 54 if split[1] != KeyPortPrefix || split[3] != KeyChannelPrefix { 55 return "", "", sdkerrors.Wrapf(ErrInvalidPath, "cannot parse channel path %s", path) 56 } 57 58 return split[2], split[4], nil 59 } 60 61 // MustParseConnectionPath returns the connection ID from a full path. Panics 62 // if the provided path is invalid. 63 func MustParseConnectionPath(path string) string { 64 connectionID, err := ParseConnectionPath(path) 65 if err != nil { 66 panic(err) 67 } 68 return connectionID 69 } 70 71 // MustParseChannelPath returns the port and channel ID from a full path. Panics 72 // if the provided path is invalid. 73 func MustParseChannelPath(path string) (string, string) { 74 portID, channelID, err := ParseChannelPath(path) 75 if err != nil { 76 panic(err) 77 } 78 return portID, channelID 79 }