From 8371bee88deb9a99922d7e1107e9eb8754fc4dc7 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Thu, 24 Aug 2023 11:21:17 +0200 Subject: [PATCH] xdr: Add function to obtain the type of a binary-compressed key (#5026) --- xdr/main.go | 13 +++++++++++++ xdr/main_test.go | 5 ++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/xdr/main.go b/xdr/main.go index 0428b0813a..04d0204508 100644 --- a/xdr/main.go +++ b/xdr/main.go @@ -13,6 +13,7 @@ import ( "strings" xdr "github.com/stellar/go-xdr/xdr3" + "github.com/stellar/go/support/errors" ) @@ -230,6 +231,18 @@ func (e *EncodingBuffer) LedgerKeyUnsafeMarshalBinaryCompress(key LedgerKey) ([] return e.xdrEncoderBuf.Bytes(), nil } +// GetBinaryCompressedLedgerKeyType gets the key type from the result of LedgerKeyUnsafeMarshalBinaryCompress +func GetBinaryCompressedLedgerKeyType(compressedKey []byte) (LedgerEntryType, error) { + if len(compressedKey) < 1 { + return 0, errors.New("empty compressed ledger key") + } + result := LedgerEntryType(compressedKey[0]) + if int(result) > len(ledgerEntryTypeMap)-1 { + return 0, fmt.Errorf("incorrect key type %d", result) + } + return result, nil +} + func (e *EncodingBuffer) MarshalBase64(encodable EncoderTo) (string, error) { b, err := e.UnsafeMarshalBase64(encodable) if err != nil { diff --git a/xdr/main_test.go b/xdr/main_test.go index f9bc846448..42d280f4b1 100644 --- a/xdr/main_test.go +++ b/xdr/main_test.go @@ -217,8 +217,11 @@ func TestLedgerKeyBinaryCompressCoverage(t *testing.T) { ) assert.NoError(t, gxdr.Convert(shape, &ledgerKey)) - _, err := e.LedgerKeyUnsafeMarshalBinaryCompress(ledgerKey) + compressed, err := e.LedgerKeyUnsafeMarshalBinaryCompress(ledgerKey) assert.NoError(t, err) + keyType, err := GetBinaryCompressedLedgerKeyType(compressed) + assert.NoError(t, err) + assert.Equal(t, ledgerKey.Type, keyType) } }