wip-code-check #46

Closed
carlos wants to merge 18 commits from wip-code-check into master
18 changed files with 1841 additions and 46 deletions

View File

@ -71,6 +71,7 @@ func getHandler(appFlags *asm.FlagParser, rs *resource.DbResource, pe *persist.P
rs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob)
rs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit)
rs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction)
rs.AddLocalFunc("quit_with_help", ussdHandlers.QuitWithHelp)
return ussdHandlers, nil
}

3
go.mod
View File

@ -5,9 +5,12 @@ go 1.22.6
require (
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240911162138-1f2af8672dc7
github.com/alecthomas/assert/v2 v2.2.2
github.com/peteole/testdata-loader v0.3.0
gopkg.in/leonelquinteros/gotext.v1 v1.3.1
)
require gopkg.in/dnaeon/go-vcr.v4 v4.0.1 // indirect
require (
github.com/alecthomas/participle/v2 v2.0.0 // indirect
github.com/alecthomas/repr v0.2.0 // indirect

2
go.sum
View File

@ -30,6 +30,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/dnaeon/go-vcr.v4 v4.0.1 h1:dIFuOqqDZIJ9BTcK+DXmElzypQ6PV9fBQZSIwY+J1yM=
gopkg.in/dnaeon/go-vcr.v4 v4.0.1/go.mod h1:65yxh9goQVrudqofKtHA4JNFWd6XZRkWfKN4YpMx7KI=
gopkg.in/leonelquinteros/gotext.v1 v1.3.1 h1:8d9/fdTG0kn/B7NNGV1BsEyvektXFAbkMsTZS2sFSCc=
gopkg.in/leonelquinteros/gotext.v1 v1.3.1/go.mod h1:X1WlGDeAFIYsW6GjgMm4VwUwZ2XjI7Zan2InxSUQWrU=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@ -0,0 +1,129 @@
//go:build !online
// +build !online
package server
import (
"testing"
"github.com/alecthomas/assert/v2"
"gopkg.in/dnaeon/go-vcr.v4/pkg/recorder"
)
func TestCheckBalanceOffline(t *testing.T) {
r, err := recorder.New("custodial/balance")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
tests := []struct {
name string
balance string
publicKey string
}{
{
name: "Test check balance with correct public key",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002",
balance: "3.06000000003 CELO",
},
{
name: "Test check balance with public key that doesn't exist in the custodial system",
balance: "",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
balance, err := as.CheckBalance(tt.publicKey)
if err != nil {
t.Fatalf("Failed to get balance with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal")
})
}
}
func TestCheckAccountStatusOffline(t *testing.T) {
r, err := recorder.New("custodial/status")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
tests := []struct {
name string
status string
trackingId string
}{
{
name: "Test check status with tracking id that exists in the custodial system",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18",
status: "SUCCESS",
},
{
name: "Test check status with tracking id that doesn't exist in the custodial system",
status: "",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status, err := as.CheckAccountStatus(tt.trackingId)
if err != nil {
t.Fatalf("Failed to account status with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, status, tt.status, "Expected status and actual status should be equal")
})
}
}
func TestCreateAccountOffline(t *testing.T) {
r, err := recorder.New("custodial/create")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
accountRes, err := as.CreateAccount()
if err != nil {
t.Fatalf("Failed to create an account with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, accountRes.Ok, true, "account response status is true")
}

View File

@ -0,0 +1,130 @@
//go:build online
// +build online
package server
import (
"net/http"
"testing"
"github.com/alecthomas/assert/v2"
"gopkg.in/dnaeon/go-vcr.v4/pkg/recorder"
)
func TestCheckBalance(t *testing.T) {
r, err := recorder.New("custodial/balance")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := &http.Client{}
as := AccountService{
Client: client,
}
tests := []struct {
name string
balance string
publicKey string
}{
{
name: "Test check balance with correct public key",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002",
balance: "3.06000000003 CELO",
},
{
name: "Test check balance with public key that doesn't exist in the custodial system",
balance: "",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
balance, err := as.CheckBalance(tt.publicKey)
if err != nil {
t.Fatalf("Failed to get balance with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal")
})
}
}
func TestCheckAccountStatus(t *testing.T) {
r, err := recorder.New("custodial/status")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := &http.Client{}
as := AccountService{
Client: client,
}
tests := []struct {
name string
status string
trackingId string
}{
{
name: "Test check status with tracking id that exists in the custodial system",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18",
status: "SUCCESS",
},
{
name: "Test check status with tracking id that doesn't exist in the custodial system",
status: "",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status, err := as.CheckAccountStatus(tt.trackingId)
if err != nil {
t.Fatalf("Failed to account status with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, status, tt.status, "Expected status and actual status should be equal")
})
}
}
func TestCreateAccount(t *testing.T) {
r, err := recorder.New("custodial/create")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := &http.Client{}
as := AccountService{
Client: client,
}
accountRes, err := as.CreateAccount()
if err != nil {
t.Fatalf("Failed to create an account with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, accountRes.Ok, true, "account response status is true")
}

View File

@ -16,6 +16,7 @@ type AccountServiceInterface interface {
}
type AccountService struct {
Client *http.Client
}
@ -34,7 +35,8 @@ type AccountService struct {
// If no error occurs, this will be nil.
//
func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) {
resp, err := http.Get(config.TrackStatusURL + trackingId)
resp,err := as.Client.Get(config.TrackStatusURL + trackingId)
// resp, err := http.Get(config.TrackStatusURL + trackingId)
if err != nil {
return "", err
}
@ -62,7 +64,8 @@ func (as *AccountService) CheckAccountStatus(trackingId string) (string, error)
// - publicKey: The public key associated with the account whose balance needs to be checked.
func (as *AccountService) CheckBalance(publicKey string) (string, error) {
resp, err := http.Get(config.BalanceURL + publicKey)
//resp, err := http.Get(config.BalanceURL + publicKey)
resp, err := as.Client.Get(config.BalanceURL + publicKey)
if err != nil {
return "0.0", err
}
@ -91,7 +94,8 @@ func (as *AccountService) CheckBalance(publicKey string) (string, error) {
// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data.
// If no error occurs, this will be nil.
func (as *AccountService) CreateAccount() (*models.AccountResponse, error) {
resp, err := http.Post(config.CreateAccountURL, "application/json", nil)
//resp, err := http.Post(config.CreateAccountURL, "application/json", nil)
resp, err := as.Client.Post(config.CreateAccountURL, "application/json", nil)
if err != nil {
return nil, err
}

View File

@ -0,0 +1,126 @@
package server
import (
"testing"
"github.com/alecthomas/assert/v2"
"gopkg.in/dnaeon/go-vcr.v4/pkg/recorder"
)
func TestCheckBalance(t *testing.T) {
r, err := recorder.New("custodial/balance")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
tests := []struct {
name string
balance string
publicKey string
}{
{
name: "Test check balance with correct public key",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002",
balance: "3.06000000003 CELO",
},
{
name: "Test check balance with public key that doesn't exist in the custodial system",
balance: "",
publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
balance, err := as.CheckBalance(tt.publicKey)
if err != nil {
t.Fatalf("Failed to get balance with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal")
})
}
}
func TestCheckAccountStatus(t *testing.T) {
r, err := recorder.New("custodial/status")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
tests := []struct {
name string
status string
trackingId string
}{
{
name: "Test check status with tracking id that exists in the custodial system",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18",
status: "SUCCESS",
},
{
name: "Test check status with tracking id that doesn't exist in the custodial system",
status: "",
trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status, err := as.CheckAccountStatus(tt.trackingId)
if err != nil {
t.Fatalf("Failed to account status with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, status, tt.status, "Expected status and actual status should be equal")
})
}
}
func TestCreateAccount(t *testing.T) {
r, err := recorder.New("custodial/create")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
client := r.GetDefaultClient()
as := AccountService{
Client: client,
}
accountRes, err := as.CreateAccount()
if err != nil {
t.Fatalf("Failed to create an account with error %s", err)
}
if err != nil {
return
}
assert.NoError(t, err)
assert.Equal(t, accountRes.Ok, true, "account response status is true")
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"net/http"
"path"
"regexp"
"strconv"
@ -73,10 +74,13 @@ func NewHandlers(appFlags *asm.FlagParser, userdataStore db.Db) (*Handlers, erro
userDb := &utils.UserDataStore{
Db: userdataStore,
}
client := &http.Client{}
h := &Handlers{
userdataStore: userDb,
flagManager: appFlags,
accountService: &server.AccountService{},
userdataStore: userDb,
flagManager: appFlags,
accountService: &server.AccountService{
Client: client,
},
}
return h, nil
}
@ -481,22 +485,19 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res
if err != nil {
return res, err
}
if err == nil {
if len(input) == 4 {
if bytes.Equal(input, AccountPin) {
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)
} else {
res.FlagSet = append(res.FlagSet, flag_allow_update)
res.FlagReset = append(res.FlagReset, flag_account_authorized)
}
if len(input) == 4 {
if bytes.Equal(input, AccountPin) {
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)
} else {
res.FlagSet = append(res.FlagSet, flag_incorrect_pin)
res.FlagSet = append(res.FlagSet, flag_allow_update)
res.FlagReset = append(res.FlagReset, flag_account_authorized)
return res, nil
}
} else {
res.FlagSet = append(res.FlagSet, flag_incorrect_pin)
res.FlagReset = append(res.FlagReset, flag_account_authorized)
return res, nil
}
} else {
return res, nil
@ -543,7 +544,6 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b
if err != nil {
return res, nil
}
if status == "SUCCESS" {
res.FlagSet = append(res.FlagSet, flag_account_success)
res.FlagReset = append(res.FlagReset, flag_account_pending)
@ -748,7 +748,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount")
publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY)
store := h.userdataStore
publicKey, _ := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY)
amountStr := string(input)
@ -757,6 +758,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
if err != nil {
return res, err
}
res.Content = balanceStr
// Parse the balance
@ -764,6 +766,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
if len(balanceParts) != 2 {
return res, fmt.Errorf("unexpected balance format: %s", balanceStr)
}
balanceValue, err := strconv.ParseFloat(balanceParts[0], 64)
if err != nil {
return res, fmt.Errorf("failed to parse balance: %v", err)
@ -773,6 +776,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`)
matches := re.FindStringSubmatch(strings.TrimSpace(amountStr))
if len(matches) < 2 {
res.FlagSet = append(res.FlagSet, flag_invalid_amount)
res.Content = amountStr
return res, nil
@ -780,6 +784,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
inputAmount, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
res.FlagSet = append(res.FlagSet, flag_invalid_amount)
res.Content = amountStr
return res, nil
@ -792,7 +797,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
}
res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places
store := h.userdataStore
store = h.userdataStore
err = store.WriteEntry(ctx, sessionId, utils.DATA_AMOUNT, []byte(amountStr))
if err != nil {
return res, err

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,7 @@
package utils
import (
"context"
"encoding/binary"
"git.defalsify.org/vise.git/db"
)
type DataTyp uint16
@ -37,21 +34,3 @@ func PackKey(typ DataTyp, data []byte) []byte {
v := typToBytes(typ)
return append(v, data...)
}
func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) ([]byte, error) {
store.SetPrefix(db.DATATYPE_USERDATA)
store.SetSession(sessionId)
k := PackKey(typ, []byte(sessionId))
b, err := store.Get(ctx, k)
if err != nil {
return nil, err
}
return b, nil
}
func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error {
store.SetPrefix(db.DATATYPE_USERDATA)
store.SetSession(sessionId)
k := PackKey(typ, []byte(sessionId))
return store.Put(ctx, k, value)
}

View File

@ -0,0 +1,2 @@
LOAD quit_with_help 0
HALT

View File

@ -10,6 +10,6 @@ HALT
INCMP send 1
INCMP quit 2
INCMP my_account 3
INCMP quit 4
INCMP help 4
INCMP quit 9
INCMP . *

View File

@ -0,0 +1 @@
Enter a new four number pin

View File

@ -0,0 +1,3 @@
MOUT back 0
HALT
INCMP _ 0

View File

@ -0,0 +1 @@
Enter your old PIN

View File

@ -0,0 +1,9 @@
LOAD authorize_account 6
MOUT back 0
HALT
RELOAD authorize_account
CATCH incorrect_pin flag_incorrect_pin 1
MOVE new_pin
INCMP _ 0

View File

@ -4,3 +4,4 @@ MOUT guard_pin 3
MOUT back 0
HALT
INCMP _ 0
INCMP old_pin 1

View File

@ -1,3 +1,4 @@
LOAD authorize_account 6
MAP validate_amount
RELOAD get_recipient
MAP get_recipient
@ -6,9 +7,9 @@ MAP get_sender
MOUT back 0
MOUT quit 9
HALT
LOAD authorize_account 6
RELOAD authorize_account
CATCH incorrect_pin flag_incorrect_pin 1
CATCH transaction_initiated flag_account_authorized 1
INCMP _ 0
INCMP quit 9
INCMP transaction_initiated *