rlp
Encodes and decodes values using Recursive Length Prefix (RLP) encoding
Loading...
Encodes and decodes values using Recursive Length Prefix (RLP) encoding
Encodes and decodes values using Recursive Length Prefix (RLP) encoding, the serialization format used in Ethereum.
import "github.com/ChefBingbong/viem-go/utils/encoding"import "github.com/ChefBingbong/viem-go/utils/encoding"
// Encode hex string to RLPencoded, _ := encoding.ToRlp("0x123456789").Hex()// "0x850123456789"
// Encode byte array to RLPencoded, _ := encoding.ToRlp([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9}).Hex()// "0x89010203040506070809"
// Encode list to RLPencoded, _ := encoding.ToRlp([]any{ "0x7f", "0x7f", "0x8081e8",}).Hex()// "0xc67f7f838081e8"
// Decode RLP hex stringdecoded, _ := encoding.FromRlp("0x850123456789")result, _ := decoded.Hex()// "0x123456789"
// Decode RLP listdecoded, _ := encoding.FromRlp("0xc67f7f838081e8")result, _ := decoded.Hex()// []any{"0x7f", "0x7f", "0x8081e8"}([]byte, error) for Bytes(), (string, error) for Hex(), (any, error) for decoder methodsThe RLP-encoded or decoded value.
any (supports []byte, string (hex), []any, encoding.RecursiveBytes)The value to RLP encode.
// Encode hex stringencoded, _ := encoding.ToRlp("0x123456789").Hex()// "0x850123456789"
// Encode listencoded, _ := encoding.ToRlp([]any{"0x7f", "0x7f"}).Hex()// "0xc27f7f"[]byte or string (hex)The RLP-encoded data to decode.
// Decode from hex stringdecoded, _ := encoding.FromRlp("0x850123456789")result, _ := decoded.Hex()// "0x123456789"
// Decode from bytesdecoded, _ := encoding.FromRlp([]byte{0x85, 0x01, 0x23, 0x45, 0x67, 0x89})result, _ := decoded.Bytes()// []byte{0x01, 0x23, 0x45, 0x67, 0x89}Encodes to RLP and returns a hex string:
encoded, _ := encoding.ToRlp("0x123456789").Hex()
// "0x850123456789"
Encodes to RLP and returns bytes:
encoded, _ := encoding.ToRlp("0x123456789").Bytes()
// []byte{0x85, 0x01, 0x23, 0x45, 0x67, 0x89}
Decodes RLP and returns the result as recursive hex strings:
decoded, _ := encoding.FromRlp("0xc67f7f838081e8")
result, _ := decoded.Hex()
// []any{"0x7f", "0x7f", "0x8081e8"}
Decodes RLP and returns the result as recursive bytes:
decoded, _ := encoding.FromRlp("0x850123456789")
result, _ := decoded.Bytes()
// []byte{0x01, 0x23, 0x45, 0x67, 0x89}
Encodes data to RLP bytes:
encoded, _ := encoding.RlpEncode("0x123456789")
// []byte{0x85, 0x01, 0x23, 0x45, 0x67, 0x89}
Encodes data to RLP hex string:
encoded, _ := encoding.RlpEncodeToHex("0x123456789")
// "0x850123456789"
Decodes RLP bytes:
decoded, _ := encoding.RlpDecode([]byte{0x85, 0x01, 0x23, 0x45, 0x67, 0x89})
// []byte{0x01, 0x23, 0x45, 0x67, 0x89}
Decodes RLP hex string:
decoded, _ := encoding.RlpDecodeHex("0x850123456789")
// []byte{0x01, 0x23, 0x45, 0x67, 0x89}
0x80 + length followed by bytes0xb7 + length_of_length followed by length and bytes0xc0 + length followed by items0xf7 + length_of_length followed by length and items