2022-01-05 05:03:03 +03:00
|
|
|
from rest_framework import status, serializers
|
2022-01-05 03:13:08 +03:00
|
|
|
from rest_framework.generics import CreateAPIView, ListAPIView
|
2022-01-02 01:34:23 +03:00
|
|
|
from rest_framework.views import APIView
|
2022-01-05 03:13:08 +03:00
|
|
|
from rest_framework import viewsets
|
2022-01-02 01:34:23 +03:00
|
|
|
from rest_framework.response import Response
|
2022-01-05 03:13:08 +03:00
|
|
|
|
2022-01-03 04:31:28 +03:00
|
|
|
from django.contrib.auth import authenticate, login, logout
|
2022-01-02 15:59:48 +03:00
|
|
|
from django.contrib.auth.models import User
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
from .serializers import ListOrderSerializer, MakeOrderSerializer, UpdateOrderSerializer
|
2022-01-06 19:54:37 +03:00
|
|
|
from .models import Order
|
2022-01-06 23:33:40 +03:00
|
|
|
from .logics import EXP_MAKER_BOND_INVOICE, Logics
|
2022-01-02 01:13:27 +03:00
|
|
|
|
2022-01-02 18:19:49 +03:00
|
|
|
from .nick_generator.nick_generator import NickGenerator
|
|
|
|
from robohash import Robohash
|
2022-01-02 20:04:51 +03:00
|
|
|
from scipy.stats import entropy
|
|
|
|
from math import log2
|
|
|
|
import numpy as np
|
|
|
|
import hashlib
|
|
|
|
from pathlib import Path
|
2022-01-03 12:06:51 +03:00
|
|
|
from datetime import timedelta
|
|
|
|
from django.utils import timezone
|
2022-01-02 18:19:49 +03:00
|
|
|
|
2022-01-06 19:54:37 +03:00
|
|
|
from decouple import config
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
EXP_MAKER_BOND_INVOICE = int(config('EXP_MAKER_BOND_INVOICE'))
|
2022-01-04 13:21:45 +03:00
|
|
|
|
2022-01-03 22:13:39 +03:00
|
|
|
avatar_path = Path('frontend/static/assets/avatars')
|
|
|
|
avatar_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
2022-01-02 01:13:27 +03:00
|
|
|
# Create your views here.
|
2022-01-02 01:34:23 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
class OrderMakerView(CreateAPIView):
|
2022-01-02 01:34:23 +03:00
|
|
|
serializer_class = MakeOrderSerializer
|
|
|
|
|
2022-01-02 02:06:47 +03:00
|
|
|
def post(self,request):
|
2022-01-02 01:34:23 +03:00
|
|
|
serializer = self.serializer_class(data=request.data)
|
2022-01-02 15:59:48 +03:00
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
if not serializer.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
type = serializer.data.get('type')
|
|
|
|
currency = serializer.data.get('currency')
|
|
|
|
amount = serializer.data.get('amount')
|
|
|
|
payment_method = serializer.data.get('payment_method')
|
|
|
|
premium = serializer.data.get('premium')
|
|
|
|
satoshis = serializer.data.get('satoshis')
|
|
|
|
is_explicit = serializer.data.get('is_explicit')
|
|
|
|
|
|
|
|
valid, context = Logics.validate_already_maker_or_taker(request.user)
|
|
|
|
if not valid: return Response(context, status=status.HTTP_409_CONFLICT)
|
|
|
|
|
|
|
|
# Creates a new order
|
|
|
|
order = Order(
|
|
|
|
type=type,
|
|
|
|
currency=currency,
|
|
|
|
amount=amount,
|
|
|
|
payment_method=payment_method,
|
|
|
|
premium=premium,
|
|
|
|
satoshis=satoshis,
|
|
|
|
is_explicit=is_explicit,
|
|
|
|
expires_at=timezone.now()+timedelta(minutes=EXP_MAKER_BOND_INVOICE),
|
|
|
|
maker=request.user)
|
|
|
|
|
|
|
|
order.last_satoshis = order.t0_satoshis = Logics.satoshis_now(order) # TODO move to Order class method when new instance is created!
|
|
|
|
|
|
|
|
order.save()
|
2022-01-05 03:13:08 +03:00
|
|
|
return Response(ListOrderSerializer(order).data, status=status.HTTP_201_CREATED)
|
2022-01-02 15:59:48 +03:00
|
|
|
|
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
class OrderView(viewsets.ViewSet):
|
2022-01-06 23:33:40 +03:00
|
|
|
serializer_class = UpdateOrderSerializer
|
2022-01-02 15:59:48 +03:00
|
|
|
lookup_url_kwarg = 'order_id'
|
|
|
|
|
|
|
|
def get(self, request, format=None):
|
|
|
|
order_id = request.GET.get(self.lookup_url_kwarg)
|
|
|
|
|
2022-01-06 16:55:47 +03:00
|
|
|
if order_id == None:
|
|
|
|
return Response({'Bad Request':'Order ID parameter not found in request'}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
order = Order.objects.filter(id=order_id)
|
|
|
|
|
|
|
|
# check if exactly one order is found in the db
|
|
|
|
if len(order) == 1 :
|
|
|
|
order = order[0]
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 1) If order expired
|
2022-01-06 16:55:47 +03:00
|
|
|
if order.status == Order.Status.EXP:
|
|
|
|
return Response({'bad_request':'This order has expired'},status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
data = ListOrderSerializer(order).data
|
|
|
|
|
|
|
|
# Add booleans if user is maker, taker, partipant, buyer or seller
|
|
|
|
data['is_maker'] = order.maker == request.user
|
|
|
|
data['is_taker'] = order.taker == request.user
|
|
|
|
data['is_participant'] = data['is_maker'] or data['is_taker']
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 2) If not a participant and order is not public, forbid.
|
2022-01-06 16:55:47 +03:00
|
|
|
if not data['is_participant'] and order.status != Order.Status.PUB:
|
|
|
|
return Response({'bad_request':'Not allowed to see this order'},status.HTTP_403_FORBIDDEN)
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 3) Non participants can view details (but only if PUB)
|
2022-01-06 16:55:47 +03:00
|
|
|
elif not data['is_participant'] and order.status != Order.Status.PUB:
|
|
|
|
return Response(data, status=status.HTTP_200_OK)
|
|
|
|
|
|
|
|
# For participants add position side, nicks and status as message
|
|
|
|
data['is_buyer'] = Logics.is_buyer(order,request.user)
|
|
|
|
data['is_seller'] = Logics.is_seller(order,request.user)
|
|
|
|
data['maker_nick'] = str(order.maker)
|
|
|
|
data['taker_nick'] = str(order.taker)
|
|
|
|
data['status_message'] = Order.Status(order.status).label
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 4) If status is 'waiting for maker bond', reply with a MAKER HODL invoice.
|
2022-01-06 16:55:47 +03:00
|
|
|
if order.status == Order.Status.WFB and data['is_maker']:
|
2022-01-06 19:20:04 +03:00
|
|
|
valid, context = Logics.gen_maker_hodl_invoice(order, request.user)
|
2022-01-06 23:33:40 +03:00
|
|
|
data = {**data, **context} if valid else Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# 5) If status is 'Public' and user is taker/buyer, reply with a TAKER HODL invoice.
|
|
|
|
elif order.status == Order.Status.PUB and data['is_taker'] and data['is_buyer']:
|
|
|
|
valid, context = Logics.gen_takerbuyer_hodl_invoice(order, request.user)
|
|
|
|
data = {**data, **context} if valid else Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# 6) If status is 'Public' and user is taker/seller, reply with a ESCROW HODL invoice.
|
|
|
|
elif order.status == Order.Status.PUB and data['is_taker'] and data['is_seller']:
|
|
|
|
valid, context = Logics.gen_seller_hodl_invoice(order, request.user)
|
|
|
|
data = {**data, **context} if valid else Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# 7) If status is 'WF2/WTC' and user is maker/seller, reply with an ESCROW HODL invoice.
|
|
|
|
elif (order.status == Order.Status.WF2 or order.status == Order.Status.WF2) and data['is_maker'] and data['is_seller']:
|
|
|
|
valid, context = Logics.gen_seller_hodl_invoice(order, request.user)
|
|
|
|
data = {**data, **context} if valid else Response(context, status=status.HTTP_400_BAD_REQUEST)
|
2022-01-06 16:55:47 +03:00
|
|
|
|
|
|
|
return Response(data, status=status.HTTP_200_OK)
|
|
|
|
return Response({'Order Not Found':'Invalid Order Id'},status=status.HTTP_404_NOT_FOUND)
|
2022-01-02 15:59:48 +03:00
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
def take_update_confirm_dispute_cancel(self, request, format=None):
|
2022-01-05 03:13:08 +03:00
|
|
|
order_id = request.GET.get(self.lookup_url_kwarg)
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
serializer = UpdateOrderSerializer(data=request.data)
|
|
|
|
if not serializer.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
order = Order.objects.get(id=order_id)
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# action is either 1)'take', 2)'confirm', 3)'cancel', 4)'dispute' , 5)'update' (invoice) 6)'rate' (counterparty)
|
|
|
|
action = serializer.data.get('action')
|
|
|
|
invoice = serializer.data.get('invoice')
|
|
|
|
rating = serializer.data.get('rating')
|
2022-01-05 03:13:08 +03:00
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 1) If action is take, it is be taker request!
|
|
|
|
if action == 'take':
|
|
|
|
if order.status == Order.Status.PUB:
|
|
|
|
valid, context = Logics.validate_already_maker_or_taker(request.user)
|
|
|
|
if not valid: return Response(context, status=status.HTTP_409_CONFLICT)
|
|
|
|
|
|
|
|
Logics.take(order, request.user)
|
|
|
|
else: Response({'bad_request':'This order is not public anymore.'}, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# 2) If action is update (invoice)
|
|
|
|
elif action == 'update' and invoice:
|
|
|
|
updated, context = Logics.update_invoice(order,request.user,invoice)
|
|
|
|
if not updated: return Response(context,status.HTTP_400_BAD_REQUEST)
|
2022-01-06 15:32:17 +03:00
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
# 3) If action is cancel
|
|
|
|
elif action == 'cancel':
|
|
|
|
pass
|
|
|
|
|
|
|
|
# 4) If action is confirm
|
|
|
|
elif action == 'confirm':
|
|
|
|
pass
|
|
|
|
|
|
|
|
# 5) If action is dispute
|
|
|
|
elif action == 'dispute':
|
|
|
|
pass
|
|
|
|
|
|
|
|
# 6) If action is dispute
|
|
|
|
elif action == 'rate' and rating:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# If nothing... something else is going on. Probably not allowed!
|
2022-01-05 03:13:08 +03:00
|
|
|
else:
|
|
|
|
return Response({'bad_request':'Not allowed'})
|
|
|
|
|
|
|
|
return self.get(request)
|
|
|
|
|
|
|
|
class UserView(APIView):
|
2022-01-02 18:19:49 +03:00
|
|
|
lookup_url_kwarg = 'token'
|
|
|
|
NickGen = NickGenerator(
|
|
|
|
lang='English',
|
|
|
|
use_adv=False,
|
|
|
|
use_adj=True,
|
|
|
|
use_noun=True,
|
|
|
|
max_num=999)
|
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
# Probably should be turned into a post method
|
2022-01-03 17:27:25 +03:00
|
|
|
def get(self,request, format=None):
|
2022-01-02 18:19:49 +03:00
|
|
|
'''
|
2022-01-02 20:04:51 +03:00
|
|
|
Get a new user derived from a high entropy token
|
2022-01-02 18:19:49 +03:00
|
|
|
|
|
|
|
- Request has a high-entropy token,
|
|
|
|
- Generates new nickname and avatar.
|
|
|
|
- Creates login credentials (new User object)
|
|
|
|
Response with Avatar and Nickname.
|
|
|
|
'''
|
2022-01-02 20:04:51 +03:00
|
|
|
token = request.GET.get(self.lookup_url_kwarg)
|
|
|
|
|
|
|
|
# Compute token entropy
|
|
|
|
value, counts = np.unique(list(token), return_counts=True)
|
|
|
|
shannon_entropy = entropy(counts, base=62)
|
|
|
|
bits_entropy = log2(len(value)**len(token))
|
2022-01-05 15:18:54 +03:00
|
|
|
# Payload
|
2022-01-02 20:04:51 +03:00
|
|
|
context = {'token_shannon_entropy': shannon_entropy, 'token_bits_entropy': bits_entropy}
|
|
|
|
|
|
|
|
# Deny user gen if entropy below 128 bits or 0.7 shannon heterogeneity
|
|
|
|
if bits_entropy < 128 or shannon_entropy < 0.7:
|
2022-01-02 21:27:40 +03:00
|
|
|
context['bad_request'] = 'The token does not have enough entropy'
|
2022-01-02 20:04:51 +03:00
|
|
|
return Response(context, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# Hashes the token, only 1 iteration. Maybe more is better.
|
|
|
|
hash = hashlib.sha256(str.encode(token)).hexdigest()
|
|
|
|
|
2022-01-05 15:18:54 +03:00
|
|
|
# Generate nickname
|
2022-01-02 20:04:51 +03:00
|
|
|
nickname = self.NickGen.short_from_SHA256(hash, max_length=18)[0]
|
|
|
|
context['nickname'] = nickname
|
|
|
|
|
2022-01-05 15:18:54 +03:00
|
|
|
# Generate avatar
|
2022-01-02 20:04:51 +03:00
|
|
|
rh = Robohash(hash)
|
2022-01-04 16:47:37 +03:00
|
|
|
rh.assemble(roboset='set1', bgset='any')# for backgrounds ON
|
2022-01-04 01:52:46 +03:00
|
|
|
|
2022-01-04 16:47:37 +03:00
|
|
|
# Does not replace image if existing (avoid re-avatar in case of nick collusion)
|
2022-01-02 20:04:51 +03:00
|
|
|
|
2022-01-04 16:47:37 +03:00
|
|
|
image_path = avatar_path.joinpath(nickname+".png")
|
|
|
|
if not image_path.exists():
|
|
|
|
with open(image_path, "wb") as f:
|
|
|
|
rh.img.save(f, format="png")
|
|
|
|
|
|
|
|
# Create new credentials and logsin if nickname is new
|
2022-01-02 20:04:51 +03:00
|
|
|
if len(User.objects.filter(username=nickname)) == 0:
|
|
|
|
User.objects.create_user(username=nickname, password=token, is_staff=False)
|
2022-01-03 12:06:51 +03:00
|
|
|
user = authenticate(request, username=nickname, password=token)
|
2022-01-04 16:47:37 +03:00
|
|
|
user.profile.avatar = str(image_path)[9:] # removes frontend/ from url (ugly, to be fixed)
|
2022-01-03 04:31:28 +03:00
|
|
|
login(request, user)
|
2022-01-03 12:06:51 +03:00
|
|
|
return Response(context, status=status.HTTP_201_CREATED)
|
2022-01-02 20:04:51 +03:00
|
|
|
|
2022-01-03 12:06:51 +03:00
|
|
|
else:
|
|
|
|
user = authenticate(request, username=nickname, password=token)
|
|
|
|
if user is not None:
|
|
|
|
login(request, user)
|
|
|
|
# Sends the welcome back message, only if created +30 mins ago
|
2022-01-03 17:27:25 +03:00
|
|
|
if request.user.date_joined < (timezone.now()-timedelta(minutes=30)):
|
2022-01-03 12:06:51 +03:00
|
|
|
context['found'] = 'We found your Robosat. Welcome back!'
|
|
|
|
return Response(context, status=status.HTTP_202_ACCEPTED)
|
|
|
|
else:
|
2022-01-04 16:47:37 +03:00
|
|
|
# It is unlikely, but maybe the nickname is taken (1 in 20 Billion change)
|
2022-01-03 12:06:51 +03:00
|
|
|
context['found'] = 'Bad luck, this nickname is taken'
|
|
|
|
context['bad_request'] = 'Enter a different token'
|
|
|
|
return Response(context, status=status.HTTP_403_FORBIDDEN)
|
|
|
|
|
2022-01-03 04:31:28 +03:00
|
|
|
def delete(self,request):
|
|
|
|
user = User.objects.get(id = request.user.id)
|
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
# TO DO. Pressing "give me another" deletes the logged in user
|
2022-01-03 12:06:51 +03:00
|
|
|
# However it might be a long time recovered user
|
|
|
|
# Only delete if user live is < 5 minutes
|
|
|
|
|
2022-01-04 16:47:37 +03:00
|
|
|
# TODO check if user exists AND it is not a maker or taker!
|
2022-01-03 04:31:28 +03:00
|
|
|
if user is not None:
|
|
|
|
logout(request)
|
|
|
|
user.delete()
|
2022-01-03 22:13:39 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
return Response({'user_deleted':'User deleted permanently'},status=status.HTTP_302_FOUND)
|
2022-01-03 04:31:28 +03:00
|
|
|
|
|
|
|
return Response(status=status.HTTP_403_FORBIDDEN)
|
2022-01-02 18:19:49 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
class BookView(ListAPIView):
|
|
|
|
serializer_class = ListOrderSerializer
|
2022-01-03 17:27:25 +03:00
|
|
|
|
|
|
|
def get(self,request, format=None):
|
2022-01-03 22:13:39 +03:00
|
|
|
currency = request.GET.get('currency')
|
2022-01-04 18:58:10 +03:00
|
|
|
type = request.GET.get('type')
|
2022-01-05 03:13:08 +03:00
|
|
|
queryset = Order.objects.filter(currency=currency, type=type, status=int(Order.Status.PUB))
|
2022-01-03 17:39:59 +03:00
|
|
|
if len(queryset)== 0:
|
2022-01-03 22:13:39 +03:00
|
|
|
return Response({'not_found':'No orders found, be the first to make one'}, status=status.HTTP_404_NOT_FOUND)
|
2022-01-03 17:39:59 +03:00
|
|
|
|
2022-01-04 18:58:10 +03:00
|
|
|
queryset = queryset.order_by('created_at')
|
2022-01-03 22:13:39 +03:00
|
|
|
book_data = []
|
|
|
|
for order in queryset:
|
2022-01-05 03:13:08 +03:00
|
|
|
data = ListOrderSerializer(order).data
|
2022-01-03 17:27:25 +03:00
|
|
|
user = User.objects.filter(id=data['maker'])
|
|
|
|
if len(user) == 1:
|
|
|
|
data['maker_nick'] = user[0].username
|
2022-01-06 23:33:40 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
# Non participants should not see the status or who is the taker
|
|
|
|
for key in ('status','taker'):
|
|
|
|
del data[key]
|
2022-01-03 22:13:39 +03:00
|
|
|
book_data.append(data)
|
2022-01-03 17:39:59 +03:00
|
|
|
|
|
|
|
return Response(book_data, status=status.HTTP_200_OK)
|
2022-01-03 17:27:25 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|