From ef8294b0fdb8e2815beb8c43ce5fe5b4d8da9c2d Mon Sep 17 00:00:00 2001
From: adorda <adorda@boletinoficial.gob.ar>
Date: Tue, 26 Feb 2019 16:14:40 -0300
Subject: [PATCH] Agregados status, terminado el refactor sobre verify

---
 app/services.py | 33 +++++++++++++++++++++------------
 app/tests.py    | 22 ++++++++++++++--------
 app/views.py    |  9 +++++++--
 3 files changed, 42 insertions(+), 22 deletions(-)

diff --git a/app/services.py b/app/services.py
index d11c2b4..ab51a9e 100644
--- a/app/services.py
+++ b/app/services.py
@@ -30,10 +30,8 @@ class DefinitiveReceiptGenerator:
     interpreter = ReceiptInterpreter()
     gateway = EthereumGateway()
 
-    def generate_definitive_receipt(self, original_file_hash, temp_rd):
-        ots_version, ots_hash, tx_hash = self.interpreter.interpret(temp_rd)
+    def generate_definitive_receipt(self, original_file_hash, tx_hash, ots_hash):
         tx = self.gateway.transaction(tx_hash)
-
         return self.encoder.encode(Utils.get_permanent_ots(original_file_hash, ots_hash, tx_hash,
                                                            tx['blockNumber']).encode('utf-8')).decode('utf-8')
 
@@ -59,7 +57,8 @@ class SmartContractVerification:
         verified = self.timestamp.verify(ots_hash, file_hash)
         block = None
         if verified:
-            block = self.timestamp.get_block(ots_hash)
+            block_number = self.timestamp.get_block(ots_hash)
+            block = self.gateway.block(block_number)
         return verified, block
 
 
@@ -80,7 +79,11 @@ class VerifyService:
             ots_version, file_hash, ots_hash, tx_hash, block_number = self.interpreter.interpret(rd)
             verified, block = self.definitive_verificator.verify(original_file_hash, ots_hash)
             if verified:
-                return {'status': 'success', 'block': block}
+                return {'status': 'success',
+                        'block': block,
+                        'permanent_rd': self.receipt_generator.generate_definitive_receipt(original_file_hash,
+                                                                                           tx_hash,
+                                                                                           ots_hash)}
             else:
                 return {'status': 'failure'}
 
@@ -94,7 +97,9 @@ class VerifyService:
                 else:
                     return {'status': 'success',
                             'block': block,
-                            'permanent_rd': self.receipt_generator.generate_definitive_receipt(original_file_hash, rd)}
+                            'permanent_rd': self.receipt_generator.generate_definitive_receipt(original_file_hash,
+                                                                                               tx_hash,
+                                                                                               ots_hash)}
             else:
                 try:
                     if tx and not tx.blockNumber:
@@ -115,21 +120,25 @@ class VerifyServiceTranslation:
     def verify(self, original_file_hash, rd):
         result = self.verify_service.verify(original_file_hash, rd)
         dict_res = {gettext('status'): result['status']}
+        res_status = 200
         if result['status'] == 'success':
             dict_res[gettext('permanent_rd')] = result['permanent_rd']
             dict_res[gettext('attestation_time')] = str(Utils.datetime_from_timestamp(result['block'].timestamp))
             dict_res[gettext('messages')] = gettext('file_uploaded') % (
-                                                original_file_hash,
-                                                str(result['block'].number),
-                                                str(Utils.datetime_from_timestamp(result['block'].timestamp))
-                                            )
+                original_file_hash,
+                str(result['block'].number),
+                str(Utils.datetime_from_timestamp(result['block'].timestamp))
+            )
         elif result['status'] == 'failure':
-            dict_res[gettext('messages')] = result[gettext('file_not_found')]
+            dict_res[gettext('messages')] = gettext('file_not_found')
+            res_status = 404
         elif result['status'] == 'pending':
-            dict_res[gettext('messages')] = result[gettext('transaction_pending')]
+            dict_res[gettext('messages')] = gettext('transaction_pending')
         else:
             raise StatusNotValidException('Status invalid in verify service result : {}'.format(result['status']))
 
+        return dict_res, res_status
+
 
 class MemcachedStorage:
     client = base.Client((MEMCACHED_HOST, MEMCACHED_PORT))
diff --git a/app/tests.py b/app/tests.py
index 866e3b5..08b37f0 100644
--- a/app/tests.py
+++ b/app/tests.py
@@ -10,6 +10,8 @@ You should have received a copy of the GNU General Public License along with thi
 import base64
 import json
 import time
+import unittest
+
 from django.utils.translation import gettext as _
 from django.test import TestCase
 from django.test import Client
@@ -23,7 +25,7 @@ from app.services import PendingTransactionsService, CheckCriteria, MemcachedSto
     VerifyService
 
 
-class TimestampTest(TestCase):
+class TimestampTest(unittest.TestCase):
 
     def test_full_cycle(self):
         c = Client()
@@ -219,7 +221,7 @@ class EthereumMocks:
             ]
 
 
-class PendingTransactionTest(TestCase, EthereumMocks):
+class PendingTransactionTest(unittest.TestCase, EthereumMocks):
 
     def setUp(self):
         self.service = PendingTransactionsService()
@@ -272,7 +274,7 @@ class PendingTransactionTest(TestCase, EthereumMocks):
         self.assertEqual(failed, [txs[-1]])
 
 
-class MemcachedStorageTest(TestCase):
+class MemcachedStorageTest(unittest.TestCase):
 
     def setUp(self):
         self.storage = MemcachedStorage()
@@ -314,7 +316,7 @@ class MemcachedStorageTest(TestCase):
         self.assertEqual(some_stuff, retrieved)
 
 
-class TransactionUnstuckerTest(TestCase, EthereumMocks):
+class TransactionUnstuckerTest(unittest.TestCase, EthereumMocks):
 
     def setUp(self):
         self.unstucker = TransactionUnstucker()
@@ -374,12 +376,12 @@ class VerificationMocks:
     class NotSealedTransactionMock:
         def transaction(self, tx_hash):
             return AttributeDict(
-                {'hash': '0xf495705b5d7d68afdcefe72d9bbacec59b1a968c964ab0b6b13cec6491e5ddec', 'blockNumber': None})
+                {'hash': tx_hash, 'blockNumber': None})
 
     class SealedTransactionMock:
         def transaction(self, tx_hash):
             return AttributeDict(
-                {'hash': '0xf495705b5d7d68afdcefe72d9bbacec59b1a968c964ab0b6b13cec6491e5ddec', 'blockNumber': 1000})
+                {'hash': tx_hash, 'blockNumber': 1000})
 
     class TXisCanonicalMock:
         def transaction_is_canonical(self, tx):
@@ -403,8 +405,12 @@ class VerificationMocks:
     class TxNoCanonicalSealedTx(SealedTransactionMock, TXisNotCanonicalMock):
         pass
 
+    class ReceiptGeneratorMock:
+        def generate_definitive_receipt(self, original_file_hash, tx_hash, ots_hash):
+            return "{}{}{}".format(original_file_hash, tx_hash, ots_hash)
+
 
-class VerifyServiceTest(TestCase, VerificationMocks):
+class VerifyServiceTest(unittest.TestCase, VerificationMocks):
 
     def setUp(self):
         self.service = VerifyService()
@@ -444,10 +450,10 @@ class VerifyServiceTest(TestCase, VerificationMocks):
 
     def test_definitive_rd_correct(self):
         self.service.definitive_verificator = self.TrueVerificationMock()
+        self.service.receipt_generator = self.ReceiptGeneratorMock()
         res = self.service.verify(self.file_hash, self.def_rd)
         self.assertEqual(res['status'], 'success')
 
     def test_definitive_rd_incorrect(self):
         res = self.service.verify(self.file_hash, self.def_rd)
         self.assertEqual(res['status'], 'failure')
-
diff --git a/app/views.py b/app/views.py
index 53273c0..d5f8a2c 100644
--- a/app/views.py
+++ b/app/views.py
@@ -22,6 +22,9 @@ from app.managers import TimestampManager
 from app.services import VerifyService, VerifyServiceTranslation
 from app.utils import Utils
 from TsaApi.local_settings import TEMPORARY_OTS_PREFIX, PERMANENT_OTS_PREFIX, CONTRACTS
+import logging
+
+logger = logging.getLogger('logger')
 
 
 class Stamp(APIView):
@@ -134,9 +137,11 @@ class Verify(APIView):
 
             rd = base64.b64decode(base64_rd).decode('utf-8')
 
-            result = self.verify_service.verify(original_file_hash, rd)
+            # importante la asignación del prefijo de ots permanente
+            self.verify_service.verify_service.permanent_ots_prefix = PERMANENT_OTS_PREFIX
+            result, res_status = self.verify_service.verify(original_file_hash, rd)
 
-            return Response(result)
+            return Response(result, status=res_status)
         except ValidationError as e:
             return Response({_('status'): _('failure'), _('messages'): _('parameter_missing') % e.message},
                             status=status.HTTP_400_BAD_REQUEST)
-- 
GitLab