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) } }