From 87a9670bd37d24397921771a23ce2d39fd0815b6 Mon Sep 17 00:00:00 2001 From: Boris Nagaev Date: Sat, 10 May 2025 23:17:11 -0300 Subject: [PATCH] l402: make TokenID.String() a value method If a TokenID is passed by value to logging functions (such as the Printf family) the pointer-based String() method is not used. As a result, the token is logged as an array when using %v and as binary when using %s, which is inconvenient. --- l402/identifier.go | 2 +- l402/identifier_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/l402/identifier.go b/l402/identifier.go index 776f3ae..e0e7af7 100644 --- a/l402/identifier.go +++ b/l402/identifier.go @@ -37,7 +37,7 @@ var ( type TokenID [TokenIDSize]byte // String returns the hex encoded representation of the token ID as a string. -func (t *TokenID) String() string { +func (t TokenID) String() string { return hex.EncodeToString(t[:]) } diff --git a/l402/identifier_test.go b/l402/identifier_test.go index 55edd1f..550550c 100644 --- a/l402/identifier_test.go +++ b/l402/identifier_test.go @@ -3,9 +3,11 @@ package l402 import ( "bytes" "errors" + "fmt" "testing" "github.com/lightningnetwork/lnd/lntypes" + "github.com/stretchr/testify/require" ) var ( @@ -67,3 +69,36 @@ func TestIdentifierSerialization(t *testing.T) { } } } + +// TestTokenIDString makes sure that TokenID is logged properly in Printf +// function family. +func TestTokenIDString(t *testing.T) { + cases := []struct { + token TokenID + formatString string + wantText string + }{ + { + token: TokenID{1, 2, 3}, + formatString: "client %v paid", + wantText: "client 01020300000000000000000000000000000" + + "00000000000000000000000000000 paid", + }, + { + token: TokenID{1, 2, 3}, + formatString: "client %s paid", + wantText: "client 01020300000000000000000000000000000" + + "00000000000000000000000000000 paid", + }, + } + + for _, tc := range cases { + t.Run(tc.formatString, func(t *testing.T) { + got := fmt.Sprintf(tc.formatString, tc.token) + require.Equal(t, tc.wantText, got) + + got = fmt.Sprintf(tc.formatString, &tc.token) + require.Equal(t, tc.wantText, got) + }) + } +}