def handle(self, *args, **options):
     logger.debug("Comienzo del Command 'transaction_validator'")
     while True:
         logger.info("Pending transactions ...")
         bcobj = get_bcobj()
         try:
             status_pending = DocumentStatus.objects.get(name="Pendiente")
         except:
             logger.error("No se ha encontrado el estado 'Pendiente'")
             return None
         pending_txs = Document.objects.filter(status=status_pending)
         for tx in pending_txs:
             if bcobj.is_validated(tx.tx_id):
                 try:
                     status = DocumentStatus.objects.get(name="Confirmado")
                 except DocumentStatus.DoesNotExist:
                     logger.error(
                         "No se ha encontrado el estado 'Confirmado'")
                     return None
                 tx.status = status
                 tx.save()
                 logger.info(f'Transacción {tx.tx_id} validada')
             elif (tx.timestamp + timedelta(seconds=60)) < timezone.now():
                 try:
                     status = DocumentStatus.objects.get(name="Rechazado")
                 except Exception as e:
                     logger.error(
                         "No se ha encontrado el estado 'Rechazado'")
                     return None
                 tx.status = status
                 tx.save()
                 logger.warning(f'Transacción {tx.tx_id} rechazada')
         pending_actions = CollaboratorAction.objects.filter(
             status=status_pending)
         for action in pending_actions:
             if bcobj.is_validated(action.tx_id):
                 try:
                     status = DocumentStatus.objects.get(name="Confirmado")
                 except DocumentStatus.DoesNotExist:
                     logger.error(
                         "No se ha encontrado el estado 'Confirmado'")
                     return None
                 action.status = status
                 action.save()
                 logger.info(f'Transacción {action.tx_id} validada')
             elif (action.timestamp +
                   timedelta(seconds=60)) < timezone.now():
                 try:
                     status = DocumentStatus.objects.get(name="Rechazado")
                 except Exception as e:
                     logger.error(
                         "No se ha encontrado el estado 'Rechazado'")
                     return None
                 action.status = status
                 action.save()
                 logger.warning(f'Transacción {action.tx_id} rechazada')
         time.sleep(5)
Beispiel #2
0
def balance_view(request):
    try:
        bcobj = get_bcobj()
        balance = bcobj.get_balance(request.user.signuser.address)
        balance_to_eth = float(balance)/float(1000000000000000000)
        balance = round(balance_to_eth,2)
    except:
        logger.error("Error al obtener el balance")
        balance =  0
    return JsonResponse({'balance':balance})
Beispiel #3
0
def upload_view(request):
    if request.method == 'POST':
        filename = None
        hash = request.POST.get('hash', None)
        if 'file' in request.FILES:
            filename = request.FILES['file']
        if not filename:
            messages.error(request, "Se debe especificar un documento")
            return render(request, 'upload.html')
        try:
            sc_sign = SCInfo.objects.get(name="Sign")
        except:
            messages.error(request, "No se ha encontrado información del SC")
            return render(request, 'upload.html')
        bc_values = BCValue.objects.first()
        if not bc_values:
            messages.error(request, "No se ha encontrado información sobre la BC")
            return render(request, 'upload.html')
        try:
            status = DocumentStatus.objects.get(name="Pendiente")
        except:
            messages.error(request, "No se ha encontrado el estado 'Pendiente' en la app")
            return render(request, 'upload.html')
        b_hash = bytes.fromhex(hash)
        bcobj = get_bcobj()
        try:
            logger.info("Comprobando existencia del documento en la BC ...")
            exists = bcobj.call(sc_sign.abi, sc_sign.address, "hashDocuments", b_hash)
        except:
            messages.error(request, "Error al comprobar si existe en la BC")
            logger.error(traceback.format_exc())
            return render(request, 'upload.html')

        if exists:
            owner = bcobj.call(sc_sign.abi, sc_sign.address, "hashOwner", b_hash)
            try:
                user = SignUser.objects.get(address=owner)
                messages.warning(request, f"Este documento ya lo ha registrado {user.email} en la BC")
            except:
                messages.warning(request, f"Este documento ya se encuentra registrado en la BC")
            return render(request, 'upload.html')

        tx_id = bcobj.transact(sc_sign, bc_values.gas, bc_values.gas_price, "newDocument", request.user.signuser, b_hash)
        logger.info(f"{filename} Tx -> {tx_id}")
        new_document = Document()
        new_document.hash = hash
        new_document.minter = request.user.signuser
        new_document.name = filename #coge el nombre
        new_document.document = filename #gurada el documento
        new_document.tx_id = tx_id
        new_document.status = status
        new_document.save()
        messages.success(request, "Documento registrado con éxito")
    return render(request, 'upload.html')
Beispiel #4
0
def get_signUser_or_create(email):
    user = get_user_or_create(email)
    try:
        sign_user = SignUser.objects.get(user=user)
    except:
        sign_user = SignUser()
        bcobj = get_bcobj()
        passphrase = "aabbcc11"
        account = bcobj.create_account(passphrase)
        sign_user.user = user
        sign_user.passphrase = passphrase
        sign_user.address = account[0]
        sign_user.private_key = account[1]
        sign_user.save()
    return sign_user
Beispiel #5
0
def add_comment_view(request):
    if request.method == "POST":
        hash = request.POST.get('hash', None)
        if not hash:
            return HttpResponseRedirect(reverse('home'))
        try:
            document = Document.objects.get(hash=hash)
        except:
            messages.error(request, "Documento no encontrado en la aplicación")
            return HttpResponseRedirect(reverse('home'))
        try:
            sc_sign = SCInfo.objects.get(name="Sign")
        except:
            messages.error(request, "No se ha encontrado información del SC")
            return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))
        bc_values = BCValue.objects.first()
        if not bc_values:
            messages.error(request, "No se ha encontrado información sobre la BC")
            return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))
        try:
            status = DocumentStatus.objects.get(name="Pendiente")
        except:
            messages.error(request, "No se ha encontrado el estado 'Pendiente' en la app")
            return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))

        comment = request.POST.get('comment_back', None)
        if not comment:
            return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))

        status_doc = get_doc_status(document, request.user.signuser, comment)
        if not status_doc:
            messages.error(request, "No se ha encontrado el estado del documento")
            return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))

        bcobj = get_bcobj()
        tx_id = bcobj.transact(sc_sign, bc_values.gas, bc_values.gas_price, "addValidationUser", request.user.signuser, hash, request.user.signuser.address, comment)
        logger.info(f"Tx -> {tx_id}")
        new_action = CollaboratorAction()
        new_action.document = document
        new_action.collaborator = request.user.signuser
        new_action.tx_id = tx_id
        new_action.status = status
        new_action.comment = comment
        new_action.save()
        document.status = status_doc
        document.save()
        return HttpResponseRedirect(reverse('doc_details', kwargs={'hash':hash}))
    return HttpResponseRedirect(reverse('home'))
Beispiel #6
0
def document_detail(request, hash):
    try:
        document = Document.objects.get(hash=hash)
        collaborators = CollaboratorDocument.objects.filter(document=document)
        r_address = request.user.signuser.address
        is_collaborator = collaborators.filter(collaborator__address=r_address).exists()
        comments = CollaboratorAction.objects.filter(document=document).exclude(comment="Validated").order_by('-timestamp')
        if r_address != document.minter.address and not is_collaborator:
            return render(request, 'doc_detail.html')
        if r_address == document.minter.address:
            CollaboratorAction.objects.filter(document=document).update(view=True)

        colaborador_document = {}
        last_action_tx = {}
        for c in collaborators:
            msg = get_last_comment(document, c.collaborator)
            tx = get_last_tx_action(document, c.collaborator)
            colaborador_document[c.collaborator.user.email] = msg
            last_action_tx[c.collaborator.user.email] = tx
        context = {
            'document':document,
            'collaborators': collaborators,
            'is_collaborator':is_collaborator,
            'comments':comments,
            'colaborador_document': colaborador_document,
            'last_action_tx':last_action_tx
        }
        if request.method == 'POST':
            collaborator_email = request.POST.get("collaborator_email", '')
            if not collaborator_email:
                logger.info("No se ha especificado el email del colaborador")
                messages.warning(request, "No se ha especificado el email del colaborador")
                return render(request, 'doc_detail.html', context)
            if collaborator_email == request.user.email:
                logger.info("No te puedes añadir de colaborador a ti mismo")
                messages.warning(request, "No te puedes añadir de colaborador a ti mismo")
                return render(request, 'doc_detail.html', context)
            status = None
            if document.status.name in ["Confirmado" ,"Rechazado"]:
                try:
                    status = DocumentStatus.objects.get(name="Con colaboradores")
                except:
                    messages.warning(request, "No se ha encontrado el estado del documento")
                    return render(request, 'doc_detail.html', context)

            sign_user = get_signUser_or_create(collaborator_email)
            sc_sign = SCInfo.objects.get(name="Sign")
            bc_values = BCValue.objects.first()
            if not bc_values:
                messages.error(request, "No se ha encontrado información sobre la BC")
                return render(request, 'doc_detail.html', context)
            b_hash = bytes.fromhex(hash)
            bcobj = get_bcobj()
            try:
                logger.info("Comprobando existencia del colaborador en el documento en la BC ...")
                exists = bcobj.call(sc_sign.abi, sc_sign.address, "hashValidatorUser", b_hash, sign_user.address)
            except:
                messages.warning(request, "Error al comprobar si existe este colaborador en la BC")
                logger.error(traceback.format_exc())
                return render(request, 'doc_detail.html', context)
            if exists:
                messages.warning(request, f"Este colaborador ya se encuentra asociado a este documento")
                return render(request, 'doc_detail.html', context)
            tx_id = bcobj.transact(sc_sign, bc_values.gas, bc_values.gas_price, "addValidatorUser", request.user.signuser, b_hash, sign_user.address)
            logger.info(f"Added Collaborator Tx -> {tx_id}")
            validated_email(sign_user, request.user)
            new_collaborator = CollaboratorDocument()
            new_collaborator.document = document
            new_collaborator.collaborator = sign_user
            new_collaborator.tx_id = tx_id
            new_collaborator.save()
            if status:
                document.status = status
                document.save()
            messages.success(request, "colaborador añadido con éxito")
        return render(request, 'doc_detail.html', context)
    except Document.DoesNotExist:
        messages.error(request, "No se ha encontrado este hash en el sistema")
        return render(request, 'doc_detail.html')
    except SCInfo.DoesNotExist:
        messages.error(request, "No se ha encontrado información del SC")
        return render(request, 'doc_detail.html')
    except:
        messages.error(request, "Ha ocurrido un error, contacte con el administrador")
        logger.error(traceback.format_exc())
        return render(request, 'doc_detail.html')