gnunet-svn
[Top][All Lists]
Advanced

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

[GNUnet-SVN] [taler-bank] branch master updated (a3e7f9d -> 8c2d25b)


From: gnunet
Subject: [GNUnet-SVN] [taler-bank] branch master updated (a3e7f9d -> 8c2d25b)
Date: Fri, 29 Mar 2019 18:08:19 +0100

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

marcello pushed a change to branch master
in repository bank.

    from a3e7f9d  "/history" new policy for  'start' default.
     new eadac43  Hot-addressing #5542.
     new c4a08b5  Minor change for #5542.
     new a475bd0  Handling new exeption within the middleware.
     new 1192d66  providing the 'hint' field to those exeptions missing it.
     new 87378c6  typo
     new 5bc40f6  Addressing #5543.
     new 10c96a7  Addressing #5543.
     new 95bf6b0  Addressing #5543.
     new efd3fa0  5543.  Let Jinja render abnormal balances.
     new 4bef7eb  syntax
     new 0d43973  syntax
     new 8c2d25b  #5546

The 12 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:
 talerbank/app/amount.py                   | 68 ++++++++++++++-----------------
 talerbank/app/middleware.py               | 16 +++++---
 talerbank/app/models.py                   | 29 ++++++++++++-
 talerbank/app/templates/profile_page.html |  7 +++-
 talerbank/app/views.py                    |  3 +-
 talerbank/jinja2.py                       | 17 ++++++++
 6 files changed, 92 insertions(+), 48 deletions(-)

diff --git a/talerbank/app/amount.py b/talerbank/app/amount.py
index 458fdea..83f91e0 100644
--- a/talerbank/app/amount.py
+++ b/talerbank/app/amount.py
@@ -5,23 +5,25 @@
 #  This library is free software; you can redistribute it and/or
 #  modify it under the terms of the GNU Lesser General Public
 #  License as published by the Free Software Foundation; either
-#  version 2.1 of the License, or (at your option) any later version.
+#  version 2.1 of the License, or (at your option) any later
+# version.
 #
 #  This library is distributed in the hope that it will be useful,
 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-#  Lesser General Public License for more details.
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU Lesser General Public License for more details.
 #
 #  You should have received a copy of the GNU Lesser General Public
-#  License along with this library; if not, write to the Free Software
-#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  
USA
+#  License along with this library; if not, write to the Free
+#  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+#  Boston, MA  02110-1301  USA
 #
 #  @author Marcello Stanisci
 #  @version 0.1
 #  @repository https://git.taler.net/copylib.git/
 #  This code is "copylib", it is versioned under the Git repository
-#  mentioned above, and it is meant to be manually copied into any project
-#  which might need it.
+#  mentioned above, and it is meant to be manually copied into
+#  any project which might need it.
 
 
 ##
@@ -41,31 +43,12 @@ class CurrencyMismatch(Exception):
         super(CurrencyMismatch, self).__init__(
             "%s vs %s" % (curr1, curr2))
 
-
-##
-# Exception class to raise when an amount object
-# is getting a value "too big"; the threshold here is
-# the maximum value that the wallet can handle, which
-# is 2^53 - 1.
-class AmountOverflow(Exception):
-    hint = "Overflowing amount"
-
-    ##
-    # Init constructor.
-    #
-    # @param self the object itself
-    # @param part whether the exception occurred in a 'value'
-    #        or in a 'fraction' part of an amount.
-    def __init__(self, part) -> None:
-        super(BadFormatAmount, self).__init__(
-            "This part exceedes 2^53 -1: " + part)
-
-
 ##
 # Exception class to raise when a amount string is not valid.
 class BadFormatAmount(Exception):
-    hint = "Amount given was incorrect"
-    
+
+    hint = "Malformed amount string"
+
     ##
     # Init constructor.
     #
@@ -75,9 +58,20 @@ class BadFormatAmount(Exception):
         super(BadFormatAmount, self).__init__(
             "Bad format amount: " + faulty_str)
 
-
 ##
 # Main Amount class.
+class NumberTooBig(Exception):
+    hint = "Number given is too big"
+    def __init__(self) -> None:
+        super(NumberTooBig, self).__init__(
+            "Number given is too big")
+
+class NegativeNumber(Exception):
+    hint = "Negative number given as value and/or fraction"
+    def __init__(self) -> None:
+        super(NegativeNumber, self).__init__(
+            "Negative number given as value and/or fraction")
+
 class Amount:
     ##
     # How many "fraction" units make one "value" unit of currency
@@ -102,17 +96,14 @@ class Amount:
     # @param value integer part the amount
     # @param fraction fractional part of the amount
     def __init__(self, currency, value=0, fraction=0) -> None:
-
-        # NOTE: the following, not-so-good, assertions got
-        # eliminated in the _stable_ branch due to a recent
-        # hot-fix.  So this file is going to have to be manually
-        # deconflicted.
-        assert value >= 0 and fraction >= 0
+        if value < 0 or fraction < 0:
+            raise NegativeNumber()
         self.value = value
         self.fraction = fraction
         self.currency = currency
         self.__normalize()
-        assert self.value <= Amount._max_value()
+        if self.value > Amount._max_value():
+            raise NumberTooBig()
 
     ##
     # Normalize amount.  It means it makes sure that the
@@ -241,7 +232,8 @@ class Amount:
     # @param pretty if True, put the currency in the last position and
     #        omit the colon.
     def stringify(self, ndigits: int, pretty=False) -> str:
-        assert ndigits > 0
+        if ndigits <= 0:
+            raise BadFormatAmount("ndigits must be > 0")
         tmp = self.fraction
         fraction_str = ""
         while ndigits > 0:
diff --git a/talerbank/app/middleware.py b/talerbank/app/middleware.py
index 214a21e..a5888e2 100644
--- a/talerbank/app/middleware.py
+++ b/talerbank/app/middleware.py
@@ -7,8 +7,10 @@ from .views import \
      LoginFailed, RejectNoRightsException)
 from .schemas import \
     (URLParameterMissing, URLParameterMalformed,
-     JSONFieldException)
-from .amount import CurrencyMismatch, BadFormatAmount
+     JSONFieldException, UnknownCurrencyException)
+from .amount import \
+    (CurrencyMismatch, BadFormatAmount,
+     NumberTooBig, NegativeNumber)
 
 LOGGER = logging.getLogger()
 
@@ -41,12 +43,15 @@ class ExceptionMiddleware:
             CurrencyMismatch: 11,
             BadFormatAmount: 11,
             LoginFailed: 12,
-            RejectNoRightsException: 13}
-
+            RejectNoRightsException: 13,
+            UnknownCurrencyException: 14,
+            NumberTooBig: 1,
+            NegativeNumber: 0}
 
         # List of all the HTTP endpoint that are likely
         # to generate exceptions.
         self.apis = {
+            "/withdraw": 5400,
             "/reject": 5300,
             "/history": 5200,
             "/admin/add/incoming": 5100}
@@ -58,7 +63,8 @@ class ExceptionMiddleware:
             "/profile": "profile",
             "/register": "index",
             "/public-accounts": "index",
-            "/pin/verify": "profile"}
+            "/pin/verify": "profile",
+            "/withdraw": "profile"}
 
     ##
     # This function is transparently invoked by Django when
diff --git a/talerbank/app/models.py b/talerbank/app/models.py
index 0e9cc47..5b52883 100644
--- a/talerbank/app/models.py
+++ b/talerbank/app/models.py
@@ -26,8 +26,18 @@ from django.conf import settings
 from django.core.exceptions import \
     ValidationError, \
     ObjectDoesNotExist
-from .amount import Amount, BadFormatAmount, CurrencyMismatch
+from .amount import Amount, BadFormatAmount, NumberTooBig
 
+class InvalidAmount(Amount):
+    def __init__(self, currency):
+        super(InvalidAmount, self).__init__(currency, value=float('nan'), 
fraction=float('nan'))
+
+    def stringify(self, ndigits, pretty):
+        return "Invalid Amount, please report"
+    def dump(self):
+        return "Invalid Amount, please report"
+
+class AmountField(models.Field):
 
 ##
 # Helper function that instantiates a zero-valued @a Amount
@@ -75,7 +85,22 @@ class AmountField(models.Field):
         del args # pacify PEP checkers
         if value is None:
             return Amount.parse(settings.TALER_CURRENCY)
-        return Amount.parse(value)
+        try:
+            return Amount.parse(value)
+        except NumberTooBig:
+            # Keep the currency right to avoid causing
+            # exceptions if some operation is attempted
+            # against this invalid amount.  NOTE that the
+            # value is defined as NaN, so no actual/useful
+            # amount will ever be generated using this one.
+            # And more, the NaN value will make it easier
+            # to scan the database to find these faulty
+            # amounts.
+            # We also decide to not raise exception here
+            # because they would propagate in too many places
+            # in the code, and it would be too verbose to
+            # just try-cactch any possible exception situation.
+            return InvalidAmount(settings.TALER_CURRENCY)
 
 
     ##
diff --git a/talerbank/app/templates/profile_page.html 
b/talerbank/app/templates/profile_page.html
index e5f9abc..8722a7d 100644
--- a/talerbank/app/templates/profile_page.html
+++ b/talerbank/app/templates/profile_page.html
@@ -38,7 +38,12 @@
 {% block content %}
   <section id="menu">
     <p>Account: # {{ account_no }}</p>
-    <p>Current balance: <b>{{ sign }} {{ balance }}</b></p>
+    {% if is_valid_amount(balance) %}
+      <p>Current balance: <b>{{ sign }} {{ amount_stringify(balance) }}</b></p>
+    {% else %}
+      <p class="informational-fail">Current balance: <b>INVALID AMOUNT, PLEASE 
REPORT</b></p>
+    {% endif%}
+
   </section>
   <section id="main">
     <article>
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index 6d87e22..2914341 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -247,8 +247,7 @@ def profile_page(request):
     fail_message, success_message, hint = get_session_hint(request, 
"profile_hint")
     context = dict(
         name=request.user.username,
-        balance=request.user.bankaccount.amount.stringify(
-            settings.TALER_DIGITS, pretty=True),
+        balance=request.user.bankaccount.amount,
         sign="-" if request.user.bankaccount.debit else "",
         fail_message=fail_message,
         success_message=success_message,
diff --git a/talerbank/jinja2.py b/talerbank/jinja2.py
index b646162..d6a1e2b 100644
--- a/talerbank/jinja2.py
+++ b/talerbank/jinja2.py
@@ -20,6 +20,7 @@
 #  @brief Extends the Jinja2 API with custom functions.
 
 import os
+import math
 from urllib.parse import urlparse
 from django.urls import reverse, get_script_prefix
 from django.conf import settings
@@ -108,6 +109,20 @@ def env_get(name, default=None):
 #
 # @param options opaque argument (?) given from the caller.
 # @return Jinja2-specific object that contains the new definitions.
+def is_valid_amount(amount):
+    if math.isnan(amount.value):
+        return False
+    return True
+
+
+##
+# Stringifies amount.
+#
+# @param amount amount object.
+# @return amount pretty string.
+def amount_stringify(amount):
+    return amount.stringify(settings.TALER_DIGITS, pretty=True)
+
 def environment(**options):
     env = Environment(**options)
     env.globals.update({
@@ -115,5 +130,7 @@ def environment(**options):
         'url': url,
         'settings_value': settings_value,
         'env': env_get,
+        'is_valid_amount': is_valid_amount,
+        'amount_stringify': amount_stringify
     })
     return env

-- 
To stop receiving notification emails like this one, please contact
address@hidden



reply via email to

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