[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[taler-cashless2ecash] branch master updated (889a4e9 -> 470230f)
From: |
gnunet |
Subject: |
[taler-cashless2ecash] branch master updated (889a4e9 -> 470230f) |
Date: |
Tue, 09 Apr 2024 22:43:42 +0200 |
This is an automated email from the git hooks/post-receive script.
joel-haeberli pushed a change to branch master
in repository cashless2ecash.
from 889a4e9 code: add logging, cli and simulation
new abd2a39 ignore: log file
new 52ba853 fix: serialization and logging
new 470230f fix: long-poll
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.gitignore | 1 +
c2ec/auth.go | 8 +-
c2ec/bank-integration.go | 13 ++--
c2ec/c2ec-config.yaml | 2 +-
c2ec/db.go | 2 +-
c2ec/db/0000-c2ec_schema.sql | 2 +-
c2ec/http-util.go | 8 +-
c2ec/logger.go | 25 ++++---
c2ec/main.go | 4 +-
c2ec/model.go | 6 +-
c2ec/postgres.go | 133 +++++++++++++++++++++------------
c2ec/wallee-attestor.go | 2 +-
c2ec/wallee-client.go | 4 +-
c2ec/c2ec-log.txt => simulation/README | 0
simulation/c2ec-simulation | Bin 7559872 -> 7572674 bytes
simulation/http-util.go | 2 +-
simulation/sim-terminal.go | 49 ++++++++++--
simulation/sim-wallet.go | 27 ++++---
18 files changed, 186 insertions(+), 102 deletions(-)
rename c2ec/c2ec-log.txt => simulation/README (100%)
diff --git a/.gitignore b/.gitignore
index ae6275b..127f465 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ infra/
bruno/
c2ec/c2ec
c2ec/.vscode
+c2ec/c2ec-log.txt
cli/c2ec-cli
LocalMakefile
diff --git a/c2ec/auth.go b/c2ec/auth.go
index 867ff25..b008f31 100644
--- a/c2ec/auth.go
+++ b/c2ec/auth.go
@@ -57,7 +57,7 @@ func AuthenticateTerminal(req *http.Request) bool {
if err != nil {
return false
}
- LogInfo(fmt.Sprintf("req=%s by terminal with id=%d,
provider=%s", req.RequestURI, terminalId, provider))
+ LogInfo("auth", fmt.Sprintf("req=%s by terminal with id=%d,
provider=%s", req.RequestURI, terminalId, provider))
terminal, err := DB.GetTerminalById(terminalId)
if err != nil {
@@ -65,18 +65,18 @@ func AuthenticateTerminal(req *http.Request) bool {
}
if !terminal.Active {
- LogWarn(fmt.Sprintf("request from inactive terminal.
id=%d", terminalId))
+ LogWarn("auth", fmt.Sprintf("request from inactive
terminal. id=%d", terminalId))
return false
}
prvdr, err := DB.GetTerminalProviderByName(provider)
if err != nil {
- LogWarn(fmt.Sprintf("failed requesting provider by name
%s", err.Error()))
+ LogWarn("auth", fmt.Sprintf("failed requesting provider
by name %s", err.Error()))
return false
}
if terminal.ProviderId != prvdr.ProviderId {
- LogWarn("terminal's provider id did not match provider
id of supplied provider")
+ LogWarn("auth", "terminal's provider id did not match
provider id of supplied provider")
return false
}
diff --git a/c2ec/bank-integration.go b/c2ec/bank-integration.go
index c67622a..ecae2d5 100644
--- a/c2ec/bank-integration.go
+++ b/c2ec/bank-integration.go
@@ -69,7 +69,7 @@ func bankIntegrationConfig(res http.ResponseWriter, req
*http.Request) {
serializedCfg, err :=
NewJsonCodec[BankIntegrationConfig]().EncodeToBytes(&cfg)
if err != nil {
- LogInfo(fmt.Sprintf("failed serializing config: %s",
err.Error()))
+ LogInfo("bank-integration-api", fmt.Sprintf("failed serializing
config: %s", err.Error()))
res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
return
}
@@ -83,7 +83,7 @@ func handleWithdrawalRegistration(res http.ResponseWriter,
req *http.Request) {
jsonCodec := NewJsonCodec[C2ECWithdrawRegistration]()
registration, err := ReadStructFromBody(req, jsonCodec)
if err != nil {
-
+ LogWarn("bank-integration-api", fmt.Sprintf("invalid body for
withdrawal registration error=%s", err.Error()))
err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
TypeUri: TALER_URI_PROBLEM_PREFIX +
"/C2EC_WITHDRAW_REGISTRATION_INVALID_REQ",
Title: "invalid request",
@@ -99,7 +99,7 @@ func handleWithdrawalRegistration(res http.ResponseWriter,
req *http.Request) {
// read and validate the wopid path parameter
wopid := req.PathValue(WOPID_PARAMETER)
if !WopidValid(wopid) {
- LogWarn("wopid " + wopid + " not valid")
+ LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
if wopid == "" {
err := WriteProblem(res, HTTP_BAD_REQUEST,
&RFC9457Problem{
TypeUri: TALER_URI_PROBLEM_PREFIX +
"/C2EC_INVALID_PATH_PARAMETER",
@@ -167,7 +167,7 @@ func handleWithdrawalStatus(res http.ResponseWriter, req
*http.Request) {
// read and validate the wopid path parameter
wopid := req.PathValue(WOPID_PARAMETER)
if !WopidValid(wopid) {
- LogWarn("wopid " + wopid + " not valid")
+ LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
if wopid == "" {
err := WriteProblem(res, HTTP_BAD_REQUEST,
&RFC9457Problem{
TypeUri: TALER_URI_PROBLEM_PREFIX +
"/C2EC_INVALID_PATH_PARAMETER",
@@ -193,9 +193,7 @@ func handleWithdrawalStatus(res http.ResponseWriter, req
*http.Request) {
statusChannel := make(chan WithdrawalOperationStatus)
errChan := make(chan error)
- // listen for status change in goroutine
go DB.ListenForWithdrawalStatusChange(timeoutCtx,
WithdrawalIdentifier(wopid), statusChannel, errChan)
-
for {
select {
case <-timeoutCtx.Done():
@@ -222,6 +220,7 @@ func handleWithdrawalStatus(res http.ResponseWriter, req
*http.Request) {
return
case <-statusChannel:
getWithdrawalOrWriteError(wopid, res,
req.RequestURI)
+ return
}
}
}
@@ -233,7 +232,7 @@ func handlePaymentNotification(res http.ResponseWriter, req
*http.Request) {
wopid := req.PathValue(WOPID_PARAMETER)
if !WopidValid(wopid) {
- LogWarn("wopid " + wopid + " not valid")
+ LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
if wopid == "" {
err := WriteProblem(res, HTTP_BAD_REQUEST,
&RFC9457Problem{
TypeUri: TALER_URI_PROBLEM_PREFIX +
"/C2EC_INVALID_PATH_PARAMETER",
diff --git a/c2ec/c2ec-config.yaml b/c2ec/c2ec-config.yaml
index 1ee8ffc..6ae068e 100644
--- a/c2ec/c2ec-config.yaml
+++ b/c2ec/c2ec-config.yaml
@@ -1,7 +1,7 @@
c2ec:
prod: false
host: "localhost"
- port: 8081
+ port: 8082
unix-domain-socket: false
unix-socket-path: "c2ec.sock"
fail-on-missing-attestors: false # forced if prod=true
diff --git a/c2ec/db.go b/c2ec/db.go
index a65ad55..0a799d1 100644
--- a/c2ec/db.go
+++ b/c2ec/db.go
@@ -155,5 +155,5 @@ type C2ECDatabase interface {
wopid WithdrawalIdentifier,
out chan WithdrawalOperationStatus,
errs chan error,
- ) (WithdrawalOperationStatus, error)
+ )
}
diff --git a/c2ec/db/0000-c2ec_schema.sql b/c2ec/db/0000-c2ec_schema.sql
index 061989c..cdf81e7 100644
--- a/c2ec/db/0000-c2ec_schema.sql
+++ b/c2ec/db/0000-c2ec_schema.sql
@@ -81,7 +81,7 @@ CREATE TABLE IF NOT EXISTS withdrawal (
wopid BYTEA CHECK (LENGTH(wopid)=32) NOT NULL,
reserve_pub_key BYTEA CHECK (LENGTH(reserve_pub_key)=32) NOT NULL,
registration_ts INT8 NOT NULL,
- amount taler_amount_currency NOT NULL,
+ amount taler_amount_currency,
fees taler_amount_currency,
withdrawal_status withdrawal_operation_status NOT NULL DEFAULT 'pending',
terminal_id INT8 NOT NULL REFERENCES terminal(terminal_id),
diff --git a/c2ec/http-util.go b/c2ec/http-util.go
index 4cd8158..2ddb840 100644
--- a/c2ec/http-util.go
+++ b/c2ec/http-util.go
@@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
+ "io"
"net/http"
"strings"
)
@@ -147,14 +148,15 @@ func ReadStructFromBody[T any](req *http.Request, codec
Codec[T]) (*T, error) {
func ReadBody(req *http.Request) ([]byte, error) {
if req.ContentLength < 0 {
- return make([]byte, 0), nil
+ return nil, errors.New("malformed body")
}
- body := make([]byte, req.ContentLength)
- _, err := req.Body.Read(body)
+ body, err := io.ReadAll(req.Body)
if err != nil {
+ LogError("http-util", err)
return nil, err
}
+ LogInfo("http-util", "read body from request. body="+string(body))
return body, nil
}
diff --git a/c2ec/logger.go b/c2ec/logger.go
index eece29c..89dd7e8 100644
--- a/c2ec/logger.go
+++ b/c2ec/logger.go
@@ -8,8 +8,8 @@ import (
const LOG_PATH = "c2ec-log.txt"
-// LEVEL | TIME | MESSAGE
-const LOG_PATTERN = "%d | %s | %s"
+// LEVEL | TIME | SRC | MESSAGE
+const LOG_PATTERN = "level=%d | time=%s | src=%s | %s"
const TIME_FORMAT = "yyyy-MM-dd hh:mm:ss"
type LogLevel int
@@ -20,29 +20,29 @@ const (
ERROR
)
-func LogError(err error) {
+func LogError(src string, err error) {
- go logAppendError(ERROR, err)
+ go logAppendError(src, ERROR, err)
}
-func LogWarn(msg string) {
+func LogWarn(src string, msg string) {
- go logAppend(WARN, msg)
+ go logAppend(src, WARN, msg)
}
-func LogInfo(msg string) {
+func LogInfo(src string, msg string) {
- go logAppend(INFO, msg)
+ go logAppend(src, INFO, msg)
}
-func logAppendError(level LogLevel, err error) {
+func logAppendError(src string, level LogLevel, err error) {
- logAppend(level, err.Error())
+ logAppend(src, level, err.Error())
}
-func logAppend(level LogLevel, msg string) {
+func logAppend(src string, level LogLevel, msg string) {
- openAppendClose(fmt.Sprintf(LOG_PATTERN, level,
time.Now().Format(time.UnixDate), msg))
+ openAppendClose(fmt.Sprintf(LOG_PATTERN, level,
time.Now().Format(time.UnixDate), src, msg))
}
func openAppendClose(s string) {
@@ -53,6 +53,7 @@ func openAppendClose(s string) {
// if file does not yet exist, open with create flag.
f, err = os.OpenFile(LOG_PATH,
os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil || f == nil {
+ fmt.Println("error: ", err.Error())
panic("failed opening or creating log file")
}
}
diff --git a/c2ec/main.go b/c2ec/main.go
index 370d55d..c6e149c 100644
--- a/c2ec/main.go
+++ b/c2ec/main.go
@@ -42,7 +42,7 @@ var PROVIDER_CLIENTS = map[string]ProviderClient{}
// 6. listen for incoming requests (as specified in config)
func main() {
- LogInfo(fmt.Sprintf("starting c2ec at %s",
time.Now().Format(time.UnixDate)))
+ LogInfo("main", fmt.Sprintf("starting c2ec at %s",
time.Now().Format(time.UnixDate)))
cfgPath := DEFAULT_C2EC_CONFIG_PATH
if len(os.Args) > 1 && os.Args[1] != "" {
@@ -127,7 +127,7 @@ func setupAttestors(cfg *C2ECConfig) error {
if cfg.Server.IsProd || cfg.Server.StrictAttestors {
panic("no provider entry for " + provider.Name)
} else {
- fmt.Println("non-strict attestor
initialization. skipping", provider)
+ LogWarn("non-strict attestor initialization.
skipping", provider.Name)
continue
}
}
diff --git a/c2ec/model.go b/c2ec/model.go
index 8b5e0b8..56b1dcb 100644
--- a/c2ec/model.go
+++ b/c2ec/model.go
@@ -53,11 +53,11 @@ func ToWithdrawalOpStatus(s string)
(WithdrawalOperationStatus, error) {
func WopidValid(wopid string) bool {
decoded, err := base64.URLEncoding.DecodeString(wopid)
- LogInfo(fmt.Sprintf("decoded wopid=%s", string(decoded)))
if err != nil {
- LogError(err)
+ LogError("model", err)
+ return false
}
- return err != nil //&& len(wopidBytes) == 32
+ return len(decoded) == 32
}
type ErrorDetail struct {
diff --git a/c2ec/postgres.go b/c2ec/postgres.go
index a8a2597..8fc277b 100644
--- a/c2ec/postgres.go
+++ b/c2ec/postgres.go
@@ -3,10 +3,12 @@ package main
import (
"bytes"
"context"
+ "encoding/base32"
"encoding/base64"
"errors"
"fmt"
"math"
+ "strconv"
"time"
"github.com/jackc/pgx/v5"
@@ -18,7 +20,7 @@ import (
const PS_ASC_SELECTOR = "ASC"
const PS_DESC_SELECTOR = "DESC"
-const PS_INSERT_WITHDRAWAL = "INSERT INTO " + WITHDRAWAL_TABLE_NAME + " (" +
+const PS_INSERT_WITHDRAWAL = "INSERT INTO " + WITHDRAWAL_TABLE_NAME + " (" +
WITHDRAWAL_FIELD_NAME_WOPID + "," +
WITHDRAWAL_FIELD_NAME_RESPUBKEY + "," +
WITHDRAWAL_FIELD_NAME_STATUS + "," +
@@ -116,21 +118,32 @@ func (db *C2ECPostgres) RegisterWithdrawal(
terminalId uint64,
) error {
+ resPubKeyBytes, err :=
base32.HexEncoding.DecodeString(string(resPubKey))
+ if err != nil {
+ return err
+ }
+
ts := time.Now()
res, err := db.pool.Query(
db.ctx,
PS_INSERT_WITHDRAWAL,
wopid,
- resPubKey,
+ resPubKeyBytes,
SELECTED,
ts.Unix(),
terminalId,
)
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return err
}
- res.Close()
+ defer res.Close()
+ if res.Err() != nil {
+ LogError("postgres", err)
+ return err
+ }
+ LogInfo("postgres", "query="+PS_INSERT_WITHDRAWAL)
+ LogInfo("postgres", "registered withdrawal successfully. affected
rows="+strconv.Itoa(int(res.CommandTag().RowsAffected())))
return nil
}
@@ -141,7 +154,7 @@ func (db *C2ECPostgres) GetWithdrawalByWopid(wopid string)
(*Withdrawal, error)
PS_GET_WITHDRAWAL_BY_WOPID,
wopid,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -152,13 +165,14 @@ func (db *C2ECPostgres) GetWithdrawalByWopid(wopid
string) (*Withdrawal, error)
withdrawals, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Withdrawal])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
if len(withdrawals) < 1 {
return nil, nil
}
+ LogInfo("postgres", "query="+PS_GET_WITHDRAWAL_BY_WOPID)
return withdrawals[0], nil
}
}
@@ -169,7 +183,7 @@ func (db *C2ECPostgres)
GetWithdrawalByProviderTransactionId(tid string) (*Withd
PS_GET_WITHDRAWAL_BY_PTID,
tid,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -180,13 +194,14 @@ func (db *C2ECPostgres)
GetWithdrawalByProviderTransactionId(tid string) (*Withd
withdrawals, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Withdrawal])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
if len(withdrawals) < 1 {
return nil, nil
}
+ LogInfo("postgres", "query="+PS_GET_WITHDRAWAL_BY_PTID)
return withdrawals[0], nil
}
}
@@ -206,10 +221,11 @@ func (db *C2ECPostgres) NotifyPayment(
fees,
)
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return err
}
res.Close()
+ LogInfo("postgres", "query="+PS_PAYMENT_NOTIFICATION)
return nil
}
@@ -219,7 +235,7 @@ func (db *C2ECPostgres) GetAttestableWithdrawals()
([]*Withdrawal, error) {
db.ctx,
PS_GET_UNCONFIRMED_WITHDRAWALS,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -230,10 +246,11 @@ func (db *C2ECPostgres) GetAttestableWithdrawals()
([]*Withdrawal, error) {
withdrawals, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Withdrawal])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
+ LogInfo("postgres", "query="+PS_GET_UNCONFIRMED_WITHDRAWALS)
return withdrawals, nil
}
}
@@ -256,10 +273,11 @@ func (db *C2ECPostgres) FinaliseWithdrawal(
withdrawalId,
)
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return err
}
res.Close()
+ LogInfo("postgres", "query="+PS_FINALISE_PAYMENT)
return nil
}
@@ -305,7 +323,7 @@ func (db *C2ECPostgres) GetConfirmedWithdrawals(start int,
delta int) ([]*Withdr
}
if err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -316,10 +334,11 @@ func (db *C2ECPostgres) GetConfirmedWithdrawals(start
int, delta int) ([]*Withdr
withdrawals, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Withdrawal])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
+ LogInfo("postgres", "query="+PS_CONFIRMED_TRANSACTIONS)
return withdrawals, nil
}
}
@@ -331,7 +350,7 @@ func (db *C2ECPostgres) GetTerminalProviderByName(name
string) (*Provider, error
PS_GET_PROVIDER_BY_NAME,
name,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -342,7 +361,7 @@ func (db *C2ECPostgres) GetTerminalProviderByName(name
string) (*Provider, error
provider, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Provider])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
@@ -350,6 +369,7 @@ func (db *C2ECPostgres) GetTerminalProviderByName(name
string) (*Provider, error
return nil, nil
}
+ LogInfo("postgres", "query="+PS_GET_PROVIDER_BY_NAME)
return provider[0], nil
}
}
@@ -361,7 +381,7 @@ func (db *C2ECPostgres)
GetTerminalProviderByPaytoTargetType(paytoTargetType str
PS_GET_PROVIDER_BY_PAYTO_TARGET_TYPE,
paytoTargetType,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -372,7 +392,7 @@ func (db *C2ECPostgres)
GetTerminalProviderByPaytoTargetType(paytoTargetType str
provider, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Provider])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
@@ -380,6 +400,7 @@ func (db *C2ECPostgres)
GetTerminalProviderByPaytoTargetType(paytoTargetType str
return nil, nil
}
+ LogInfo("postgres",
"query="+PS_GET_PROVIDER_BY_PAYTO_TARGET_TYPE)
return provider[0], nil
}
}
@@ -391,7 +412,7 @@ func (db *C2ECPostgres) GetTerminalById(id int) (*Terminal,
error) {
PS_GET_TERMINAL_BY_ID,
id,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -402,7 +423,7 @@ func (db *C2ECPostgres) GetTerminalById(id int) (*Terminal,
error) {
terminals, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Terminal])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
@@ -410,6 +431,7 @@ func (db *C2ECPostgres) GetTerminalById(id int) (*Terminal,
error) {
return nil, nil
}
+ LogInfo("postgres", "query="+PS_GET_TERMINAL_BY_ID)
return terminals[0], nil
}
}
@@ -421,7 +443,7 @@ func (db *C2ECPostgres) GetTransferById(requestUid
HashCode) (*Transfer, error)
PS_GET_TRANSFER_BY_ID,
requestUid,
); err != nil {
- LogError(err)
+ LogError("postgres", err)
if row != nil {
row.Close()
}
@@ -432,13 +454,14 @@ func (db *C2ECPostgres) GetTransferById(requestUid
HashCode) (*Transfer, error)
transfers, err := pgx.CollectRows(row,
pgx.RowToAddrOfStructByName[Transfer])
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return nil, err
}
if len(transfers) < 1 {
return nil, nil
}
+ LogInfo("postgres", "query="+PS_GET_TRANSFER_BY_ID)
return transfers[0], nil
}
@@ -453,10 +476,11 @@ func (db *C2ECPostgres) AddTransfer(requestId HashCode,
requestHash string) erro
requestHash,
)
if err != nil {
- LogError(err)
+ LogError("postgres", err)
return err
}
res.Close()
+ LogInfo("postgres", "query="+PS_ADD_TRANSFER)
return nil
}
@@ -465,36 +489,45 @@ func (db *C2ECPostgres) ListenForWithdrawalStatusChange(
wopid WithdrawalIdentifier,
out chan WithdrawalOperationStatus,
errs chan error,
-) (WithdrawalOperationStatus, error) {
+) {
pgNotification := make(chan *pgconn.Notification)
- channel := "w_" +
base64.StdEncoding.EncodeToString(bytes.NewBufferString(string(wopid)).Bytes())
- listener := newChannelListener(db.pool.Config().ConnConfig, channel,
pgNotification)
go func() {
+
+ connstr := PostgresConnectionString(&CONFIG.Database)
+ cfg, err := pgx.ParseConfig(connstr)
+ if err != nil {
+ errs <- err
+ }
+
+ channel := "w_" +
base64.StdEncoding.EncodeToString(bytes.NewBufferString(string(wopid)).Bytes())
+ listener := newChannelListener(cfg, channel, pgNotification)
+ LogInfo("postgres", fmt.Sprintf("listening for %s", wopid))
+
if err := listener.Listen(ctx); err != nil {
+ LogError("postgres", err)
errs <- err
}
- // close the channel we send results, because listener has
finished.
- close(pgNotification)
}()
- select {
- case e := <-errs:
- LogError(e)
- return "", e
- case <-ctx.Done():
- err := ctx.Err()
- msg := "context sent done signal while listening for status
change"
- if err != nil {
- LogError(err)
- } else {
- LogWarn(msg)
+ for {
+ select {
+ case e := <-errs:
+ LogError("postgres", e)
+ errs <- e
+ case <-ctx.Done():
+ err := ctx.Err()
+ msg := "context sent done signal while listening for
status change"
+ if err != nil {
+ LogError("postgres", err)
+ }
+ LogWarn("postgres", msg)
+ errs <- errors.New(msg)
+ case n := <-pgNotification:
+ LogInfo("postgres", fmt.Sprintf("received notification
for channel %s: %s", n.Channel, n.Payload))
+ out <- WithdrawalOperationStatus(n.Payload)
}
- return "", errors.New(msg)
- case n := <-pgNotification:
- LogInfo(fmt.Sprintf("received notification for channel %s: %s",
n.Channel, n.Payload))
- return WithdrawalOperationStatus(n.Payload), nil
}
}
@@ -507,16 +540,22 @@ func newChannelListener(
listener := &pgxlisten.Listener{
Connect: func(ctx context.Context) (*pgx.Conn, error) {
+ LogInfo("postgres", "connecting to the database")
return pgx.ConnectConfig(ctx, cfg)
},
}
listener.Handle(cn, pgxlisten.HandlerFunc(func(ctx context.Context,
notification *pgconn.Notification, conn *pgx.Conn) error {
- select {
- case out <- notification:
- case <-ctx.Done():
+ LogInfo("postgres", fmt.Sprintf("handling postgres
notification. channel=%s", notification.Channel))
+ for {
+ select {
+ case out <- notification:
+ LogInfo("postgres", fmt.Sprintf("received
notification. channel=%s, notification=%s", notification.Channel,
notification.Payload))
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
}
- return nil
}))
return listener
diff --git a/c2ec/wallee-attestor.go b/c2ec/wallee-attestor.go
index f390101..9ceb867 100644
--- a/c2ec/wallee-attestor.go
+++ b/c2ec/wallee-attestor.go
@@ -54,7 +54,7 @@ func (wa *WalleeAttestor) Listen(
go func() {
err := wa.listener.Listen(ctx)
if err != nil {
- LogError(err)
+ LogError("wallee-attestor", err)
errs <- err
}
close(notificationChannel)
diff --git a/c2ec/wallee-client.go b/c2ec/wallee-client.go
index bb6d83d..87b48cc 100644
--- a/c2ec/wallee-client.go
+++ b/c2ec/wallee-client.go
@@ -174,7 +174,7 @@ func calculateWalleeAuthToken(
key := make([]byte, base64.StdEncoding.DecodedLen(len(userKeyBase64)))
_, err := base64.StdEncoding.Decode(key, []byte(userKeyBase64))
if err != nil {
- LogError(err)
+ LogError("wallee-client", err)
return "", err
}
@@ -185,7 +185,7 @@ func calculateWalleeAuthToken(
macer := hmac.New(sha512.New, key)
_, err = macer.Write(authMsg)
if err != nil {
- LogError(err)
+ LogError("wallee-client", err)
return "", err
}
mac := make([]byte, 64)
diff --git a/c2ec/c2ec-log.txt b/simulation/README
similarity index 100%
rename from c2ec/c2ec-log.txt
rename to simulation/README
diff --git a/simulation/c2ec-simulation b/simulation/c2ec-simulation
index 8952b8c..14a6430 100755
Binary files a/simulation/c2ec-simulation and b/simulation/c2ec-simulation
differ
diff --git a/simulation/http-util.go b/simulation/http-util.go
index 2f9e34a..b2fe628 100644
--- a/simulation/http-util.go
+++ b/simulation/http-util.go
@@ -178,7 +178,7 @@ func HttpGet[T any](
}
req.Header.Add("Accept", codec.HttpApplicationContentHeader())
- fmt.Printf("requesting %s\n", url)
+ fmt.Printf("requesting GET %s\n", url)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, -1, err
diff --git a/simulation/sim-terminal.go b/simulation/sim-terminal.go
index 1d48dd0..ecc1813 100644
--- a/simulation/sim-terminal.go
+++ b/simulation/sim-terminal.go
@@ -1,10 +1,12 @@
package main
import (
+ "bytes"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
+ "net/http"
"strconv"
"time"
)
@@ -17,7 +19,7 @@ const TERMINAL_USER_ID = TERMINAL_PROVIDER + "-1"
// retrieved from the cli tool when added the terminal
const TERMINAL_ACCESS_TOKEN = "secret"
-const SIM_TERMINAL_LONG_POLL_MS_STR = "20000" // 20 seconds
+const SIM_TERMINAL_LONG_POLL_MS_STR = "5000" // 20 seconds
const QR_CODE_CONTENT_BASE = "taler://withdraw/localhost:8081/c2ec/"
@@ -43,8 +45,11 @@ func Terminal(in chan *SimulatedPhysicalInteraction, out
chan *SimulatedPhysical
// -> start long polling always before showing the QR code
awaitSelection := make(chan *C2ECWithdrawalStatus)
longPollFailed := make(chan error)
+
+ out <- &SimulatedPhysicalInteraction{Msg: uri}
+
+ fmt.Println("now sending long poll request to c2ec from terminal and
await parameter selection")
go func() {
- // long poll for parameter selection notification by c2ec
url := FormatUrl(
C2EC_BANK_WITHDRAWAL_STATUS_URL,
@@ -68,8 +73,6 @@ func Terminal(in chan *SimulatedPhysicalInteraction, out chan
*SimulatedPhysical
awaitSelection <- response
}()
- out <- &SimulatedPhysicalInteraction{Msg: uri}
-
for {
select {
case w := <-awaitSelection:
@@ -78,12 +81,46 @@ func Terminal(in chan *SimulatedPhysicalInteraction, out
chan *SimulatedPhysical
if !DISABLE_DELAYS {
time.Sleep(time.Duration(TERMINAL_ACCEPT_CARD_DELAY_MS))
}
- fmt.Println("the card was tead by the terminal.
simulating the payment using the providers backend. delay:",
PROVIDER_BACKEND_PAYMENT_DELAY_MS)
+ fmt.Println("card accepted. terminal waits for response
of provider backend.")
if !DISABLE_DELAYS {
time.Sleep(time.Duration(PROVIDER_BACKEND_PAYMENT_DELAY_MS))
}
- // sending payment notification now...
+ fmt.Println("payment was processed at the provider
backend. sending payment notification.")
+ paymentNotification := &C2ECPaymentNotification{
+ ProviderTransactionId:
"simulation-transaction-id-0",
+ Amount: Amount{
+ Currency: "CHF",
+ Fraction: 10,
+ Value: 10,
+ },
+ Fees: Amount{
+ Currency: "CHF",
+ Fraction: 10,
+ Value: 0,
+ },
+ }
+ cdc := NewJsonCodec[C2ECPaymentNotification]()
+ pnbytes, err := cdc.EncodeToBytes(paymentNotification)
+ if err != nil {
+ fmt.Println("failed serializing payment
notification")
+ kill <- err
+ }
+ paymentUrl := FormatUrl(
+ C2EC_BANK_WITHDRAWAL_PAYMENT_URL,
+ map[string]string{"wopid": wopid},
+ map[string]string{},
+ )
+ _, err = http.Post(
+ paymentUrl,
+ cdc.HttpApplicationContentHeader(),
+ bytes.NewReader(pnbytes),
+ )
+ if err != nil {
+ fmt.Println("error on POST request:",
err.Error())
+ kill <- err
+ }
+ fmt.Println("Terminal flow ended")
case f := <-longPollFailed:
fmt.Println("long-polling for selection failed...
error:", err.Error())
kill <- f
diff --git a/simulation/sim-wallet.go b/simulation/sim-wallet.go
index c659e48..5162a3c 100644
--- a/simulation/sim-wallet.go
+++ b/simulation/sim-wallet.go
@@ -13,7 +13,7 @@ import (
"time"
)
-const SIM_WALLET_LONG_POLL_MS_STR = "20000" // 20 seconds
+const SIM_WALLET_LONG_POLL_MS_STR = "5000" // 20 seconds
func Wallet(in chan *SimulatedPhysicalInteraction, out chan
*SimulatedPhysicalInteraction, kill chan error) {
@@ -45,19 +45,26 @@ func Wallet(in chan *SimulatedPhysicalInteraction, out chan
*SimulatedPhysicalIn
}
cdc := NewJsonCodec[C2ECWithdrawRegistration]()
- body, err := cdc.EncodeToBytes(&C2ECWithdrawRegistration{
- ReservePubKey: EddsaPublicKey(simulateReservePublicKey()),
- TerminalId: uint64(tid),
- })
+ reg := new(C2ECWithdrawRegistration)
+ reg.ReservePubKey = EddsaPublicKey(simulateReservePublicKey())
+ reg.TerminalId = uint64(tid)
+ body, err := cdc.EncodeToBytes(reg)
+ regByte := bytes.NewBuffer(body)
+ // fmt.Println("body (bytes):", regByte.Bytes())
if err != nil {
kill <- err
}
res, err := http.Post(
registrationUrl,
cdc.HttpApplicationContentHeader(),
- bytes.NewBuffer(body),
+ bytes.NewReader(regByte.Bytes()),
)
+ if err != nil {
+ fmt.Println("error on POST request:", err.Error())
+ kill <- err
+ }
+
if res.StatusCode != 204 {
fmt.Println("response status from registration:",
res.StatusCode)
kill <- errors.New("failed registering the withdrawal
parameters")
@@ -68,9 +75,9 @@ func Wallet(in chan *SimulatedPhysicalInteraction, out chan
*SimulatedPhysicalIn
// Start long poll for confirmed or abort
awaitConfirmationOrAbortion := make(chan *C2ECWithdrawalStatus)
longPollFailed := make(chan error)
- go func() {
- // long poll for parameter selection notification by c2ec
+ // long poll for parameter selection notification by c2ec
+ go func() {
url := FormatUrl(
C2EC_BANK_WITHDRAWAL_STATUS_URL,
map[string]string{"wopid": wopid},
@@ -89,7 +96,6 @@ func Wallet(in chan *SimulatedPhysicalInteraction, out chan
*SimulatedPhysicalIn
longPollFailed <- errors.New("status of withdrawal
status response was " + strconv.Itoa(status))
return
}
-
awaitConfirmationOrAbortion <- response
}()
@@ -106,11 +112,10 @@ func Wallet(in chan *SimulatedPhysicalInteraction, out
chan *SimulatedPhysicalIn
os.Exit(0)
}
case f := <-longPollFailed:
- fmt.Println("long-polling for selection failed...
error:", err.Error())
+ fmt.Println("long-polling for selection failed...
error:", f.Error())
kill <- f
}
}
-
}
// returns wopid.
--
To stop receiving notification emails like this one, please contact
gnunet@gnunet.org.
- [taler-cashless2ecash] branch master updated (889a4e9 -> 470230f),
gnunet <=