diff --git a/cmd/africastalking/main.go b/cmd/africastalking/main.go index 1b43600..8aaacde 100644 --- a/cmd/africastalking/main.go +++ b/cmd/africastalking/main.go @@ -18,7 +18,7 @@ import ( "git.grassecon.net/grassrootseconomics/visedriver/config" "git.grassecon.net/grassrootseconomics/visedriver/initializers" - "git.grassecon.net/grassrootseconomics/visedriver/common" + "git.grassecon.net/grassrootseconomics/visedriver/storage" "git.grassecon.net/grassrootseconomics/visedriver/session" at "git.grassecon.net/grassrootseconomics/visedriver-africastalking/africastalking" @@ -67,7 +67,7 @@ func main() { if connStr == "" { connStr = config.DbConn } - connData, err := common.ToConnData(config.DbConn) + connData, err := storage.ToConnData(config.DbConn) if err != nil { fmt.Fprintf(os.Stderr, "connstr err: %v", err) os.Exit(1) @@ -97,12 +97,7 @@ func main() { cfg.EngineDebug = true } - menuStorageService, err := common.NewStorageService(connData) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - + menuStorageService := storage.NewMenuStorageService(connData, "") rs, err := menuStorageService.GetResource(ctx) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) diff --git a/cmd/main.go b/cmd/main.go index 72ab974..1a7d218 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -13,7 +13,7 @@ import ( "git.defalsify.org/vise.git/lang" "git.grassecon.net/grassrootseconomics/visedriver/config" "git.grassecon.net/grassrootseconomics/visedriver/initializers" - "git.grassecon.net/grassrootseconomics/visedriver/common" + "git.grassecon.net/grassrootseconomics/visedriver/storage" httpremote "git.grassecon.net/grassrootseconomics/sarafu-api/remote/http" "git.grassecon.net/grassrootseconomics/sarafu-vise/args" "git.grassecon.net/grassrootseconomics/sarafu-vise/handlers" @@ -55,7 +55,7 @@ func main() { if connStr != "" { connStr = config.DbConn } - connData, err := common.ToConnData(connStr) + connData, err := storage.ToConnData(connStr) if err != nil { fmt.Fprintf(os.Stderr, "connstr err: %v", err) os.Exit(1) @@ -88,7 +88,7 @@ func main() { MenuSeparator: menuSeparator, } - menuStorageService, err := common.NewStorageService(connData) + menuStorageService := storage.NewMenuStorageService(connData, "") if err != nil { fmt.Fprintf(os.Stderr, "menu storage service error: %v", err) os.Exit(1) diff --git a/devtools/store/dump/main.go b/devtools/store/dump/main.go new file mode 100644 index 0000000..005e3b1 --- /dev/null +++ b/devtools/store/dump/main.go @@ -0,0 +1,100 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "path" + + "git.grassecon.net/grassrootseconomics/visedriver/config" + "git.grassecon.net/grassrootseconomics/visedriver/initializers" + "git.grassecon.net/grassrootseconomics/visedriver/storage" + "git.grassecon.net/grassrootseconomics/sarafu-vise/debug" + "git.defalsify.org/vise.git/db" + "git.defalsify.org/vise.git/logging" +) + +var ( + logg = logging.NewVanilla() + scriptDir = path.Join("services", "registration") +) + +func init() { + initializers.LoadEnvVariables() +} + + +func formatItem(k []byte, v []byte) (string, error) { + o, err := debug.FromKey(k) + if err != nil { + return "", err + } + s := fmt.Sprintf("%vValue: %v\n\n", o, string(v)) + return s, nil +} + +func main() { + config.LoadConfig() + + var connStr string + var sessionId string + var database string + var engineDebug bool + var err error + + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + flag.StringVar(&connStr, "c", ".state", "connection string") + flag.BoolVar(&engineDebug, "d", false, "use engine debug output") + flag.Parse() + + if connStr != "" { + connStr = config.DbConn + } + connData, err := storage.ToConnData(config.DbConn) + if err != nil { + fmt.Fprintf(os.Stderr, "connstr err: %v", err) + os.Exit(1) + } + + logg.Infof("start command", "conn", connData) + + ctx := context.Background() + ctx = context.WithValue(ctx, "SessionId", sessionId) + ctx = context.WithValue(ctx, "Database", database) + + resourceDir := scriptDir + menuStorageService := storage.NewMenuStorageService(connData, resourceDir) + + store, err := menuStorageService.GetUserdataDb(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, "get userdata db: %v\n", err.Error()) + os.Exit(1) + } + store.SetPrefix(db.DATATYPE_USERDATA) + + d, err := store.Dump(ctx, []byte(sessionId)) + if err != nil { + fmt.Fprintf(os.Stderr, "store dump fail: %v\n", err.Error()) + os.Exit(1) + } + + for true { + k, v := d.Next(ctx) + if k == nil { + break + } + r, err := formatItem(k, v) + if err != nil { + fmt.Fprintf(os.Stderr, "format db item error: %v", err) + os.Exit(1) + } + fmt.Printf(r) + } + + err = store.Close() + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } +} diff --git a/devtools/store/generate/main.go b/devtools/store/generate/main.go new file mode 100644 index 0000000..c055717 --- /dev/null +++ b/devtools/store/generate/main.go @@ -0,0 +1,91 @@ +package main + +import ( + "context" + "crypto/sha1" + "flag" + "fmt" + "os" + "path" + + testdataloader "github.com/peteole/testdata-loader" + "git.defalsify.org/vise.git/logging" + "git.grassecon.net/grassrootseconomics/visedriver/config" + "git.grassecon.net/grassrootseconomics/visedriver/storage" + "git.grassecon.net/grassrootseconomics/visedriver/initializers" + "git.grassecon.net/grassrootseconomics/sarafu-vise/store" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" +) + +var ( + logg = logging.NewVanilla() + baseDir = testdataloader.GetBasePath() + scriptDir = path.Join("services", "registration") +) + +func init() { + initializers.LoadEnvVariables() +} + +func main() { + config.LoadConfig() + + var connStr string + var sessionId string + var database string + var engineDebug bool + var err error + + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + flag.StringVar(&connStr, "c", "", "connection string") + flag.BoolVar(&engineDebug, "d", false, "use engine debug output") + flag.Parse() + + if connStr != "" { + connStr = config.DbConn + } + connData, err := storage.ToConnData(config.DbConn) + if err != nil { + fmt.Fprintf(os.Stderr, "connstr err: %v", err) + os.Exit(1) + } + + logg.Infof("start command", "conn", connData) + + ctx := context.Background() + ctx = context.WithValue(ctx, "SessionId", sessionId) + ctx = context.WithValue(ctx, "Database", database) + + resourceDir := scriptDir + menuStorageService := storage.NewMenuStorageService(connData, resourceDir) + + userDb, err := menuStorageService.GetUserdataDb(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + userStore := store.UserDataStore{userDb} + + h := sha1.New() + h.Write([]byte(sessionId)) + address := h.Sum(nil) + addressString := fmt.Sprintf("%x", address) + + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(addressString)) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + err = userStore.WriteEntry(ctx, addressString, storedb.DATA_PUBLIC_KEY_REVERSE, []byte(sessionId)) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + err = userDb.Close() + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } +} diff --git a/go.mod b/go.mod index d97d956..a4d8e1c 100644 --- a/go.mod +++ b/go.mod @@ -4,16 +4,17 @@ go 1.23.4 require ( git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d + git.grassecon.net/grassrootseconomics/common v0.0.0-20250112090451-d33e94fda029 git.grassecon.net/grassrootseconomics/sarafu-api v0.0.0-20250111211303-3ea726a0302c - git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250111222109-2ea51d88d8c0 - git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250111212417-1f8ba0d7ff9b + git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250112075903-5b312f9569f0 + git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250112092227-e0892ac0be76 github.com/alecthomas/assert/v2 v2.2.2 github.com/gofrs/uuid v4.4.0+incompatible github.com/grassrootseconomics/ussd-data-service v1.2.0-beta github.com/jackc/pgx/v5 v5.7.1 github.com/peteole/testdata-loader v0.3.0 github.com/stretchr/testify v1.9.0 - golang.org/x/crypto v0.27.0 + golang.org/x/crypto v0.32.0 gopkg.in/leonelquinteros/gotext.v1 v1.3.1 ) @@ -34,8 +35,8 @@ require ( github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/x448/float16 v0.8.4 // indirect - golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.25.0 // indirect - golang.org/x/text v0.18.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/text v0.21.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index d36f18a..4a31d94 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,13 @@ git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d h1:bPAOVZOX4frSGhfOdcj7kc555f8dc9DmMd2YAyC2AMw= git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d/go.mod h1:jyBMe1qTYUz3mmuoC9JQ/TvFeW0vTanCUcPu3H8p4Ck= +git.grassecon.net/grassrootseconomics/common v0.0.0-20250112090451-d33e94fda029 h1:UKi91cAsxexbVKVuD1YBU/VF5+50ryyohfeJ4heSkVs= +git.grassecon.net/grassrootseconomics/common v0.0.0-20250112090451-d33e94fda029/go.mod h1:WcWUIkf9vKW4Vy+hc1QJORFZgMLtVQiTWoObue5EQ+8= git.grassecon.net/grassrootseconomics/sarafu-api v0.0.0-20250111211303-3ea726a0302c h1:5h1nsczPXBhOfe5Wbyccp3ontooztKUVAtDw8aoT8BI= git.grassecon.net/grassrootseconomics/sarafu-api v0.0.0-20250111211303-3ea726a0302c/go.mod h1:CXdVutRsCkdWWCJ9hELi/72z3FDKkhLksxCXBSnjuKI= -git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250111222109-2ea51d88d8c0 h1:jzYZKsZBuho4kt0dEWqflXHPLM7tWxpNmXTGFP615dE= -git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250111222109-2ea51d88d8c0/go.mod h1:E6W7ZOa7ZvVr0Bc5ot0LNSwpSPYq4hXlAIvEPy3AJ7U= -git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250111212417-1f8ba0d7ff9b h1:3bM4VFf3h3EoqeEtMiT49ymklpIUgBFnT53V246gy1g= -git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250111212417-1f8ba0d7ff9b/go.mod h1:0vbG2P/BSIfKgI8GbhBTQ+YfPMptgbiGxz6CpZDYi3w= +git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250112075903-5b312f9569f0 h1:gICHTIEhiBv3SJ7kdcogUIGtfmoaWvZGalp2sBRj2c0= +git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250112075903-5b312f9569f0/go.mod h1:E6W7ZOa7ZvVr0Bc5ot0LNSwpSPYq4hXlAIvEPy3AJ7U= +git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250112092227-e0892ac0be76 h1:3v0Q/baP/8FEe4kl2DC6pirMgFOAbn69O2f5ddOjcoI= +git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250112092227-e0892ac0be76/go.mod h1:JEfOHnOCCwH8s7eevu4ImTdO8oQwRD/bqYtmfT/pwzQ= github.com/alecthomas/assert/v2 v2.2.2 h1:Z/iVC0xZfWTaFNE6bA3z07T86hd45Xe2eLt6WVy2bbk= github.com/alecthomas/assert/v2 v2.2.2/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= github.com/alecthomas/participle/v2 v2.0.0 h1:Fgrq+MbuSsJwIkw3fEj9h75vDP0Er5JzepJ0/HNHv0g= @@ -63,16 +65,16 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= -golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= -golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM= -golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8= -golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= -golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= +golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg= +golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/handlers/application/menuhandler.go b/handlers/application/menuhandler.go index 8da7a84..c9a1103 100644 --- a/handlers/application/menuhandler.go +++ b/handlers/application/menuhandler.go @@ -18,15 +18,17 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/grassrootseconomics/visedriver/common" - "git.grassecon.net/grassrootseconomics/visedriver/utils" - + dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api" "git.grassecon.net/grassrootseconomics/sarafu-vise/profile" "git.grassecon.net/grassrootseconomics/sarafu-vise/store" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" "git.grassecon.net/grassrootseconomics/sarafu-api/remote" - - dbstorage "git.grassecon.net/grassrootseconomics/visedriver/storage/db" - dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api" + "git.grassecon.net/grassrootseconomics/common/hex" + commonlang "git.grassecon.net/grassrootseconomics/common/lang" + "git.grassecon.net/grassrootseconomics/common/pin" + "git.grassecon.net/grassrootseconomics/common/person" + "git.grassecon.net/grassrootseconomics/common/phone" + "git.grassecon.net/grassrootseconomics/common/identity" ) var ( @@ -62,11 +64,11 @@ type MenuHandlers struct { pe *persist.Persister st *state.State ca cache.Memory - userdataStore common.DataStore + userdataStore store.DataStore adminstore *store.AdminStore flagManager *asm.FlagParser accountService remote.AccountService - prefixDb dbstorage.PrefixDb + prefixDb storedb.PrefixDb profile *profile.Profile ReplaceSeparatorFunc func(string) string } @@ -76,13 +78,13 @@ func NewMenuHandlers(appFlags *asm.FlagParser, userdataStore db.Db, adminstore * if userdataStore == nil { return nil, fmt.Errorf("cannot create handler with nil userdata store") } - userDb := &common.UserDataStore{ + userDb := &store.UserDataStore{ Db: userdataStore, } // Instantiate the SubPrefixDb with "DATATYPE_USERDATA" prefix - prefix := common.ToBytes(db.DATATYPE_USERDATA) - prefixDb := dbstorage.NewSubPrefixDb(userdataStore, prefix) + prefix := storedb.ToBytes(db.DATATYPE_USERDATA) + prefixDb := storedb.NewSubPrefixDb(userdataStore, prefix) h := &MenuHandlers{ userdataStore: userDb, @@ -162,7 +164,7 @@ func (h *MenuHandlers) SetLanguage(ctx context.Context, sym string, input []byte code := strings.Split(symbol, "_")[1] // TODO: Use defaultlanguage from config - if !utils.IsValidISO639(code) { + if !commonlang.IsValidISO639(code) { //Fallback to english instead? code = "eng" } @@ -192,9 +194,9 @@ func (h *MenuHandlers) createAccountNoExist(ctx context.Context, sessionId strin trackingId := r.TrackingId publicKey := r.PublicKey - data := map[common.DataTyp]string{ - common.DATA_TRACKING_ID: trackingId, - common.DATA_PUBLIC_KEY: publicKey, + data := map[storedb.DataTyp]string{ + storedb.DATA_TRACKING_ID: trackingId, + storedb.DATA_PUBLIC_KEY: publicKey, } store := h.userdataStore for key, value := range data { @@ -203,11 +205,11 @@ func (h *MenuHandlers) createAccountNoExist(ctx context.Context, sessionId strin return err } } - publicKeyNormalized, err := common.NormalizeHex(publicKey) + publicKeyNormalized, err := hex.NormalizeHex(publicKey) if err != nil { return err } - err = store.WriteEntry(ctx, publicKeyNormalized, common.DATA_PUBLIC_KEY_REVERSE, []byte(sessionId)) + err = store.WriteEntry(ctx, publicKeyNormalized, storedb.DATA_PUBLIC_KEY_REVERSE, []byte(sessionId)) if err != nil { return err } @@ -226,7 +228,7 @@ func (h *MenuHandlers) CreateAccount(ctx context.Context, sym string, input []by return res, fmt.Errorf("missing session") } store := h.userdataStore - _, err = store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + _, err = store.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { if db.IsNotFound(err) { logg.InfoCtxf(ctx, "Creating an account because it doesn't exist") @@ -251,15 +253,15 @@ func (h *MenuHandlers) CheckBlockedNumPinMisMatch(ctx context.Context, sym strin } // Get blocked number from storage. store := h.userdataStore - blockedNumber, err := store.ReadEntry(ctx, sessionId, common.DATA_BLOCKED_NUMBER) + blockedNumber, err := store.ReadEntry(ctx, sessionId, storedb.DATA_BLOCKED_NUMBER) if err != nil { - logg.ErrorCtxf(ctx, "failed to read blockedNumber entry with", "key", common.DATA_BLOCKED_NUMBER, "error", err) + logg.ErrorCtxf(ctx, "failed to read blockedNumber entry with", "key", storedb.DATA_BLOCKED_NUMBER, "error", err) return res, err } // Get temporary PIN for the blocked number. - temporaryPin, err := store.ReadEntry(ctx, string(blockedNumber), common.DATA_TEMPORARY_VALUE) + temporaryPin, err := store.ReadEntry(ctx, string(blockedNumber), storedb.DATA_TEMPORARY_VALUE) if err != nil { - logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", common.DATA_TEMPORARY_VALUE, "error", err) + logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) return res, err } if bytes.Equal(temporaryPin, input) { @@ -280,7 +282,7 @@ func (h *MenuHandlers) VerifyNewPin(ctx context.Context, sym string, input []byt flag_valid_pin, _ := h.flagManager.GetFlag("flag_valid_pin") pinInput := string(input) // Validate that the PIN is a 4-digit number. - if common.IsValidPIN(pinInput) { + if pin.IsValidPIN(pinInput) { res.FlagSet = append(res.FlagSet, flag_valid_pin) } else { res.FlagReset = append(res.FlagReset, flag_valid_pin) @@ -305,15 +307,15 @@ func (h *MenuHandlers) SaveTemporaryPin(ctx context.Context, sym string, input [ accountPIN := string(input) // Validate that the PIN is a 4-digit number. - if !common.IsValidPIN(accountPIN) { + if !pin.IsValidPIN(accountPIN) { res.FlagSet = append(res.FlagSet, flag_incorrect_pin) return res, nil } res.FlagReset = append(res.FlagReset, flag_incorrect_pin) store := h.userdataStore - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(accountPIN)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(accountPIN)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryAccountPIN entry with", "key", common.DATA_TEMPORARY_VALUE, "value", accountPIN, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryAccountPIN entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", accountPIN, "error", err) return res, err } @@ -332,16 +334,16 @@ func (h *MenuHandlers) SaveOthersTemporaryPin(ctx context.Context, sym string, i } temporaryPin := string(input) // First, we retrieve the blocked number associated with this session - blockedNumber, err := store.ReadEntry(ctx, sessionId, common.DATA_BLOCKED_NUMBER) + blockedNumber, err := store.ReadEntry(ctx, sessionId, storedb.DATA_BLOCKED_NUMBER) if err != nil { - logg.ErrorCtxf(ctx, "failed to read blockedNumber entry with", "key", common.DATA_BLOCKED_NUMBER, "error", err) + logg.ErrorCtxf(ctx, "failed to read blockedNumber entry with", "key", storedb.DATA_BLOCKED_NUMBER, "error", err) return res, err } // Then we save the temporary PIN for that blocked number - err = store.WriteEntry(ctx, string(blockedNumber), common.DATA_TEMPORARY_VALUE, []byte(temporaryPin)) + err = store.WriteEntry(ctx, string(blockedNumber), storedb.DATA_TEMPORARY_VALUE, []byte(temporaryPin)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryPin entry with", "key", common.DATA_TEMPORARY_VALUE, "value", temporaryPin, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryPin entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", temporaryPin, "error", err) return res, err } @@ -358,9 +360,9 @@ func (h *MenuHandlers) ConfirmPinChange(ctx context.Context, sym string, input [ flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") store := h.userdataStore - temporaryPin, err := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) + temporaryPin, err := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) if err != nil { - logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", common.DATA_TEMPORARY_VALUE, "error", err) + logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) return res, err } if bytes.Equal(temporaryPin, input) { @@ -371,16 +373,16 @@ func (h *MenuHandlers) ConfirmPinChange(ctx context.Context, sym string, input [ } // Hash the PIN - hashedPIN, err := common.HashPIN(string(temporaryPin)) + hashedPIN, err := pin.HashPIN(string(temporaryPin)) if err != nil { logg.ErrorCtxf(ctx, "failed to hash temporaryPin", "error", err) return res, err } // save the hashed PIN as the new account PIN - err = store.WriteEntry(ctx, sessionId, common.DATA_ACCOUNT_PIN, []byte(hashedPIN)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACCOUNT_PIN, []byte(hashedPIN)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write DATA_ACCOUNT_PIN entry with", "key", common.DATA_ACCOUNT_PIN, "hashedPIN value", hashedPIN, "error", err) + logg.ErrorCtxf(ctx, "failed to write DATA_ACCOUNT_PIN entry with", "key", storedb.DATA_ACCOUNT_PIN, "hashedPIN value", hashedPIN, "error", err) return res, err } return res, nil @@ -401,9 +403,9 @@ func (h *MenuHandlers) VerifyCreatePin(ctx context.Context, sym string, input [] return res, fmt.Errorf("missing session") } store := h.userdataStore - temporaryPin, err := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) + temporaryPin, err := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) if err != nil { - logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", common.DATA_TEMPORARY_VALUE, "error", err) + logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) return res, err } if bytes.Equal(input, temporaryPin) { @@ -416,15 +418,15 @@ func (h *MenuHandlers) VerifyCreatePin(ctx context.Context, sym string, input [] } // Hash the PIN - hashedPIN, err := common.HashPIN(string(temporaryPin)) + hashedPIN, err := pin.HashPIN(string(temporaryPin)) if err != nil { logg.ErrorCtxf(ctx, "failed to hash temporaryPin", "error", err) return res, err } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACCOUNT_PIN, []byte(hashedPIN)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACCOUNT_PIN, []byte(hashedPIN)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write DATA_ACCOUNT_PIN entry with", "key", common.DATA_ACCOUNT_PIN, "value", hashedPIN, "error", err) + logg.ErrorCtxf(ctx, "failed to write DATA_ACCOUNT_PIN entry with", "key", storedb.DATA_ACCOUNT_PIN, "value", hashedPIN, "error", err) return res, err } @@ -457,18 +459,18 @@ func (h *MenuHandlers) SaveFirstname(ctx context.Context, sym string, input []by allowUpdate := h.st.MatchFlag(flag_allow_update, true) firstNameSet := h.st.MatchFlag(flag_firstname_set, true) if allowUpdate { - temporaryFirstName, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_FIRST_NAME, []byte(temporaryFirstName)) + temporaryFirstName, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_FIRST_NAME, []byte(temporaryFirstName)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write firstName entry with", "key", common.DATA_FIRST_NAME, "value", temporaryFirstName, "error", err) + logg.ErrorCtxf(ctx, "failed to write firstName entry with", "key", storedb.DATA_FIRST_NAME, "value", temporaryFirstName, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_firstname_set) } else { if firstNameSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(firstName)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(firstName)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryFirstName entry with", "key", common.DATA_TEMPORARY_VALUE, "value", firstName, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryFirstName entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", firstName, "error", err) return res, err } } else { @@ -497,18 +499,18 @@ func (h *MenuHandlers) SaveFamilyname(ctx context.Context, sym string, input []b familyNameSet := h.st.MatchFlag(flag_familyname_set, true) if allowUpdate { - temporaryFamilyName, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_FAMILY_NAME, []byte(temporaryFamilyName)) + temporaryFamilyName, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_FAMILY_NAME, []byte(temporaryFamilyName)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write familyName entry with", "key", common.DATA_FAMILY_NAME, "value", temporaryFamilyName, "error", err) + logg.ErrorCtxf(ctx, "failed to write familyName entry with", "key", storedb.DATA_FAMILY_NAME, "value", temporaryFamilyName, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_familyname_set) } else { if familyNameSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(familyName)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(familyName)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryFamilyName entry with", "key", common.DATA_TEMPORARY_VALUE, "value", familyName, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryFamilyName entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", familyName, "error", err) return res, err } } else { @@ -536,18 +538,18 @@ func (h *MenuHandlers) SaveYob(ctx context.Context, sym string, input []byte) (r yobSet := h.st.MatchFlag(flag_yob_set, true) if allowUpdate { - temporaryYob, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_YOB, []byte(temporaryYob)) + temporaryYob, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_YOB, []byte(temporaryYob)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write yob entry with", "key", common.DATA_TEMPORARY_VALUE, "value", temporaryYob, "error", err) + logg.ErrorCtxf(ctx, "failed to write yob entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", temporaryYob, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_yob_set) } else { if yobSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(yob)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(yob)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryYob entry with", "key", common.DATA_TEMPORARY_VALUE, "value", yob, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryYob entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", yob, "error", err) return res, err } } else { @@ -575,18 +577,18 @@ func (h *MenuHandlers) SaveLocation(ctx context.Context, sym string, input []byt locationSet := h.st.MatchFlag(flag_location_set, true) if allowUpdate { - temporaryLocation, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_LOCATION, []byte(temporaryLocation)) + temporaryLocation, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_LOCATION, []byte(temporaryLocation)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write location entry with", "key", common.DATA_LOCATION, "value", temporaryLocation, "error", err) + logg.ErrorCtxf(ctx, "failed to write location entry with", "key", storedb.DATA_LOCATION, "value", temporaryLocation, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_location_set) } else { if locationSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(location)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(location)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryLocation entry with", "key", common.DATA_TEMPORARY_VALUE, "value", location, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryLocation entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", location, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_location_set) @@ -616,18 +618,18 @@ func (h *MenuHandlers) SaveGender(ctx context.Context, sym string, input []byte) genderSet := h.st.MatchFlag(flag_gender_set, true) if allowUpdate { - temporaryGender, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_GENDER, []byte(temporaryGender)) + temporaryGender, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_GENDER, []byte(temporaryGender)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write gender entry with", "key", common.DATA_GENDER, "value", gender, "error", err) + logg.ErrorCtxf(ctx, "failed to write gender entry with", "key", storedb.DATA_GENDER, "value", gender, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_gender_set) } else { if genderSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(gender)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(gender)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryGender entry with", "key", common.DATA_TEMPORARY_VALUE, "value", gender, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryGender entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", gender, "error", err) return res, err } } else { @@ -657,18 +659,18 @@ func (h *MenuHandlers) SaveOfferings(ctx context.Context, sym string, input []by offeringsSet := h.st.MatchFlag(flag_offerings_set, true) if allowUpdate { - temporaryOfferings, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) - err = store.WriteEntry(ctx, sessionId, common.DATA_OFFERINGS, []byte(temporaryOfferings)) + temporaryOfferings, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_OFFERINGS, []byte(temporaryOfferings)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write offerings entry with", "key", common.DATA_TEMPORARY_VALUE, "value", offerings, "error", err) + logg.ErrorCtxf(ctx, "failed to write offerings entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", offerings, "error", err) return res, err } res.FlagSet = append(res.FlagSet, flag_offerings_set) } else { if offeringsSet { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(offerings)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(offerings)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryOfferings entry with", "key", common.DATA_TEMPORARY_VALUE, "value", offerings, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryOfferings entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", offerings, "error", err) return res, err } } else { @@ -711,7 +713,7 @@ func (h *MenuHandlers) CheckIdentifier(ctx context.Context, sym string, input [] return res, fmt.Errorf("missing session") } store := h.userdataStore - publicKey, _ := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + publicKey, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) res.Content = string(publicKey) @@ -732,13 +734,13 @@ func (h *MenuHandlers) Authorize(ctx context.Context, sym string, input []byte) flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") store := h.userdataStore - AccountPin, err := store.ReadEntry(ctx, sessionId, common.DATA_ACCOUNT_PIN) + AccountPin, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACCOUNT_PIN) if err != nil { - logg.ErrorCtxf(ctx, "failed to read AccountPin entry with", "key", common.DATA_ACCOUNT_PIN, "error", err) + logg.ErrorCtxf(ctx, "failed to read AccountPin entry with", "key", storedb.DATA_ACCOUNT_PIN, "error", err) return res, err } if len(input) == 4 { - if common.VerifyPIN(string(AccountPin), string(input)) { + if pin.VerifyPIN(string(AccountPin), string(input)) { if h.st.MatchFlag(flag_account_authorized, false) { res.FlagReset = append(res.FlagReset, flag_incorrect_pin) res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) @@ -784,19 +786,19 @@ func (h *MenuHandlers) ResetIncorrectPin(ctx context.Context, sym string, input res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS) + currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS) if err != nil { if !db.IsNotFound(err) { return res, err } } pinAttemptsValue, _ := strconv.ParseUint(string(currentWrongPinAttempts), 0, 64) - remainingPINAttempts := common.AllowedPINAttempts - uint8(pinAttemptsValue) + remainingPINAttempts := pin.AllowedPINAttempts - uint8(pinAttemptsValue) if remainingPINAttempts == 0 { res.FlagSet = append(res.FlagSet, flag_account_blocked) return res, nil } - if remainingPINAttempts < common.AllowedPINAttempts { + if remainingPINAttempts < pin.AllowedPINAttempts { res.Content = strconv.Itoa(int(remainingPINAttempts)) } @@ -830,9 +832,9 @@ func (h *MenuHandlers) CheckAccountStatus(ctx context.Context, sym string, input } store := h.userdataStore - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + publicKey, err := store.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } @@ -910,7 +912,7 @@ func (h *MenuHandlers) VerifyYob(ctx context.Context, sym string, input []byte) return res, nil } - if utils.IsValidYOb(date) { + if person.IsValidYOb(date) { res.FlagReset = append(res.FlagReset, flag_incorrect_date_format) } else { res.FlagSet = append(res.FlagSet, flag_incorrect_date_format) @@ -945,7 +947,7 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt store := h.userdataStore // get the active sym and active balance - activeSym, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_SYM) + activeSym, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM) if err != nil { if db.IsNotFound(err) { balance := "0.00" @@ -953,13 +955,13 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt return res, nil } - logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", common.DATA_ACTIVE_SYM, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", storedb.DATA_ACTIVE_SYM, "error", err) return res, err } - activeBal, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_BAL) + activeBal, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL) if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", common.DATA_ACTIVE_BAL, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) return res, err } @@ -1003,25 +1005,25 @@ func (h *MenuHandlers) ResetOthersPin(ctx context.Context, sym string, input []b if !ok { return res, fmt.Errorf("missing session") } - blockedPhonenumber, err := store.ReadEntry(ctx, sessionId, common.DATA_BLOCKED_NUMBER) + blockedPhonenumber, err := store.ReadEntry(ctx, sessionId, storedb.DATA_BLOCKED_NUMBER) if err != nil { - logg.ErrorCtxf(ctx, "failed to read blockedPhonenumber entry with", "key", common.DATA_BLOCKED_NUMBER, "error", err) + logg.ErrorCtxf(ctx, "failed to read blockedPhonenumber entry with", "key", storedb.DATA_BLOCKED_NUMBER, "error", err) return res, err } - temporaryPin, err := store.ReadEntry(ctx, string(blockedPhonenumber), common.DATA_TEMPORARY_VALUE) + temporaryPin, err := store.ReadEntry(ctx, string(blockedPhonenumber), storedb.DATA_TEMPORARY_VALUE) if err != nil { - logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", common.DATA_TEMPORARY_VALUE, "error", err) + logg.ErrorCtxf(ctx, "failed to read temporaryPin entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) return res, err } // Hash the PIN - hashedPIN, err := common.HashPIN(string(temporaryPin)) + hashedPIN, err := pin.HashPIN(string(temporaryPin)) if err != nil { logg.ErrorCtxf(ctx, "failed to hash temporaryPin", "error", err) return res, err } - err = store.WriteEntry(ctx, string(blockedPhonenumber), common.DATA_ACCOUNT_PIN, []byte(hashedPIN)) + err = store.WriteEntry(ctx, string(blockedPhonenumber), storedb.DATA_ACCOUNT_PIN, []byte(hashedPIN)) if err != nil { return res, nil } @@ -1051,8 +1053,8 @@ func (h *MenuHandlers) ValidateBlockedNumber(ctx context.Context, sym string, in return res, fmt.Errorf("missing session") } blockedNumber := string(input) - _, err = store.ReadEntry(ctx, blockedNumber, common.DATA_PUBLIC_KEY) - if !common.IsValidPhoneNumber(blockedNumber) { + _, err = store.ReadEntry(ctx, blockedNumber, storedb.DATA_PUBLIC_KEY) + if !phone.IsValidPhoneNumber(blockedNumber) { res.FlagSet = append(res.FlagSet, flag_unregistered_number) return res, nil } @@ -1066,7 +1068,7 @@ func (h *MenuHandlers) ValidateBlockedNumber(ctx context.Context, sym string, in return res, err } } - err = store.WriteEntry(ctx, sessionId, common.DATA_BLOCKED_NUMBER, []byte(blockedNumber)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_BLOCKED_NUMBER, []byte(blockedNumber)) if err != nil { return res, nil } @@ -1090,7 +1092,7 @@ func (h *MenuHandlers) ValidateRecipient(ctx context.Context, sym string, input recipient := string(input) if recipient != "0" { - recipientType, err := common.CheckRecipient(recipient) + recipientType, err := identity.CheckRecipient(recipient) if err != nil { // Invalid recipient format (not a phone number, address, or valid alias format) res.FlagSet = append(res.FlagSet, flag_invalid_recipient) @@ -1100,23 +1102,23 @@ func (h *MenuHandlers) ValidateRecipient(ctx context.Context, sym string, input } // save the recipient as the temporaryRecipient - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(recipient)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(recipient)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryRecipient entry with", "key", common.DATA_TEMPORARY_VALUE, "value", recipient, "error", err) + logg.ErrorCtxf(ctx, "failed to write temporaryRecipient entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", recipient, "error", err) return res, err } switch recipientType { case "phone number": // format the phone number - formattedNumber, err := common.FormatPhoneNumber(recipient) + formattedNumber, err := phone.FormatPhoneNumber(recipient) if err != nil { logg.ErrorCtxf(ctx, "Failed to format the phone number: %s", recipient, "error", err) return res, err } // Check if the phone number is registered - publicKey, err := store.ReadEntry(ctx, formattedNumber, common.DATA_PUBLIC_KEY) + publicKey, err := store.ReadEntry(ctx, formattedNumber, storedb.DATA_PUBLIC_KEY) if err != nil { if db.IsNotFound(err) { logg.InfoCtxf(ctx, "Unregistered phone number: %s", recipient) @@ -1125,22 +1127,22 @@ func (h *MenuHandlers) ValidateRecipient(ctx context.Context, sym string, input return res, nil } - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } // Save the publicKey as the recipient - err = store.WriteEntry(ctx, sessionId, common.DATA_RECIPIENT, publicKey) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT, publicKey) if err != nil { - logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", common.DATA_RECIPIENT, "value", string(publicKey), "error", err) + logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", storedb.DATA_RECIPIENT, "value", string(publicKey), "error", err) return res, err } case "address": // Save the valid Ethereum address as the recipient - err = store.WriteEntry(ctx, sessionId, common.DATA_RECIPIENT, []byte(recipient)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT, []byte(recipient)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", common.DATA_RECIPIENT, "value", recipient, "error", err) + logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", storedb.DATA_RECIPIENT, "value", recipient, "error", err) return res, err } @@ -1156,9 +1158,9 @@ func (h *MenuHandlers) ValidateRecipient(ctx context.Context, sym string, input } // Alias validation succeeded, save the Ethereum address - err = store.WriteEntry(ctx, sessionId, common.DATA_RECIPIENT, []byte(r.Address)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT, []byte(r.Address)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", common.DATA_RECIPIENT, "value", r.Address, "error", err) + logg.ErrorCtxf(ctx, "failed to write recipient entry with", "key", storedb.DATA_RECIPIENT, "value", r.Address, "error", err) return res, err } } @@ -1181,12 +1183,12 @@ func (h *MenuHandlers) TransactionReset(ctx context.Context, sym string, input [ flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") store := h.userdataStore - err = store.WriteEntry(ctx, sessionId, common.DATA_AMOUNT, []byte("")) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte("")) if err != nil { return res, nil } - err = store.WriteEntry(ctx, sessionId, common.DATA_RECIPIENT, []byte("")) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT, []byte("")) if err != nil { return res, nil } @@ -1210,7 +1212,7 @@ func (h *MenuHandlers) InviteValidRecipient(ctx context.Context, sym string, inp l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - recipient, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) + recipient, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) // TODO // send an invitation SMS @@ -1233,7 +1235,7 @@ func (h *MenuHandlers) ResetTransactionAmount(ctx context.Context, sym string, i flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") store := h.userdataStore - err = store.WriteEntry(ctx, sessionId, common.DATA_AMOUNT, []byte("")) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte("")) if err != nil { return res, nil } @@ -1255,9 +1257,9 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) } store := h.userdataStore - activeBal, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_BAL) + activeBal, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL) if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", common.DATA_ACTIVE_BAL, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) return res, err } @@ -1281,9 +1283,9 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b var balanceValue float64 // retrieve the active balance - activeBal, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_BAL) + activeBal, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL) if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", common.DATA_ACTIVE_BAL, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) return res, err } balanceValue, err = strconv.ParseFloat(string(activeBal), 64) @@ -1309,9 +1311,9 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b // Format the amount with 2 decimal places before saving formattedAmount := fmt.Sprintf("%.2f", inputAmount) - err = store.WriteEntry(ctx, sessionId, common.DATA_AMOUNT, []byte(formattedAmount)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(formattedAmount)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write amount entry with", "key", common.DATA_AMOUNT, "value", formattedAmount, "error", err) + logg.ErrorCtxf(ctx, "failed to write amount entry with", "key", storedb.DATA_AMOUNT, "value", formattedAmount, "error", err) return res, err } @@ -1328,7 +1330,7 @@ func (h *MenuHandlers) GetRecipient(ctx context.Context, sym string, input []byt return res, fmt.Errorf("missing session") } store := h.userdataStore - recipient, _ := store.ReadEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE) + recipient, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) res.Content = string(recipient) @@ -1344,7 +1346,7 @@ func (h *MenuHandlers) RetrieveBlockedNumber(ctx context.Context, sym string, in return res, fmt.Errorf("missing session") } store := h.userdataStore - blockedNumber, _ := store.ReadEntry(ctx, sessionId, common.DATA_BLOCKED_NUMBER) + blockedNumber, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_BLOCKED_NUMBER) res.Content = string(blockedNumber) @@ -1376,13 +1378,13 @@ func (h *MenuHandlers) GetAmount(ctx context.Context, sym string, input []byte) store := h.userdataStore // retrieve the active symbol - activeSym, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_SYM) + activeSym, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM) if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", common.DATA_ACTIVE_SYM, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", storedb.DATA_ACTIVE_SYM, "error", err) return res, err } - amount, _ := store.ReadEntry(ctx, sessionId, common.DATA_AMOUNT) + amount, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_AMOUNT) res.Content = fmt.Sprintf("%s %s", string(amount), string(activeSym)) @@ -1404,12 +1406,12 @@ func (h *MenuHandlers) InitiateTransaction(ctx context.Context, sym string, inpu l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - data, err := common.ReadTransactionData(ctx, h.userdataStore, sessionId) + data, err := store.ReadTransactionData(ctx, h.userdataStore, sessionId) if err != nil { return res, err } - finalAmountStr, err := common.ParseAndScaleAmount(data.Amount, data.ActiveDecimal) + finalAmountStr, err := store.ParseAndScaleAmount(data.Amount, data.ActiveDecimal) if err != nil { return res, err } @@ -1476,7 +1478,7 @@ func (h *MenuHandlers) GetCurrentProfileInfo(ctx context.Context, sym string, in parts := strings.SplitN(sm, "_", 2) filename := parts[1] dbKeyStr := "DATA_" + strings.ToUpper(filename) - dbKey, err := common.StringToDataTyp(dbKeyStr) + dbKey, err := storedb.StringToDataTyp(dbKeyStr) if err != nil { return res, err @@ -1484,75 +1486,75 @@ func (h *MenuHandlers) GetCurrentProfileInfo(ctx context.Context, sym string, in store := h.userdataStore switch dbKey { - case common.DATA_FIRST_NAME: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_FIRST_NAME) + case storedb.DATA_FIRST_NAME: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_FIRST_NAME) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read first name entry with", "key", "error", common.DATA_FIRST_NAME, err) + logg.ErrorCtxf(ctx, "Failed to read first name entry with", "key", "error", storedb.DATA_FIRST_NAME, err) return res, err } res.FlagSet = append(res.FlagSet, flag_firstname_set) res.Content = string(profileInfo) - case common.DATA_FAMILY_NAME: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_FAMILY_NAME) + case storedb.DATA_FAMILY_NAME: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_FAMILY_NAME) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read family name entry with", "key", "error", common.DATA_FAMILY_NAME, err) + logg.ErrorCtxf(ctx, "Failed to read family name entry with", "key", "error", storedb.DATA_FAMILY_NAME, err) return res, err } res.FlagSet = append(res.FlagSet, flag_familyname_set) res.Content = string(profileInfo) - case common.DATA_GENDER: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_GENDER) + case storedb.DATA_GENDER: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_GENDER) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read gender entry with", "key", "error", common.DATA_GENDER, err) + logg.ErrorCtxf(ctx, "Failed to read gender entry with", "key", "error", storedb.DATA_GENDER, err) return res, err } res.FlagSet = append(res.FlagSet, flag_gender_set) res.Content = string(profileInfo) - case common.DATA_YOB: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_YOB) + case storedb.DATA_YOB: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_YOB) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read year of birth(yob) entry with", "key", "error", common.DATA_YOB, err) + logg.ErrorCtxf(ctx, "Failed to read year of birth(yob) entry with", "key", "error", storedb.DATA_YOB, err) return res, err } res.FlagSet = append(res.FlagSet, flag_yob_set) res.Content = string(profileInfo) - case common.DATA_LOCATION: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_LOCATION) + case storedb.DATA_LOCATION: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_LOCATION) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read location entry with", "key", "error", common.DATA_LOCATION, err) + logg.ErrorCtxf(ctx, "Failed to read location entry with", "key", "error", storedb.DATA_LOCATION, err) return res, err } res.FlagSet = append(res.FlagSet, flag_location_set) res.Content = string(profileInfo) - case common.DATA_OFFERINGS: - profileInfo, err = store.ReadEntry(ctx, sessionId, common.DATA_OFFERINGS) + case storedb.DATA_OFFERINGS: + profileInfo, err = store.ReadEntry(ctx, sessionId, storedb.DATA_OFFERINGS) if err != nil { if db.IsNotFound(err) { res.Content = defaultValue break } - logg.ErrorCtxf(ctx, "Failed to read offerings entry with", "key", "error", common.DATA_OFFERINGS, err) + logg.ErrorCtxf(ctx, "Failed to read offerings entry with", "key", "error", storedb.DATA_OFFERINGS, err) return res, err } res.FlagSet = append(res.FlagSet, flag_offerings_set) @@ -1592,21 +1594,21 @@ func (h *MenuHandlers) GetProfileInfo(ctx context.Context, sym string, input []b } store := h.userdataStore // Retrieve user data as strings with fallback to defaultValue - firstName := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_FIRST_NAME)) - familyName := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_FAMILY_NAME)) - yob := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_YOB)) - gender := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_GENDER)) - location := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_LOCATION)) - offerings := getEntryOrDefault(store.ReadEntry(ctx, sessionId, common.DATA_OFFERINGS)) + firstName := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_FIRST_NAME)) + familyName := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_FAMILY_NAME)) + yob := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_YOB)) + gender := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_GENDER)) + location := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_LOCATION)) + offerings := getEntryOrDefault(store.ReadEntry(ctx, sessionId, storedb.DATA_OFFERINGS)) // Construct the full name - name := utils.ConstructName(firstName, familyName, defaultValue) + name := person.ConstructName(firstName, familyName, defaultValue) // Calculate age from year of birth age := defaultValue if yob != defaultValue { if yobInt, err := strconv.Atoi(yob); err == nil { - age = strconv.Itoa(utils.CalculateAgeWithYOB(yobInt)) + age = strconv.Itoa(person.CalculateAgeWithYOB(yobInt)) } else { return res, fmt.Errorf("invalid year of birth: %v", err) } @@ -1637,7 +1639,7 @@ func (h *MenuHandlers) GetProfileInfo(ctx context.Context, sym string, input []b func (h *MenuHandlers) SetDefaultVoucher(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error - store := h.userdataStore + userStore := h.userdataStore sessionId, ok := ctx.Value("SessionId").(string) if !ok { @@ -1647,13 +1649,13 @@ func (h *MenuHandlers) SetDefaultVoucher(ctx context.Context, sym string, input flag_no_active_voucher, _ := h.flagManager.GetFlag("flag_no_active_voucher") // check if the user has an active sym - _, err = store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_SYM) + _, err = userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM) if err != nil { if db.IsNotFound(err) { - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } @@ -1678,37 +1680,38 @@ func (h *MenuHandlers) SetDefaultVoucher(ctx context.Context, sym string, input defaultAddr := firstVoucher.ContractAddress // Scale down the balance - scaledBalance := common.ScaleDownBalance(defaultBal, defaultDec) + scaledBalance := store.ScaleDownBalance(defaultBal, defaultDec) + // TODO: implement atomic transaction // set the active symbol - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_SYM, []byte(defaultSym)) + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM, []byte(defaultSym)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write defaultSym entry with", "key", common.DATA_ACTIVE_SYM, "value", defaultSym, "error", err) + logg.ErrorCtxf(ctx, "failed to write defaultSym entry with", "key", storedb.DATA_ACTIVE_SYM, "value", defaultSym, "error", err) return res, err } // set the active balance - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_BAL, []byte(scaledBalance)) + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL, []byte(scaledBalance)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write defaultBal entry with", "key", common.DATA_ACTIVE_BAL, "value", scaledBalance, "error", err) + logg.ErrorCtxf(ctx, "failed to write defaultBal entry with", "key", storedb.DATA_ACTIVE_BAL, "value", scaledBalance, "error", err) return res, err } // set the active decimals - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_DECIMAL, []byte(defaultDec)) + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_DECIMAL, []byte(defaultDec)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write defaultDec entry with", "key", common.DATA_ACTIVE_DECIMAL, "value", defaultDec, "error", err) + logg.ErrorCtxf(ctx, "failed to write defaultDec entry with", "key", storedb.DATA_ACTIVE_DECIMAL, "value", defaultDec, "error", err) return res, err } // set the active contract address - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_ADDRESS, []byte(defaultAddr)) + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS, []byte(defaultAddr)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write defaultAddr entry with", "key", common.DATA_ACTIVE_ADDRESS, "value", defaultAddr, "error", err) + logg.ErrorCtxf(ctx, "failed to write defaultAddr entry with", "key", storedb.DATA_ACTIVE_ADDRESS, "value", defaultAddr, "error", err) return res, err } return res, nil } - logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", common.DATA_ACTIVE_SYM, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeSym entry with", "key", storedb.DATA_ACTIVE_SYM, "error", err) return res, err } @@ -1726,10 +1729,10 @@ func (h *MenuHandlers) CheckVouchers(ctx context.Context, sym string, input []by return res, fmt.Errorf("missing session") } - store := h.userdataStore - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + userStore := h.userdataStore + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } @@ -1740,7 +1743,7 @@ func (h *MenuHandlers) CheckVouchers(ctx context.Context, sym string, input []by } // check the current active sym and update the data - activeSym, _ := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_SYM) + activeSym, _ := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM) if activeSym != nil { activeSymStr := string(activeSym) @@ -1759,30 +1762,30 @@ func (h *MenuHandlers) CheckVouchers(ctx context.Context, sym string, input []by } // Scale down the balance - scaledBalance := common.ScaleDownBalance(activeData.Balance, activeData.TokenDecimals) + scaledBalance := store.ScaleDownBalance(activeData.Balance, activeData.TokenDecimals) // Update the balance field with the scaled value activeData.Balance = scaledBalance // Pass the matching voucher data to UpdateVoucherData - if err := common.UpdateVoucherData(ctx, h.userdataStore, sessionId, activeData); err != nil { + if err := store.UpdateVoucherData(ctx, h.userdataStore, sessionId, activeData); err != nil { logg.ErrorCtxf(ctx, "failed on UpdateVoucherData", "error", err) return res, err } } - data := common.ProcessVouchers(vouchersResp) + data := store.ProcessVouchers(vouchersResp) // Store all voucher data - dataMap := map[common.DataTyp]string{ - common.DATA_VOUCHER_SYMBOLS: data.Symbols, - common.DATA_VOUCHER_BALANCES: data.Balances, - common.DATA_VOUCHER_DECIMALS: data.Decimals, - common.DATA_VOUCHER_ADDRESSES: data.Addresses, + dataMap := map[storedb.DataTyp]string{ + storedb.DATA_VOUCHER_SYMBOLS: data.Symbols, + storedb.DATA_VOUCHER_BALANCES: data.Balances, + storedb.DATA_VOUCHER_DECIMALS: data.Decimals, + storedb.DATA_VOUCHER_ADDRESSES: data.Addresses, } for key, value := range dataMap { - if err := h.prefixDb.Put(ctx, []byte(common.ToBytes(key)), []byte(value)); err != nil { + if err := h.prefixDb.Put(ctx, []byte(storedb.ToBytes(key)), []byte(value)); err != nil { return res, nil } } @@ -1795,7 +1798,7 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b var res resource.Result // Read vouchers from the store - voucherData, err := h.prefixDb.Get(ctx, common.ToBytes(common.DATA_VOUCHER_SYMBOLS)) + voucherData, err := h.prefixDb.Get(ctx, storedb.ToBytes(storedb.DATA_VOUCHER_SYMBOLS)) if err != nil { logg.ErrorCtxf(ctx, "Failed to read the voucherData from prefixDb", "error", err) return res, err @@ -1829,7 +1832,7 @@ func (h *MenuHandlers) ViewVoucher(ctx context.Context, sym string, input []byte return res, nil } - metadata, err := common.GetVoucherData(ctx, h.prefixDb, inputStr) + metadata, err := store.GetVoucherData(ctx, h.prefixDb, inputStr) if err != nil { return res, fmt.Errorf("failed to retrieve voucher data: %v", err) } @@ -1839,7 +1842,7 @@ func (h *MenuHandlers) ViewVoucher(ctx context.Context, sym string, input []byte return res, nil } - if err := common.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) return res, err } @@ -1860,14 +1863,14 @@ func (h *MenuHandlers) SetVoucher(ctx context.Context, sym string, input []byte) } // Get temporary data - tempData, err := common.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + tempData, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) if err != nil { logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) return res, err } // Set as active and clear temporary data - if err := common.UpdateVoucherData(ctx, h.userdataStore, sessionId, tempData); err != nil { + if err := store.UpdateVoucherData(ctx, h.userdataStore, sessionId, tempData); err != nil { logg.ErrorCtxf(ctx, "failed on UpdateVoucherData", "error", err) return res, err } @@ -1888,9 +1891,9 @@ func (h *MenuHandlers) GetVoucherDetails(ctx context.Context, sym string, input flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error") // get the active address - activeAddress, err := store.ReadEntry(ctx, sessionId, common.DATA_ACTIVE_ADDRESS) + activeAddress, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS) if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeAddress entry with", "key", common.DATA_ACTIVE_ADDRESS, "error", err) + logg.ErrorCtxf(ctx, "failed to read activeAddress entry with", "key", storedb.DATA_ACTIVE_ADDRESS, "error", err) return res, err } @@ -1919,10 +1922,10 @@ func (h *MenuHandlers) CheckTransactions(ctx context.Context, sym string, input flag_no_transfers, _ := h.flagManager.GetFlag("flag_no_transfers") flag_api_error, _ := h.flagManager.GetFlag("flag_api_error") - store := h.userdataStore - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + userStore := h.userdataStore + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } @@ -1940,22 +1943,22 @@ func (h *MenuHandlers) CheckTransactions(ctx context.Context, sym string, input return res, nil } - data := common.ProcessTransfers(transactionsResp) + data := store.ProcessTransfers(transactionsResp) // Store all transaction data - dataMap := map[common.DataTyp]string{ - common.DATA_TX_SENDERS: data.Senders, - common.DATA_TX_RECIPIENTS: data.Recipients, - common.DATA_TX_VALUES: data.TransferValues, - common.DATA_TX_ADDRESSES: data.Addresses, - common.DATA_TX_HASHES: data.TxHashes, - common.DATA_TX_DATES: data.Dates, - common.DATA_TX_SYMBOLS: data.Symbols, - common.DATA_TX_DECIMALS: data.Decimals, + dataMap := map[storedb.DataTyp]string{ + storedb.DATA_TX_SENDERS: data.Senders, + storedb.DATA_TX_RECIPIENTS: data.Recipients, + storedb.DATA_TX_VALUES: data.TransferValues, + storedb.DATA_TX_ADDRESSES: data.Addresses, + storedb.DATA_TX_HASHES: data.TxHashes, + storedb.DATA_TX_DATES: data.Dates, + storedb.DATA_TX_SYMBOLS: data.Symbols, + storedb.DATA_TX_DECIMALS: data.Decimals, } for key, value := range dataMap { - if err := h.prefixDb.Put(ctx, []byte(common.ToBytes(key)), []byte(value)); err != nil { + if err := h.prefixDb.Put(ctx, []byte(storedb.ToBytes(key)), []byte(value)); err != nil { logg.ErrorCtxf(ctx, "failed to write to prefixDb", "error", err) return res, err } @@ -1974,30 +1977,30 @@ func (h *MenuHandlers) GetTransactionsList(ctx context.Context, sym string, inpu return res, fmt.Errorf("missing session") } - store := h.userdataStore - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + userStore := h.userdataStore + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } // Read transactions from the store and format them - TransactionSenders, err := h.prefixDb.Get(ctx, common.ToBytes(common.DATA_TX_SENDERS)) + TransactionSenders, err := h.prefixDb.Get(ctx, storedb.ToBytes(storedb.DATA_TX_SENDERS)) if err != nil { logg.ErrorCtxf(ctx, "Failed to read the TransactionSenders from prefixDb", "error", err) return res, err } - TransactionSyms, err := h.prefixDb.Get(ctx, common.ToBytes(common.DATA_TX_SYMBOLS)) + TransactionSyms, err := h.prefixDb.Get(ctx, storedb.ToBytes(storedb.DATA_TX_SYMBOLS)) if err != nil { logg.ErrorCtxf(ctx, "Failed to read the TransactionSyms from prefixDb", "error", err) return res, err } - TransactionValues, err := h.prefixDb.Get(ctx, common.ToBytes(common.DATA_TX_VALUES)) + TransactionValues, err := h.prefixDb.Get(ctx, storedb.ToBytes(storedb.DATA_TX_VALUES)) if err != nil { logg.ErrorCtxf(ctx, "Failed to read the TransactionValues from prefixDb", "error", err) return res, err } - TransactionDates, err := h.prefixDb.Get(ctx, common.ToBytes(common.DATA_TX_DATES)) + TransactionDates, err := h.prefixDb.Get(ctx, storedb.ToBytes(storedb.DATA_TX_DATES)) if err != nil { logg.ErrorCtxf(ctx, "Failed to read the TransactionDates from prefixDb", "error", err) return res, err @@ -2039,10 +2042,10 @@ func (h *MenuHandlers) ViewTransactionStatement(ctx context.Context, sym string, if !ok { return res, fmt.Errorf("missing session") } - store := h.userdataStore - publicKey, err := store.ReadEntry(ctx, sessionId, common.DATA_PUBLIC_KEY) + userStore := h.userdataStore + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { - logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", common.DATA_PUBLIC_KEY, "error", err) + logg.ErrorCtxf(ctx, "failed to read publicKey entry with", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } @@ -2064,7 +2067,7 @@ func (h *MenuHandlers) ViewTransactionStatement(ctx context.Context, sym string, return res, fmt.Errorf("invalid input: index must be between 1 and 10") } - statement, err := common.GetTransferData(ctx, h.prefixDb, string(publicKey), index) + statement, err := store.GetTransferData(ctx, h.prefixDb, string(publicKey), index) if err != nil { return res, fmt.Errorf("failed to retrieve transfer data: %v", err) } @@ -2083,7 +2086,7 @@ func (h *MenuHandlers) ViewTransactionStatement(ctx context.Context, sym string, // handles bulk updates of profile information. func (h *MenuHandlers) insertProfileItems(ctx context.Context, sessionId string, res *resource.Result) error { var err error - store := h.userdataStore + userStore := h.userdataStore profileFlagNames := []string{ "flag_firstname_set", "flag_familyname_set", @@ -2092,13 +2095,13 @@ func (h *MenuHandlers) insertProfileItems(ctx context.Context, sessionId string, "flag_location_set", "flag_offerings_set", } - profileDataKeys := []common.DataTyp{ - common.DATA_FIRST_NAME, - common.DATA_FAMILY_NAME, - common.DATA_GENDER, - common.DATA_YOB, - common.DATA_LOCATION, - common.DATA_OFFERINGS, + profileDataKeys := []storedb.DataTyp{ + storedb.DATA_FIRST_NAME, + storedb.DATA_FAMILY_NAME, + storedb.DATA_GENDER, + storedb.DATA_YOB, + storedb.DATA_LOCATION, + storedb.DATA_OFFERINGS, } for index, profileItem := range h.profile.ProfileItems { // Ensure the profileItem is not "0"(is set) @@ -2106,7 +2109,7 @@ func (h *MenuHandlers) insertProfileItems(ctx context.Context, sessionId string, flag, _ := h.flagManager.GetFlag(profileFlagNames[index]) isProfileItemSet := h.st.MatchFlag(flag, true) if !isProfileItemSet { - err = store.WriteEntry(ctx, sessionId, profileDataKeys[index], []byte(profileItem)) + err = userStore.WriteEntry(ctx, sessionId, profileDataKeys[index], []byte(profileItem)) if err != nil { logg.ErrorCtxf(ctx, "failed to write profile entry with", "key", profileDataKeys[index], "value", profileItem, "error", err) return err @@ -2137,14 +2140,14 @@ func (h *MenuHandlers) incrementIncorrectPINAttempts(ctx context.Context, sessio var pinAttemptsCount uint8 store := h.userdataStore - currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS) + currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS) if err != nil { if db.IsNotFound(err) { //First time Wrong PIN attempt: initialize with a count of 1 pinAttemptsCount = 1 - err = store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(pinAttemptsCount)))) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(pinAttemptsCount)))) if err != nil { - logg.ErrorCtxf(ctx, "failed to write incorrect PIN attempts ", "key", common.DATA_INCORRECT_PIN_ATTEMPTS, "value", currentWrongPinAttempts, "error", err) + logg.ErrorCtxf(ctx, "failed to write incorrect PIN attempts ", "key", storedb.DATA_INCORRECT_PIN_ATTEMPTS, "value", currentWrongPinAttempts, "error", err) return err } return nil @@ -2153,9 +2156,9 @@ func (h *MenuHandlers) incrementIncorrectPINAttempts(ctx context.Context, sessio pinAttemptsValue, _ := strconv.ParseUint(string(currentWrongPinAttempts), 0, 64) pinAttemptsCount = uint8(pinAttemptsValue) + 1 - err = store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(pinAttemptsCount)))) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(pinAttemptsCount)))) if err != nil { - logg.ErrorCtxf(ctx, "failed to write incorrect PIN attempts ", "key", common.DATA_INCORRECT_PIN_ATTEMPTS, "value", pinAttemptsCount, "error", err) + logg.ErrorCtxf(ctx, "failed to write incorrect PIN attempts ", "key", storedb.DATA_INCORRECT_PIN_ATTEMPTS, "value", pinAttemptsCount, "error", err) return err } return nil @@ -2164,7 +2167,7 @@ func (h *MenuHandlers) incrementIncorrectPINAttempts(ctx context.Context, sessio // resetIncorrectPINAttempts resets the number of incorrect PIN attempts after a correct PIN entry func (h *MenuHandlers) resetIncorrectPINAttempts(ctx context.Context, sessionId string) error { store := h.userdataStore - currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS) + currentWrongPinAttempts, err := store.ReadEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS) if err != nil { if db.IsNotFound(err) { return nil @@ -2172,10 +2175,10 @@ func (h *MenuHandlers) resetIncorrectPINAttempts(ctx context.Context, sessionId return err } currentWrongPinAttemptsCount, _ := strconv.ParseUint(string(currentWrongPinAttempts), 0, 64) - if currentWrongPinAttemptsCount <= uint64(common.AllowedPINAttempts) { - err = store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(string("0"))) + if currentWrongPinAttemptsCount <= uint64(pin.AllowedPINAttempts) { + err = store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(string("0"))) if err != nil { - logg.ErrorCtxf(ctx, "failed to reset incorrect PIN attempts ", "key", common.DATA_INCORRECT_PIN_ATTEMPTS, "value", common.AllowedPINAttempts, "error", err) + logg.ErrorCtxf(ctx, "failed to reset incorrect PIN attempts ", "key", storedb.DATA_INCORRECT_PIN_ATTEMPTS, "value", pin.AllowedPINAttempts, "error", err) return err } } @@ -2189,9 +2192,9 @@ func (h *MenuHandlers) persistLanguageCode(ctx context.Context, code string) err if !ok { return fmt.Errorf("missing session") } - err := store.WriteEntry(ctx, sessionId, common.DATA_SELECTED_LANGUAGE_CODE, []byte(code)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_SELECTED_LANGUAGE_CODE, []byte(code)) if err != nil { - logg.ErrorCtxf(ctx, "failed to persist language code", "key", common.DATA_SELECTED_LANGUAGE_CODE, "value", code, "error", err) + logg.ErrorCtxf(ctx, "failed to persist language code", "key", storedb.DATA_SELECTED_LANGUAGE_CODE, "value", code, "error", err) return err } return nil diff --git a/handlers/application/menuhandler_test.go b/handlers/application/menuhandler_test.go index bf8c718..eda04d6 100644 --- a/handlers/application/menuhandler_test.go +++ b/handlers/application/menuhandler_test.go @@ -14,13 +14,13 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - dbstorage "git.grassecon.net/grassrootseconomics/visedriver/storage/db" "git.grassecon.net/grassrootseconomics/sarafu-api/models" "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/testservice" "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/mocks" "git.grassecon.net/grassrootseconomics/sarafu-vise/store" + "git.grassecon.net/grassrootseconomics/common/pin" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" - "git.grassecon.net/grassrootseconomics/visedriver/common" "github.com/alecthomas/assert/v2" testdataloader "github.com/peteole/testdata-loader" @@ -42,7 +42,7 @@ var mockReplaceSeparator = func(input string) string { } // InitializeTestStore sets up and returns an in-memory database and store. -func InitializeTestStore(t *testing.T) (context.Context, *common.UserDataStore) { +func InitializeTestStore(t *testing.T) (context.Context, *store.UserDataStore) { ctx := context.Background() // Initialize memDb @@ -51,7 +51,7 @@ func InitializeTestStore(t *testing.T) (context.Context, *common.UserDataStore) require.NoError(t, err, "Failed to connect to memDb") // Create UserDataStore with memDb - store := &common.UserDataStore{Db: db} + store := &store.UserDataStore{Db: db} t.Cleanup(func() { db.Close() // Ensure the DB is closed after each test @@ -60,14 +60,14 @@ func InitializeTestStore(t *testing.T) (context.Context, *common.UserDataStore) return ctx, store } -func InitializeTestSubPrefixDb(t *testing.T, ctx context.Context) *dbstorage.SubPrefixDb { +func InitializeTestSubPrefixDb(t *testing.T, ctx context.Context) *storedb.SubPrefixDb { db := memdb.NewMemDb() err := db.Connect(ctx, "") if err != nil { t.Fatal(err) } - prefix := common.ToBytes(visedb.DATATYPE_USERDATA) - spdb := dbstorage.NewSubPrefixDb(db, prefix) + prefix := storedb.ToBytes(visedb.DATATYPE_USERDATA) + spdb := storedb.NewSubPrefixDb(db, prefix) return spdb } @@ -311,7 +311,7 @@ func TestSaveFirstname(t *testing.T) { // Define test data firstName := "John" - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(firstName)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(firstName)); err != nil { t.Fatal(err) } @@ -332,7 +332,7 @@ func TestSaveFirstname(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_FIRST_NAME entry has been updated with the temporary value - storedFirstName, _ := store.ReadEntry(ctx, sessionId, common.DATA_FIRST_NAME) + storedFirstName, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_FIRST_NAME) assert.Equal(t, firstName, string(storedFirstName)) } @@ -357,7 +357,7 @@ func TestSaveFamilyname(t *testing.T) { // Define test data familyName := "Doeee" - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(familyName)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(familyName)); err != nil { t.Fatal(err) } @@ -376,7 +376,7 @@ func TestSaveFamilyname(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_FAMILY_NAME entry has been updated with the temporary value - storedFamilyName, _ := store.ReadEntry(ctx, sessionId, common.DATA_FAMILY_NAME) + storedFamilyName, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_FAMILY_NAME) assert.Equal(t, familyName, string(storedFamilyName)) } @@ -399,7 +399,7 @@ func TestSaveYoB(t *testing.T) { // Define test data yob := "1980" - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(yob)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(yob)); err != nil { t.Fatal(err) } @@ -420,7 +420,7 @@ func TestSaveYoB(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_YOB entry has been updated with the temporary value - storedYob, _ := store.ReadEntry(ctx, sessionId, common.DATA_YOB) + storedYob, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_YOB) assert.Equal(t, yob, string(storedYob)) } @@ -443,7 +443,7 @@ func TestSaveLocation(t *testing.T) { // Define test data location := "Kilifi" - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(location)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(location)); err != nil { t.Fatal(err) } @@ -464,7 +464,7 @@ func TestSaveLocation(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_LOCATION entry has been updated with the temporary value - storedLocation, _ := store.ReadEntry(ctx, sessionId, common.DATA_LOCATION) + storedLocation, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_LOCATION) assert.Equal(t, location, string(storedLocation)) } @@ -487,7 +487,7 @@ func TestSaveOfferings(t *testing.T) { // Define test data offerings := "Bananas" - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(offerings)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(offerings)); err != nil { t.Fatal(err) } @@ -508,7 +508,7 @@ func TestSaveOfferings(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_OFFERINGS entry has been updated with the temporary value - storedOfferings, _ := store.ReadEntry(ctx, sessionId, common.DATA_OFFERINGS) + storedOfferings, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_OFFERINGS) assert.Equal(t, offerings, string(storedOfferings)) } @@ -555,7 +555,7 @@ func TestSaveGender(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(tt.expectedGender)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(tt.expectedGender)); err != nil { t.Fatal(err) } @@ -579,7 +579,7 @@ func TestSaveGender(t *testing.T) { assert.Equal(t, expectedResult, res) // Verify that the DATA_GENDER entry has been updated with the temporary value - storedGender, _ := store.ReadEntry(ctx, sessionId, common.DATA_GENDER) + storedGender, _ := store.ReadEntry(ctx, sessionId, storedb.DATA_GENDER) assert.Equal(t, tt.expectedGender, string(storedGender)) }) } @@ -663,7 +663,7 @@ func TestCheckIdentifier(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := store.WriteEntry(ctx, sessionId, common.DATA_PUBLIC_KEY, []byte(tt.publicKey)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(tt.publicKey)) if err != nil { t.Fatal(err) } @@ -707,12 +707,12 @@ func TestGetAmount(t *testing.T) { amount := "0.03" activeSym := "SRF" - err := store.WriteEntry(ctx, sessionId, common.DATA_AMOUNT, []byte(amount)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(amount)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_SYM, []byte(activeSym)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM, []byte(activeSym)) if err != nil { t.Fatal(err) } @@ -738,7 +738,7 @@ func TestGetRecipient(t *testing.T) { recepient := "0712345678" - err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(recepient)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(recepient)) if err != nil { t.Fatal(err) } @@ -975,7 +975,7 @@ func TestIncorrectPinReset(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(tt.attempts)))); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(tt.attempts)))); err != nil { t.Fatal(err) } @@ -1097,13 +1097,13 @@ func TestAuthorize(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Hash the PIN - hashedPIN, err := common.HashPIN(accountPIN) + hashedPIN, err := pin.HashPIN(accountPIN) if err != nil { logg.ErrorCtxf(ctx, "failed to hash temporaryPin", "error", err) t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACCOUNT_PIN, []byte(hashedPIN)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACCOUNT_PIN, []byte(hashedPIN)) if err != nil { t.Fatal(err) } @@ -1230,7 +1230,7 @@ func TestVerifyCreatePin(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err = store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte("1234")) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte("1234")) if err != nil { t.Fatal(err) } @@ -1299,7 +1299,7 @@ func TestCheckAccountStatus(t *testing.T) { flagManager: fm.parser, } - err = store.WriteEntry(ctx, sessionId, common.DATA_PUBLIC_KEY, []byte(tt.publicKey)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(tt.publicKey)) if err != nil { t.Fatal(err) } @@ -1465,31 +1465,31 @@ func TestInitiateTransaction(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(tt.TemporaryValue)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(tt.TemporaryValue)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_SYM, []byte(tt.ActiveSym)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SYM, []byte(tt.ActiveSym)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_AMOUNT, []byte(tt.StoredAmount)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(tt.StoredAmount)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_PUBLIC_KEY, []byte(tt.PublicKey)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(tt.PublicKey)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_RECIPIENT, []byte(tt.Recipient)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT, []byte(tt.Recipient)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_DECIMAL, []byte(tt.ActiveDecimal)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_DECIMAL, []byte(tt.ActiveDecimal)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_ADDRESS, []byte(tt.ActiveAddress)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS, []byte(tt.ActiveAddress)) if err != nil { t.Fatal(err) } @@ -1612,7 +1612,7 @@ func TestValidateAmount(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_BAL, []byte(tt.activeBal)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL, []byte(tt.activeBal)) if err != nil { t.Fatal(err) } @@ -1683,7 +1683,7 @@ func TestValidateRecipient(t *testing.T) { } // store a public key for the valid recipient - err = store.WriteEntry(ctx, "+254711223344", common.DATA_PUBLIC_KEY, []byte(publicKey)) + err = store.WriteEntry(ctx, "+254711223344", storedb.DATA_PUBLIC_KEY, []byte(publicKey)) if err != nil { t.Fatal(err) } @@ -1750,11 +1750,11 @@ func TestCheckBalance(t *testing.T) { accountService: mockAccountService, } - err := store.WriteEntry(ctx, tt.sessionId, common.DATA_ACTIVE_SYM, []byte(tt.activeSym)) + err := store.WriteEntry(ctx, tt.sessionId, storedb.DATA_ACTIVE_SYM, []byte(tt.activeSym)) if err != nil { t.Fatal(err) } - err = store.WriteEntry(ctx, tt.sessionId, common.DATA_ACTIVE_BAL, []byte(tt.activeBal)) + err = store.WriteEntry(ctx, tt.sessionId, storedb.DATA_ACTIVE_BAL, []byte(tt.activeBal)) if err != nil { t.Fatal(err) } @@ -1789,13 +1789,13 @@ func TestGetProfile(t *testing.T) { tests := []struct { name string languageCode string - keys []common.DataTyp + keys []storedb.DataTyp profileInfo []string result resource.Result }{ { name: "Test with full profile information in eng", - keys: []common.DataTyp{common.DATA_FAMILY_NAME, common.DATA_FIRST_NAME, common.DATA_GENDER, common.DATA_OFFERINGS, common.DATA_LOCATION, common.DATA_YOB}, + keys: []storedb.DataTyp{storedb.DATA_FAMILY_NAME, storedb.DATA_FIRST_NAME, storedb.DATA_GENDER, storedb.DATA_OFFERINGS, storedb.DATA_LOCATION, storedb.DATA_YOB}, profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"}, languageCode: "eng", result: resource.Result{ @@ -1807,7 +1807,7 @@ func TestGetProfile(t *testing.T) { }, { name: "Test with with profile information in swa", - keys: []common.DataTyp{common.DATA_FAMILY_NAME, common.DATA_FIRST_NAME, common.DATA_GENDER, common.DATA_OFFERINGS, common.DATA_LOCATION, common.DATA_YOB}, + keys: []storedb.DataTyp{storedb.DATA_FAMILY_NAME, storedb.DATA_FIRST_NAME, storedb.DATA_GENDER, storedb.DATA_OFFERINGS, storedb.DATA_LOCATION, storedb.DATA_YOB}, profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"}, languageCode: "swa", result: resource.Result{ @@ -1819,7 +1819,7 @@ func TestGetProfile(t *testing.T) { }, { name: "Test with with profile information with language that is not yet supported", - keys: []common.DataTyp{common.DATA_FAMILY_NAME, common.DATA_FIRST_NAME, common.DATA_GENDER, common.DATA_OFFERINGS, common.DATA_LOCATION, common.DATA_YOB}, + keys: []storedb.DataTyp{storedb.DATA_FAMILY_NAME, storedb.DATA_FIRST_NAME, storedb.DATA_GENDER, storedb.DATA_OFFERINGS, storedb.DATA_LOCATION, storedb.DATA_YOB}, profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"}, languageCode: "nor", result: resource.Result{ @@ -1928,7 +1928,7 @@ func TestConfirmPin(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Set up the expected behavior of the mock - err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(tt.temporarypin)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(tt.temporarypin)) if err != nil { t.Fatal(err) } @@ -2039,7 +2039,7 @@ func TestSetDefaultVoucher(t *testing.T) { flagManager: fm.parser, } - err := store.WriteEntry(ctx, sessionId, common.DATA_PUBLIC_KEY, []byte(publicKey)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(publicKey)) if err != nil { t.Fatal(err) } @@ -2072,7 +2072,7 @@ func TestCheckVouchers(t *testing.T) { prefixDb: spdb, } - err := store.WriteEntry(ctx, sessionId, common.DATA_PUBLIC_KEY, []byte(publicKey)) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(publicKey)) if err != nil { t.Fatal(err) } @@ -2090,7 +2090,7 @@ func TestCheckVouchers(t *testing.T) { assert.NoError(t, err) // Read voucher sym data from the store - voucherData, err := spdb.Get(ctx, common.ToBytes(common.DATA_VOUCHER_SYMBOLS)) + voucherData, err := spdb.Get(ctx, storedb.ToBytes(storedb.DATA_VOUCHER_SYMBOLS)) if err != nil { t.Fatal(err) } @@ -2117,7 +2117,7 @@ func TestGetVoucherList(t *testing.T) { mockSyms := []byte("1:SRF\n2:MILO") // Put voucher sym data from the store - err := spdb.Put(ctx, common.ToBytes(common.DATA_VOUCHER_SYMBOLS), mockSyms) + err := spdb.Put(ctx, storedb.ToBytes(storedb.DATA_VOUCHER_SYMBOLS), mockSyms) if err != nil { t.Fatal(err) } @@ -2149,16 +2149,16 @@ func TestViewVoucher(t *testing.T) { } // Define mock voucher data - mockData := map[common.DataTyp][]byte{ - common.DATA_VOUCHER_SYMBOLS: []byte("1:SRF\n2:MILO"), - common.DATA_VOUCHER_BALANCES: []byte("1:100\n2:200"), - common.DATA_VOUCHER_DECIMALS: []byte("1:6\n2:4"), - common.DATA_VOUCHER_ADDRESSES: []byte("1:0xd4c288865Ce\n2:0x41c188d63Qa"), + mockData := map[storedb.DataTyp][]byte{ + storedb.DATA_VOUCHER_SYMBOLS: []byte("1:SRF\n2:MILO"), + storedb.DATA_VOUCHER_BALANCES: []byte("1:100\n2:200"), + storedb.DATA_VOUCHER_DECIMALS: []byte("1:6\n2:4"), + storedb.DATA_VOUCHER_ADDRESSES: []byte("1:0xd4c288865Ce\n2:0x41c188d63Qa"), } // Put the data for key, value := range mockData { - err = spdb.Put(ctx, []byte(common.ToBytes(key)), []byte(value)) + err = spdb.Put(ctx, []byte(storedb.ToBytes(key)), []byte(value)) if err != nil { t.Fatal(err) } @@ -2190,7 +2190,7 @@ func TestSetVoucher(t *testing.T) { expectedData := fmt.Sprintf("%s,%s,%s,%s", tempData.TokenSymbol, tempData.Balance, tempData.TokenDecimals, tempData.ContractAddress) // store the expectedData - if err := store.WriteEntry(ctx, sessionId, common.DATA_TEMPORARY_VALUE, []byte(expectedData)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(expectedData)); err != nil { t.Fatal(err) } @@ -2220,7 +2220,7 @@ func TestGetVoucherDetails(t *testing.T) { flagManager: fm.parser, accountService: mockAccountService, } - err = store.WriteEntry(ctx, sessionId, common.DATA_ACTIVE_ADDRESS, []byte(tokA_AAddress)) + err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS, []byte(tokA_AAddress)) if err != nil { t.Fatal(err) } @@ -2249,7 +2249,7 @@ func TestCountIncorrectPINAttempts(t *testing.T) { h := &MenuHandlers{ userdataStore: store, } - err := store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(attempts)))) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(strconv.Itoa(int(attempts)))) if err != nil { t.Logf(err.Error()) } @@ -2258,7 +2258,7 @@ func TestCountIncorrectPINAttempts(t *testing.T) { t.Logf(err.Error()) } - attemptsAfterCount, err := store.ReadEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS) + attemptsAfterCount, err := store.ReadEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS) if err != nil { t.Logf(err.Error()) } @@ -2274,7 +2274,7 @@ func TestResetIncorrectPINAttempts(t *testing.T) { sessionId := "session123" ctx = context.WithValue(ctx, "SessionId", sessionId) - err := store.WriteEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS, []byte(string("2"))) + err := store.WriteEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS, []byte(string("2"))) if err != nil { t.Logf(err.Error()) } @@ -2283,7 +2283,7 @@ func TestResetIncorrectPINAttempts(t *testing.T) { userdataStore: store, } h.resetIncorrectPINAttempts(ctx, sessionId) - incorrectAttempts, err := store.ReadEntry(ctx, sessionId, common.DATA_INCORRECT_PIN_ATTEMPTS) + incorrectAttempts, err := store.ReadEntry(ctx, sessionId, storedb.DATA_INCORRECT_PIN_ATTEMPTS) if err != nil { t.Logf(err.Error()) @@ -2323,7 +2323,7 @@ func TestPersistLanguageCode(t *testing.T) { if err != nil { t.Logf(err.Error()) } - code, err := store.ReadEntry(ctx, sessionId, common.DATA_SELECTED_LANGUAGE_CODE) + code, err := store.ReadEntry(ctx, sessionId, storedb.DATA_SELECTED_LANGUAGE_CODE) assert.Equal(t, test.expectedLanguageCode, string(code)) } diff --git a/store/user_store.go b/store/user_store.go new file mode 100644 index 0000000..8b358e4 --- /dev/null +++ b/store/user_store.go @@ -0,0 +1,37 @@ +package store + +import ( + "context" + + visedb "git.defalsify.org/vise.git/db" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" + "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" +) + +// TODO: Rename interface, "datastore" is redundant naming and too general +type DataStore interface { + visedb.Db + ReadEntry(ctx context.Context, sessionId string, typ db.DataTyp) ([]byte, error) + WriteEntry(ctx context.Context, sessionId string, typ db.DataTyp, value []byte) error +} + +type UserDataStore struct { + visedb.Db +} + +// ReadEntry retrieves an entry to the userdata store. +func (store *UserDataStore) ReadEntry(ctx context.Context, sessionId string, typ db.DataTyp) ([]byte, error) { + store.SetPrefix(visedb.DATATYPE_USERDATA) + store.SetSession(sessionId) + k := storedb.ToBytes(typ) + return store.Get(ctx, k) +} + +// WriteEntry adds an entry to the userdata store. +// BUG: this uses sessionId twice +func (store *UserDataStore) WriteEntry(ctx context.Context, sessionId string, typ db.DataTyp, value []byte) error { + store.SetPrefix(visedb.DATATYPE_USERDATA) + store.SetSession(sessionId) + k := storedb.ToBytes(typ) + return store.Put(ctx, k, value) +}