gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[taler-taldir] branch master updated: modify payment processing logic; s


From: gnunet
Subject: [taler-taldir] branch master updated: modify payment processing logic; still unclear
Date: Tue, 12 Jul 2022 09:11:24 +0200

This is an automated email from the git hooks/post-receive script.

martin-schanzenbach pushed a commit to branch master
in repository taldir.

The following commit(s) were added to refs/heads/master by this push:
     new f5099df  modify payment processing logic; still unclear
f5099df is described below

commit f5099df82d8053e276df4f857230b27acb884f0b
Author: Martin Schanzenbach <schanzen@gnunet.org>
AuthorDate: Tue Jul 12 09:11:21 2022 +0200

    modify payment processing logic; still unclear
---
 cmd/taldir-server/main_test.go |  4 +--
 pkg/rest/taldir.go             | 78 ++++++++++++++++++++++++------------------
 pkg/taler/merchant.go          |  4 +--
 pkg/util/helper.go             | 30 +++++++++-------
 4 files changed, 66 insertions(+), 50 deletions(-)

diff --git a/cmd/taldir-server/main_test.go b/cmd/taldir-server/main_test.go
index ef59687..0789905 100644
--- a/cmd/taldir-server/main_test.go
+++ b/cmd/taldir-server/main_test.go
@@ -42,7 +42,7 @@ var validRegisterRequest = []byte(`
     "address": "abc@test",
     "public_key": "000G006XE97PTWV3B7AJNCRQZA6BF26HPV3XZ07293FMY7KD4181946A90",
     "inbox_url": "myinbox@xyz",
-    "duration": 23000000
+    "duration": 51840000000000
   }
 `)
 
@@ -51,7 +51,7 @@ var validRegisterRequestShort = []byte(`
     "address": "abc@test",
     "public_key": "000G006XE97PTWV3B7AJNCRQZA6BF26HPV3XZ07293FMY7KD4181946A90",
     "inbox_url": "myinbox@xyz",
-    "duration": 10000000
+    "duration": 23328000000000
   }
 `)
 
diff --git a/pkg/rest/taldir.go b/pkg/rest/taldir.go
index b8734b3..2fd20ae 100644
--- a/pkg/rest/taldir.go
+++ b/pkg/rest/taldir.go
@@ -211,9 +211,6 @@ type Validation struct {
 
   // The beginning of the last solution timeframe
   LastSolutionTimeframeStart time.Time
-
-  // The Taler Merchant Order ID
-  OrderId string
 }
 
 type ErrorDetail struct {
@@ -341,7 +338,7 @@ func (t *Taldir) validationRequest(w http.ResponseWriter, r 
*http.Request){
   }
   entry.HsAddress = saltHAddress(validation.HAddress, t.Salt)
   entry.Inbox = validation.Inbox
-  entry.Duration = time.Duration(validation.Duration)
+  entry.Duration = time.Duration(entry.Duration.Microseconds() + 
validation.Duration)
   entry.RegisteredAt = time.Now().UnixMicro()
   entry.PublicKey = validation.PublicKey
   err = t.Db.First(&entry, "hs_address = ?", entry.HsAddress).Error
@@ -398,53 +395,28 @@ func (t *Taldir) registerRequest(w http.ResponseWriter, r 
*http.Request){
   validation.HAddress = h_address
   hs_address := saltHAddress(validation.HAddress, t.Salt)
   err = t.Db.First(&entry, "hs_address = ?", hs_address).Error
+  validation.Duration = req.Duration
   if err == nil {
     log.Println("Entry for this address already exists..")
     regAt := time.UnixMicro(entry.RegisteredAt)
     entryValidity := regAt.Add(entry.Duration)
+    requestedValidity := time.Now().Add(time.Duration(req.Duration))
     log.Printf("Entry valid until: %s , requested until: %s\n", entryValidity, 
time.Now().Add(time.Duration(req.Duration)))
-    if time.Now().Add(time.Duration(req.Duration)).Before(entryValidity) {
+    if requestedValidity.Before(entryValidity) {
       w.WriteHeader(http.StatusOK)
       w.Header().Set("Content-Type", "application/json")
       w.Write([]byte("{\"valid_until\": " + entryValidity.String() + "}"))
       return
+    } else {
+      validation.Duration = entryValidity.Sub(requestedValidity).Microseconds()
     }
   }
   err = t.Db.First(&validation, "h_address = ?", h_address).Error
   validation.Challenge = util.GenerateChallenge(t.ChallengeBytes)
   validation.Inbox = req.Inbox
-  validation.Duration = req.Duration
   validation.PublicKey = req.PublicKey
   validation.SolutionAttemptCount = 0
   validation.LastSolutionTimeframeStart = time.Now()
-  amountSum, amountSumStr, _ := util.AmountSum(t.Cfg.Section("taldir-" + 
vars["method"]).Key("challenge_fee").MustString("KUDOS:0"),
-                                               
t.Cfg.Section("taldir").Key("monthly_fee").MustString("KUDOS:0"))
-  if amountSum > 0 {
-    // FIXME what if provided order ID and validation order ID differ???
-    if len(validation.OrderId) == 0 {
-      // Add new order for new validations
-      orderId, newOrderErr := t.Merchant.AddNewOrder(amountSumStr)
-      if newOrderErr != nil {
-        w.WriteHeader(http.StatusInternalServerError)
-        return
-      }
-      validation.OrderId = orderId
-    }
-    // Check if order paid
-    payto, paytoErr := t.Merchant.IsOrderPaid(validation.OrderId)
-    if paytoErr != nil {
-      w.WriteHeader(http.StatusInternalServerError)
-      log.Println(paytoErr)
-      return
-    }
-    if len(payto) != 0 {
-      w.WriteHeader(http.StatusPaymentRequired)
-      w.Header().Set("Location", payto) // FIXME no idea what to do with this.
-      return
-    }
-    // In this case, this order was paid
-  }
-
   if err == nil {
     // Limit re-initiation attempts
     validation.InitiationCount++
@@ -476,6 +448,44 @@ func (t *Taldir) registerRequest(w http.ResponseWriter, r 
*http.Request){
     w.WriteHeader(http.StatusInternalServerError)
     return
   }
+
+  cost, currency, err := util.CalculateCost(t.Cfg.Section("taldir-" + 
vars["method"]).Key("challenge_fee").MustString("KUDOS:0"),
+                            
t.Cfg.Section("taldir").Key("monthly_fee").MustString("KUDOS:0"),
+                            time.Duration(validation.Duration),
+                            time.Duration(2592000000000)) //Fixme 1 Month in us
+  if err != nil {
+    w.WriteHeader(http.StatusInternalServerError)
+    return
+  }
+
+  log.Printf("The calculated cost for this registration is: %s:%f", currency, 
cost)
+  if cost > 0 {
+    // FIXME what if provided order ID and validation order ID differ???
+    if len(order.Id) == 0 {
+      // Add new order for new validations
+      orderId, newOrderErr := t.Merchant.AddNewOrder(cost, currency)
+      if newOrderErr != nil {
+        w.WriteHeader(http.StatusInternalServerError)
+        return
+      }
+      order.Id = orderId
+    }
+    // Check if order paid. FIXME: How to check if this the a correct order??
+    payto, paytoErr := t.Merchant.IsOrderPaid(order.Id)
+    if paytoErr != nil {
+      w.WriteHeader(http.StatusInternalServerError)
+      log.Println(paytoErr)
+      return
+    }
+    if len(payto) != 0 {
+      w.WriteHeader(http.StatusPaymentRequired)
+      w.Header().Set("Location", payto) // FIXME no idea what to do with this.
+      return
+    }
+    // In this case, this order was paid
+  }
+
+
   log.Println("Address registration request created:", validation)
   if !t.Cfg.Section("taldir-" + vars["method"]).HasKey("command") {
     log.Fatal(err)
diff --git a/pkg/taler/merchant.go b/pkg/taler/merchant.go
index 8c9705e..44d28a5 100644
--- a/pkg/taler/merchant.go
+++ b/pkg/taler/merchant.go
@@ -135,11 +135,11 @@ func (m *Merchant) IsOrderPaid(orderId string) (string, 
error) {
   return "", nil
 }
 
-func (m *Merchant) AddNewOrder(amount string) (string, error) {
+func (m *Merchant) AddNewOrder(cost float64, currency string) (string, error) {
   var newOrder PostOrderRequest
   var orderDetail MinimalOrderDetail
   var orderResponse PostOrderResponse
-  orderDetail.Amount = amount
+  orderDetail.Amount = fmt.Sprintf("%s:%f", currency, cost)
   // FIXME get from cfg
   orderDetail.Summary = "This is an order to a TalDir registration"
   newOrder.order = orderDetail
diff --git a/pkg/util/helper.go b/pkg/util/helper.go
index 62625dd..581eba3 100644
--- a/pkg/util/helper.go
+++ b/pkg/util/helper.go
@@ -26,6 +26,7 @@ import (
   "errors"
   "strings"
   "strconv"
+  "time"
 )
 
 
@@ -79,26 +80,31 @@ func AmountToFloat(amount string) (float64, error) {
   return amountFloat, nil
 }
 
+func ParseAmount(amount string) (float64, string, error) {
+  cur, err := AmountCurrency(amount)
+  if nil != err {
+    return 0.0, "", errors.New("Currency in amount malformed")
+  }
+  val, err := AmountToFloat(amount)
+  if err != nil {
+    return 0.0, "", err
+  }
+  return val, cur, nil
+}
+
 // Check if this is a non-zero, positive amount
-func AmountSum(amountA string, amountB string) (float64, string, error) {
-  curA, err := AmountCurrency(amountA)
+func CalculateCost(sliceCostAmount string, fixedCostAmount string, howLong 
time.Duration, sliceDuration time.Duration) (float64, string, error) {
+  sliceCount := howLong.Microseconds() / sliceDuration.Microseconds()
+  sliceCost, curA, err := ParseAmount(sliceCostAmount)
   if nil != err {
     return 0.0, "", errors.New("Currency in amount malformed")
   }
-  curB, err := AmountCurrency(amountB)
+  fixedCost, curB, err := ParseAmount(fixedCostAmount)
   if nil != err {
     return 0.0, "", errors.New("Currency in amount malformed")
   }
   if curA != curB {
     return 0.0, "", errors.New("Currency in amounts different")
   }
-  valA, err := AmountToFloat(amountA)
-  if err != nil {
-    return 0.0, "", err
-  }
-  valB, err := AmountToFloat(amountB)
-  if err != nil {
-    return 0.0, "", err
-  }
-  return valA + valB, curA, nil
+  return (float64(sliceCount) * sliceCost) + fixedCost, curA, nil
 }

-- 
To stop receiving notification emails like this one, please contact
gnunet@gnunet.org.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]