-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
81c9e37
commit 966c6ac
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
// FROM: COMETBFT | ||
// IBC-Go also uses this package. Maybe the SDK in v2 upstreams this? | ||
|
||
package bytes | ||
|
||
import ( | ||
"encoding/hex" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/cometbft/cometbft/libs/bytes" | ||
) | ||
|
||
// HexBytes enables HEX-encoding for json/encoding. | ||
type HexBytes []byte | ||
|
||
// Marshal needed for protobuf compatibility | ||
func (bz HexBytes) Marshal() ([]byte, error) { | ||
return bz, nil | ||
} | ||
|
||
// Unmarshal needed for protobuf compatibility | ||
func (bz *HexBytes) Unmarshal(data []byte) error { | ||
*bz = data | ||
return nil | ||
} | ||
|
||
// This is the point of Bytes. | ||
func (bz HexBytes) MarshalJSON() ([]byte, error) { | ||
s := strings.ToUpper(hex.EncodeToString(bz)) | ||
jbz := make([]byte, len(s)+2) | ||
jbz[0] = '"' | ||
copy(jbz[1:], s) | ||
jbz[len(jbz)-1] = '"' | ||
return jbz, nil | ||
} | ||
|
||
// This is the point of Bytes. | ||
func (bz *HexBytes) UnmarshalJSON(data []byte) error { | ||
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { | ||
return fmt.Errorf("invalid hex string: %s", data) | ||
} | ||
bz2, err := hex.DecodeString(string(data[1 : len(data)-1])) | ||
if err != nil { | ||
return err | ||
} | ||
*bz = bz2 | ||
return nil | ||
} | ||
|
||
// Bytes fulfills various interfaces in light-client, etc... | ||
func (bz HexBytes) Bytes() []byte { | ||
return bz | ||
} | ||
|
||
func (bz HexBytes) String() string { | ||
return strings.ToUpper(hex.EncodeToString(bz)) | ||
} | ||
|
||
// Format writes either address of 0th element in a slice in base 16 notation, | ||
// with leading 0x (%p), or casts HexBytes to bytes and writes as hexadecimal | ||
// string to s. | ||
func (bz HexBytes) Format(s fmt.State, verb rune) { | ||
switch verb { | ||
case 'p': | ||
s.Write([]byte(fmt.Sprintf("%p", bz))) | ||
default: | ||
s.Write([]byte(fmt.Sprintf("%X", []byte(bz)))) | ||
} | ||
} | ||
|
||
// ConvertCometBFTToHexBytes converts a cometbft bytes.HexBytes to relayer HexBytes. | ||
func ConvertCometBFTToHexBytes(cbft bytes.HexBytes) HexBytes { | ||
return HexBytes(cbft) | ||
} |