From b1f9139ca50ddeb88d395dca2021ab1bdade20b6 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 26 Aug 2022 10:39:18 +0530 Subject: [PATCH] Use a fully random async_id rather than a uuid --- tools/cmd/at/template.go | 2 +- tools/utils/short-uuid.go | 17 +++++++++++++++++ tools/utils/short-uuid_test.go | 4 ++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/tools/cmd/at/template.go b/tools/cmd/at/template.go index 6b58983a0..ef4bc7e86 100644 --- a/tools/cmd/at/template.go +++ b/tools/cmd/at/template.go @@ -39,7 +39,7 @@ func create_rc_CMD_NAME(args []string) (*utils.RemoteControlCmd, error) { NoResponse: NO_RESPONSE_BASE, } if IS_ASYNC { - async_id, err := utils.HumanUUID4() + async_id, err := utils.HumanRandomId(128) if err != nil { return nil, err } diff --git a/tools/utils/short-uuid.go b/tools/utils/short-uuid.go index 7f1eb074b..ebdd43b6b 100644 --- a/tools/utils/short-uuid.go +++ b/tools/utils/short-uuid.go @@ -3,6 +3,7 @@ package utils import ( + "crypto/rand" "math" "math/big" @@ -70,6 +71,15 @@ func CreateShortUUID(alphabet string) *ShortUUID { return &ans } +func (self *ShortUUID) Random(num_bits int64) (string, error) { + max := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(num_bits), nil) + bi, err := rand.Int(rand.Reader, max) + if err != nil { + return "", err + } + return num_to_string(bi, self.alphabet, &self.alphabet_len, self.pad_to_length), nil +} + func (self *ShortUUID) Uuid4() (string, error) { b, err := uuid.NewRandom() if err != nil { @@ -92,3 +102,10 @@ func HumanUUID4() (string, error) { } return HumanUUID.Uuid4() } + +func HumanRandomId(num_bits int64) (string, error) { + if HumanUUID == nil { + HumanUUID = CreateShortUUID(HUMAN_ALPHABET) + } + return HumanUUID.Random(num_bits) +} diff --git a/tools/utils/short-uuid_test.go b/tools/utils/short-uuid_test.go index 8f20dbda0..6a58763f2 100644 --- a/tools/utils/short-uuid_test.go +++ b/tools/utils/short-uuid_test.go @@ -8,11 +8,11 @@ import ( ) func TestShortUUID(t *testing.T) { - a, err := HumanUUID4() + a, err := HumanRandomId(128) if err != nil { t.Fatal(err) } - b, err := HumanUUID4() + b, err := HumanRandomId(128) if err != nil { t.Fatal(err) }