2022-01-10 00:54:13 +03:00
|
|
|
from re import T
|
2022-01-11 04:36:34 +03:00
|
|
|
from django.db.models import query
|
2022-01-07 00:36:22 +03:00
|
|
|
from rest_framework import status, viewsets
|
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
|
|
|
|
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-16 19:06:53 +03:00
|
|
|
from .models import LNPayment, MarketTick, Order, Currency
|
2022-01-07 00:36:22 +03:00
|
|
|
from .logics import Logics
|
2022-01-18 21:24:45 +03:00
|
|
|
from .utils import get_lnd_version, get_commit_robosats, compute_premium_percentile
|
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-11 04:36:34 +03:00
|
|
|
from datetime import timedelta, datetime
|
2022-01-03 12:06:51 +03:00
|
|
|
from django.utils import timezone
|
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-07 21:22:52 +03:00
|
|
|
FEE = float(config('FEE'))
|
2022-01-24 00:12:30 +03:00
|
|
|
RETRY_TIME = int(config('RETRY_TIME'))
|
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-07 21:22:52 +03:00
|
|
|
class MakerView(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)
|
2022-01-07 00:36:22 +03:00
|
|
|
if not valid: return Response(context, status.HTTP_409_CONFLICT)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
|
|
|
# Creates a new order
|
|
|
|
order = Order(
|
|
|
|
type=type,
|
2022-01-16 19:06:53 +03:00
|
|
|
currency=Currency.objects.get(id=currency),
|
2022-01-06 23:33:40 +03:00
|
|
|
amount=amount,
|
|
|
|
payment_method=payment_method,
|
|
|
|
premium=premium,
|
|
|
|
satoshis=satoshis,
|
|
|
|
is_explicit=is_explicit,
|
2022-01-11 23:49:53 +03:00
|
|
|
expires_at=timezone.now()+timedelta(seconds=EXP_MAKER_BOND_INVOICE), # TODO Move to class method
|
2022-01-06 23:33:40 +03:00
|
|
|
maker=request.user)
|
2022-01-07 00:36:22 +03:00
|
|
|
|
|
|
|
# TODO move to Order class method when new instance is created!
|
|
|
|
order.last_satoshis = order.t0_satoshis = Logics.satoshis_now(order)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
2022-01-07 00:36:22 +03:00
|
|
|
valid, context = Logics.validate_order_size(order)
|
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
|
|
|
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):
|
2022-01-07 14:31:33 +03:00
|
|
|
'''
|
|
|
|
Full trade pipeline takes place while looking/refreshing the order page.
|
|
|
|
'''
|
2022-01-02 15:59:48 +03:00
|
|
|
order_id = request.GET.get(self.lookup_url_kwarg)
|
|
|
|
|
2022-01-06 16:55:47 +03:00
|
|
|
if order_id == None:
|
2022-01-07 14:31:33 +03:00
|
|
|
return Response({'bad_request':'Order ID parameter not found in request'}, status=status.HTTP_400_BAD_REQUEST)
|
2022-01-06 16:55:47 +03:00
|
|
|
|
|
|
|
order = Order.objects.filter(id=order_id)
|
|
|
|
|
|
|
|
# check if exactly one order is found in the db
|
2022-01-07 14:31:33 +03:00
|
|
|
if len(order) != 1 :
|
|
|
|
return Response({'bad_request':'Invalid Order Id'}, status.HTTP_404_NOT_FOUND)
|
|
|
|
|
|
|
|
# This is our order.
|
|
|
|
order = order[0]
|
|
|
|
|
2022-01-11 23:49:53 +03:00
|
|
|
# 2) If order has been cancelled
|
2022-01-07 14:31:33 +03:00
|
|
|
if order.status == Order.Status.UCA:
|
|
|
|
return Response({'bad_request':'This order has been cancelled by the maker'},status.HTTP_400_BAD_REQUEST)
|
|
|
|
if order.status == Order.Status.CCA:
|
|
|
|
return Response({'bad_request':'This order has been cancelled collaborativelly'},status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
data = ListOrderSerializer(order).data
|
2022-01-17 00:54:42 +03:00
|
|
|
data['total_secs_exp'] = Order.t_to_expire[order.status]
|
2022-01-07 14:31:33 +03:00
|
|
|
|
2022-01-11 23:49:53 +03:00
|
|
|
# if user is under a limit (penalty), inform him.
|
2022-01-10 15:10:32 +03:00
|
|
|
is_penalized, time_out = Logics.is_penalized(request.user)
|
|
|
|
if is_penalized:
|
|
|
|
data['penalty'] = time_out
|
|
|
|
|
2022-01-07 14:31:33 +03:00
|
|
|
# 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-14 15:00:53 +03:00
|
|
|
# 3.a) If not a participant and order is not public, forbid.
|
2022-01-07 14:31:33 +03:00
|
|
|
if not data['is_participant'] and order.status != Order.Status.PUB:
|
|
|
|
return Response({'bad_request':'You are not allowed to see this order'},status.HTTP_403_FORBIDDEN)
|
|
|
|
|
2022-01-14 17:19:25 +03:00
|
|
|
# 3.b If order is between public and WF2
|
2022-01-18 03:50:54 +03:00
|
|
|
if order.status >= Order.Status.PUB and order.status < Order.Status.WF2:
|
2022-01-14 15:00:53 +03:00
|
|
|
data['price_now'], data['premium_now'] = Logics.price_and_premium_now(order)
|
|
|
|
|
|
|
|
# 3. c) If maker and Public, add num robots in book, premium percentile and num similar orders.
|
2022-01-14 17:19:25 +03:00
|
|
|
if data['is_maker'] and order.status == Order.Status.PUB:
|
2022-01-14 15:00:53 +03:00
|
|
|
data['robots_in_book'] = None # TODO
|
2022-01-18 21:24:45 +03:00
|
|
|
data['premium_percentile'] = compute_premium_percentile(order)
|
2022-01-14 15:00:53 +03:00
|
|
|
data['num_similar_orders'] = len(Order.objects.filter(currency=order.currency, status=Order.Status.PUB))
|
|
|
|
|
2022-01-07 14:31:33 +03:00
|
|
|
# 4) Non participants can view details (but only if PUB)
|
|
|
|
elif not data['is_participant'] and order.status != Order.Status.PUB:
|
|
|
|
return Response(data, status=status.HTTP_200_OK)
|
|
|
|
|
2022-01-18 03:50:54 +03:00
|
|
|
# For participants add positions, nicks and status as a message and hold invoices status
|
2022-01-07 14:31:33 +03:00
|
|
|
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)
|
2022-01-07 21:22:52 +03:00
|
|
|
data['status_message'] = Order.Status(order.status).label
|
|
|
|
data['is_fiat_sent'] = order.is_fiat_sent
|
|
|
|
data['is_disputed'] = order.is_disputed
|
2022-01-14 15:00:53 +03:00
|
|
|
data['ur_nick'] = request.user.username
|
2022-01-07 21:22:52 +03:00
|
|
|
|
2022-01-18 03:50:54 +03:00
|
|
|
# Add whether hold invoices are LOCKED (ACCEPTED)
|
|
|
|
# Is there a maker bond? If so, True if locked, False otherwise
|
|
|
|
if order.maker_bond:
|
|
|
|
data['maker_locked'] = order.maker_bond.status == LNPayment.Status.LOCKED
|
|
|
|
else:
|
|
|
|
data['maker_locked'] = False
|
|
|
|
|
|
|
|
# Is there a taker bond? If so, True if locked, False otherwise
|
|
|
|
if order.taker_bond:
|
|
|
|
data['taker_locked'] = order.taker_bond.status == LNPayment.Status.LOCKED
|
|
|
|
else:
|
|
|
|
data['taker_locked'] = False
|
|
|
|
|
|
|
|
# Is there an escrow? If so, True if locked, False otherwise
|
|
|
|
if order.trade_escrow:
|
|
|
|
data['escrow_locked'] = order.trade_escrow.status == LNPayment.Status.LOCKED
|
|
|
|
else:
|
|
|
|
data['escrow_locked'] = False
|
|
|
|
|
2022-01-11 23:49:53 +03:00
|
|
|
# If both bonds are locked, participants can see the final trade amount in sats.
|
2022-01-18 18:45:04 +03:00
|
|
|
if order.taker_bond:
|
|
|
|
if order.maker_bond.status == order.taker_bond.status == LNPayment.Status.LOCKED:
|
|
|
|
# Seller sees the amount he sends
|
|
|
|
if data['is_seller']:
|
|
|
|
data['trade_satoshis'] = order.last_satoshis
|
|
|
|
# Buyer sees the amount he receives
|
|
|
|
elif data['is_buyer']:
|
|
|
|
data['trade_satoshis'] = Logics.buyer_invoice_amount(order, request.user)[1]['invoice_amount']
|
2022-01-07 14:31:33 +03:00
|
|
|
|
2022-01-09 23:05:19 +03:00
|
|
|
# 5) If status is 'waiting for maker bond' and user is MAKER, reply with a MAKER hold invoice.
|
2022-01-07 14:31:33 +03:00
|
|
|
if order.status == Order.Status.WFB and data['is_maker']:
|
2022-01-09 23:05:19 +03:00
|
|
|
valid, context = Logics.gen_maker_hold_invoice(order, request.user)
|
2022-01-07 14:31:33 +03:00
|
|
|
if valid:
|
|
|
|
data = {**data, **context}
|
|
|
|
else:
|
|
|
|
return Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2022-01-09 23:05:19 +03:00
|
|
|
# 6) If status is 'waiting for taker bond' and user is TAKER, reply with a TAKER hold invoice.
|
2022-01-07 14:31:33 +03:00
|
|
|
elif order.status == Order.Status.TAK and data['is_taker']:
|
2022-01-09 23:05:19 +03:00
|
|
|
valid, context = Logics.gen_taker_hold_invoice(order, request.user)
|
2022-01-07 14:31:33 +03:00
|
|
|
if valid:
|
|
|
|
data = {**data, **context}
|
|
|
|
else:
|
|
|
|
return Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2022-01-08 20:19:30 +03:00
|
|
|
# 7 a. ) If seller and status is 'WF2' or 'WFE'
|
|
|
|
elif data['is_seller'] and (order.status == Order.Status.WF2 or order.status == Order.Status.WFE):
|
2022-01-09 23:05:19 +03:00
|
|
|
# If the two bonds are locked, reply with an ESCROW hold invoice.
|
2022-01-07 14:31:33 +03:00
|
|
|
if order.maker_bond.status == order.taker_bond.status == LNPayment.Status.LOCKED:
|
2022-01-09 23:05:19 +03:00
|
|
|
valid, context = Logics.gen_escrow_hold_invoice(order, request.user)
|
2022-01-08 20:19:30 +03:00
|
|
|
if valid:
|
|
|
|
data = {**data, **context}
|
|
|
|
else:
|
|
|
|
return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-07 14:31:33 +03:00
|
|
|
|
2022-01-08 20:19:30 +03:00
|
|
|
# 7.b) If user is Buyer and status is 'WF2' or 'WFI'
|
|
|
|
elif data['is_buyer'] and (order.status == Order.Status.WF2 or order.status == Order.Status.WFI):
|
2022-01-07 14:31:33 +03:00
|
|
|
|
2022-01-08 20:19:30 +03:00
|
|
|
# If the two bonds are locked, reply with an AMOUNT so he can send the buyer invoice.
|
|
|
|
if order.maker_bond.status == order.taker_bond.status == LNPayment.Status.LOCKED:
|
|
|
|
valid, context = Logics.buyer_invoice_amount(order, request.user)
|
|
|
|
if valid:
|
|
|
|
data = {**data, **context}
|
|
|
|
else:
|
|
|
|
return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-07 14:31:33 +03:00
|
|
|
|
2022-01-11 23:49:53 +03:00
|
|
|
# 8) If status is 'CHA' or 'FSE' and all HTLCS are in LOCKED
|
2022-01-23 22:02:25 +03:00
|
|
|
elif order.status in [Order.Status.WFI, Order.Status.CHA, Order.Status.FSE]:
|
2022-01-11 23:49:53 +03:00
|
|
|
# If all bonds are locked.
|
2022-01-07 14:31:33 +03:00
|
|
|
if order.maker_bond.status == order.taker_bond.status == order.trade_escrow.status == LNPayment.Status.LOCKED:
|
2022-01-23 22:02:25 +03:00
|
|
|
# add whether a collaborative cancel is pending or has been asked
|
|
|
|
if (data['is_maker'] and order.taker_asked_cancel) or (data['is_taker'] and order.maker_asked_cancel):
|
|
|
|
print('PENDING')
|
|
|
|
data['pending_cancel'] = True
|
|
|
|
elif (data['is_maker'] and order.maker_asked_cancel) or (data['is_taker'] and order.taker_asked_cancel):
|
|
|
|
print('ASKED')
|
|
|
|
data['asked_for_cancel'] = True
|
|
|
|
else:
|
|
|
|
data['asked_for_cancel'] = False
|
2022-01-10 00:24:48 +03:00
|
|
|
|
2022-01-23 02:05:03 +03:00
|
|
|
# 9) If status is 'DIS' and all HTLCS are in LOCKED
|
2022-01-23 22:02:25 +03:00
|
|
|
elif order.status == Order.Status.DIS:
|
2022-01-23 02:05:03 +03:00
|
|
|
|
|
|
|
# add whether the dispute statement has been received
|
|
|
|
if data['is_maker']:
|
|
|
|
data['statement_submitted'] = (order.maker_statement != None and order.maker_statement != "")
|
|
|
|
elif data['is_taker']:
|
|
|
|
data['statement_submitted'] = (order.taker_statement != None and order.maker_statement != "")
|
2022-01-24 00:12:30 +03:00
|
|
|
|
|
|
|
# 9) If status is 'Failed routing', reply with retry amounts, time of next retry and ask for invoice at third.
|
|
|
|
elif order.status == Order.Status.FAI:
|
|
|
|
data['retries'] = order.buyer_invoice.routing_attempts
|
|
|
|
data['next_retry_time'] = order.buyer_invoice.last_routing_time + timedelta(minutes=RETRY_TIME)
|
2022-01-25 01:53:55 +03:00
|
|
|
|
|
|
|
if order.buyer_invoice.status == LNPayment.Status.EXPIRE:
|
|
|
|
data['invoice_expired'] = True
|
|
|
|
# Add invoice amount once again if invoice was expired.
|
|
|
|
data['invoice_amount'] = int(order.last_satoshis * (1-FEE))
|
2022-01-07 21:22:52 +03:00
|
|
|
|
2022-01-07 14:31:33 +03:00
|
|
|
return Response(data, status.HTTP_200_OK)
|
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-07 01:39:59 +03:00
|
|
|
'''
|
2022-01-15 17:22:07 +03:00
|
|
|
Here takes place all of the updates to the order object.
|
2022-01-07 01:39:59 +03:00
|
|
|
That is: take, confim, cancel, dispute, update_invoice or rate.
|
|
|
|
'''
|
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-17 00:54:42 +03:00
|
|
|
# action is either 1)'take', 2)'confirm', 3)'cancel', 4)'dispute' , 5)'update_invoice'
|
|
|
|
# 6)'submit_statement' (in dispute), 7)'rate' (counterparty)
|
2022-01-06 23:33:40 +03:00
|
|
|
action = serializer.data.get('action')
|
|
|
|
invoice = serializer.data.get('invoice')
|
2022-01-17 00:54:42 +03:00
|
|
|
statement = serializer.data.get('statement')
|
2022-01-06 23:33:40 +03:00
|
|
|
rating = serializer.data.get('rating')
|
2022-01-17 00:54:42 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
|
2022-01-11 23:49:53 +03:00
|
|
|
# 1) If action is take, it is a taker request!
|
2022-01-06 23:33:40 +03:00
|
|
|
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)
|
2022-01-10 15:10:32 +03:00
|
|
|
valid, context = Logics.take(order, request.user)
|
|
|
|
if not valid: return Response(context, status=status.HTTP_403_FORBIDDEN)
|
|
|
|
|
2022-01-14 17:19:25 +03:00
|
|
|
return self.get(request)
|
|
|
|
|
2022-01-06 23:33:40 +03:00
|
|
|
else: Response({'bad_request':'This order is not public anymore.'}, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2022-01-07 21:22:52 +03:00
|
|
|
# Any other action is only allowed if the user is a participant
|
|
|
|
if not (order.maker == request.user or order.taker == request.user):
|
|
|
|
return Response({'bad_request':'You are not a participant in this order'}, status.HTTP_403_FORBIDDEN)
|
|
|
|
|
|
|
|
# 2) If action is 'update invoice'
|
|
|
|
if action == 'update_invoice' and invoice:
|
2022-01-07 01:39:59 +03:00
|
|
|
valid, context = Logics.update_invoice(order,request.user,invoice)
|
2022-01-07 21:22:52 +03:00
|
|
|
if not valid: 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':
|
2022-01-07 14:31:33 +03:00
|
|
|
valid, context = Logics.cancel_order(order,request.user)
|
2022-01-07 21:22:52 +03:00
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
|
|
|
# 4) If action is confirm
|
|
|
|
elif action == 'confirm':
|
2022-01-07 21:22:52 +03:00
|
|
|
valid, context = Logics.confirm_fiat(order,request.user)
|
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
|
|
|
# 5) If action is dispute
|
|
|
|
elif action == 'dispute':
|
2022-01-17 00:54:42 +03:00
|
|
|
valid, context = Logics.open_dispute(order,request.user)
|
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
elif action == 'submit_statement':
|
|
|
|
valid, context = Logics.dispute_statement(order,request.user, statement)
|
2022-01-07 21:22:52 +03:00
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
2022-01-07 21:22:52 +03:00
|
|
|
# 6) If action is rate
|
2022-01-06 23:33:40 +03:00
|
|
|
elif action == 'rate' and rating:
|
2022-01-07 14:31:33 +03:00
|
|
|
valid, context = Logics.rate_counterparty(order,request.user, rating)
|
2022-01-07 21:22:52 +03:00
|
|
|
if not valid: return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
2022-01-07 21:22:52 +03:00
|
|
|
# If nothing of the above... something else is going on. Probably not allowed!
|
2022-01-05 03:13:08 +03:00
|
|
|
else:
|
2022-01-07 21:22:52 +03:00
|
|
|
return Response(
|
|
|
|
{'bad_request':
|
|
|
|
'The Robotic Satoshis working in the warehouse did not understand you. ' +
|
2022-01-11 23:49:53 +03:00
|
|
|
'Please, fill a Bug Issue in Github https://github.com/reckless-satoshi/robosats/issues'},
|
2022-01-07 21:22:52 +03:00
|
|
|
status.HTTP_501_NOT_IMPLEMENTED)
|
2022-01-05 03:13:08 +03:00
|
|
|
|
|
|
|
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-11 23:49:53 +03:00
|
|
|
|
2022-01-18 20:42:45 +03:00
|
|
|
# If an existing user opens the main page by mistake, we do not want it to create a new nickname/profile for him
|
|
|
|
if request.user.is_authenticated:
|
|
|
|
context = {'nickname': request.user.username}
|
|
|
|
not_participant, _ = Logics.validate_already_maker_or_taker(request.user)
|
|
|
|
|
|
|
|
# Does not allow this 'mistake' if an active order
|
|
|
|
if not not_participant:
|
|
|
|
context['bad_request'] = f'You are already logged in as {request.user} and have an active order'
|
|
|
|
return Response(context, status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
# Does not allow this 'mistake' if the last login was sometime ago (5 minutes)
|
2022-01-18 21:24:45 +03:00
|
|
|
# if request.user.last_login < timezone.now() - timedelta(minutes=5):
|
|
|
|
# context['bad_request'] = f'You are already logged in as {request.user}'
|
|
|
|
# return Response(context, status.HTTP_400_BAD_REQUEST)
|
2022-01-11 23:49:53 +03:00
|
|
|
|
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)
|
|
|
|
|
2022-01-18 20:52:48 +03:00
|
|
|
# Hash the token, only 1 iteration.
|
2022-01-02 20:04:51 +03:00
|
|
|
hash = hashlib.sha256(str.encode(token)).hexdigest()
|
|
|
|
|
2022-01-18 20:52:48 +03:00
|
|
|
# Generate nickname deterministically
|
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)
|
|
|
|
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")
|
|
|
|
|
2022-01-18 20:52:48 +03:00
|
|
|
# Create new credentials and login 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'
|
2022-01-08 01:46:30 +03:00
|
|
|
return Response(context, status.HTTP_403_FORBIDDEN)
|
2022-01-03 12:06:51 +03:00
|
|
|
|
2022-01-03 04:31:28 +03:00
|
|
|
def delete(self,request):
|
2022-01-08 01:46:30 +03:00
|
|
|
''' Pressing "give me another" deletes the logged in user '''
|
|
|
|
user = request.user
|
|
|
|
if not user:
|
|
|
|
return Response(status.HTTP_403_FORBIDDEN)
|
2022-01-03 04:31:28 +03:00
|
|
|
|
2022-01-08 01:46:30 +03:00
|
|
|
# Only delete if user life is shorter than 30 minutes. Helps deleting users by mistake
|
|
|
|
if user.date_joined < (timezone.now() - timedelta(minutes=30)):
|
|
|
|
return Response(status.HTTP_400_BAD_REQUEST)
|
2022-01-03 12:06:51 +03:00
|
|
|
|
2022-01-08 01:46:30 +03:00
|
|
|
# Check if it is not a maker or taker!
|
|
|
|
if not Logics.validate_already_maker_or_taker(user):
|
|
|
|
return Response({'bad_request':'User cannot be deleted while he is part of an order'}, status.HTTP_400_BAD_REQUEST)
|
2022-01-03 22:13:39 +03:00
|
|
|
|
2022-01-08 01:46:30 +03:00
|
|
|
logout(request)
|
|
|
|
user.delete()
|
|
|
|
return Response({'user_deleted':'User deleted permanently'}, status.HTTP_301_MOVED_PERMANENTLY)
|
2022-01-03 04:31:28 +03:00
|
|
|
|
2022-01-08 01:46:30 +03:00
|
|
|
|
2022-01-02 18:19:49 +03:00
|
|
|
|
2022-01-05 03:13:08 +03:00
|
|
|
class BookView(ListAPIView):
|
|
|
|
serializer_class = ListOrderSerializer
|
2022-01-10 00:24:48 +03:00
|
|
|
queryset = Order.objects.filter(status=Order.Status.PUB)
|
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-10 00:24:48 +03:00
|
|
|
type = request.GET.get('type')
|
|
|
|
|
2022-01-10 00:54:13 +03:00
|
|
|
queryset = Order.objects.filter(status=Order.Status.PUB)
|
|
|
|
|
|
|
|
# Currency 0 and type 2 are special cases treated as "ANY". (These are not really possible choices)
|
|
|
|
if int(currency) == 0 and int(type) != 2:
|
|
|
|
queryset = Order.objects.filter(type=type, status=Order.Status.PUB)
|
|
|
|
elif int(type) == 2 and int(currency) != 0:
|
|
|
|
queryset = Order.objects.filter(currency=currency, status=Order.Status.PUB)
|
|
|
|
elif not (int(currency) == 0 and int(type) == 2):
|
2022-01-10 00:24:48 +03:00
|
|
|
queryset = Order.objects.filter(currency=currency, type=type, status=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-10 00:24:48 +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-10 00:24:48 +03:00
|
|
|
data['maker_nick'] = str(order.maker)
|
2022-01-06 23:33:40 +03:00
|
|
|
|
2022-01-10 04:12:58 +03:00
|
|
|
# Compute current premium for those orders that are explicitly priced.
|
|
|
|
data['price'], data['premium'] = Logics.price_and_premium_now(order)
|
|
|
|
|
2022-01-10 00:24:48 +03:00
|
|
|
for key in ('status','taker'): # Non participants should not see the status or who is the taker
|
2022-01-05 03:13:08 +03:00
|
|
|
del data[key]
|
2022-01-08 20:19:30 +03:00
|
|
|
|
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-07 21:22:52 +03:00
|
|
|
|
|
|
|
class InfoView(ListAPIView):
|
|
|
|
|
2022-01-09 04:23:13 +03:00
|
|
|
def get(self, request):
|
2022-01-07 21:22:52 +03:00
|
|
|
context = {}
|
2022-01-08 01:46:30 +03:00
|
|
|
|
2022-01-07 21:22:52 +03:00
|
|
|
context['num_public_buy_orders'] = len(Order.objects.filter(type=Order.Types.BUY, status=Order.Status.PUB))
|
2022-01-12 17:26:26 +03:00
|
|
|
context['num_public_sell_orders'] = len(Order.objects.filter(type=Order.Types.SELL, status=Order.Status.PUB))
|
2022-01-11 04:36:34 +03:00
|
|
|
|
|
|
|
# Number of active users (logged in in last 30 minutes)
|
|
|
|
today = datetime.today()
|
2022-01-18 20:52:48 +03:00
|
|
|
context['active_robots_today'] = len(User.objects.filter(last_login__day=today.day))
|
2022-01-11 04:36:34 +03:00
|
|
|
|
2022-01-18 20:52:48 +03:00
|
|
|
# Compute average premium and volume of today
|
2022-01-11 04:36:34 +03:00
|
|
|
queryset = MarketTick.objects.filter(timestamp__day=today.day)
|
|
|
|
if not len(queryset) == 0:
|
2022-01-15 17:22:07 +03:00
|
|
|
weighted_premiums = []
|
2022-01-11 04:36:34 +03:00
|
|
|
volumes = []
|
|
|
|
for tick in queryset:
|
2022-01-15 17:22:07 +03:00
|
|
|
weighted_premiums.append(tick.premium*tick.volume)
|
2022-01-11 04:36:34 +03:00
|
|
|
volumes.append(tick.volume)
|
2022-01-15 17:22:07 +03:00
|
|
|
|
2022-01-11 04:36:34 +03:00
|
|
|
total_volume = sum(volumes)
|
2022-01-15 17:22:07 +03:00
|
|
|
# Avg_premium is the weighted average of the premiums by volume
|
|
|
|
avg_premium = sum(weighted_premiums) / total_volume
|
2022-01-11 04:36:34 +03:00
|
|
|
else:
|
2022-01-14 19:21:42 +03:00
|
|
|
avg_premium = 0
|
|
|
|
total_volume = 0
|
2022-01-11 04:36:34 +03:00
|
|
|
|
2022-01-15 17:22:07 +03:00
|
|
|
context['today_avg_nonkyc_btc_premium'] = round(avg_premium,2)
|
2022-01-11 17:36:43 +03:00
|
|
|
context['today_total_volume'] = total_volume
|
|
|
|
context['lnd_version'] = get_lnd_version()
|
|
|
|
context['robosats_running_commit_hash'] = get_commit_robosats()
|
2022-01-13 00:22:16 +03:00
|
|
|
context['fee'] = FEE
|
|
|
|
context['bond_size'] = float(config('BOND_SIZE'))
|
2022-01-07 21:22:52 +03:00
|
|
|
|
2022-01-08 01:46:30 +03:00
|
|
|
return Response(context, status.HTTP_200_OK)
|
2022-01-03 17:27:25 +03:00
|
|
|
|
|
|
|
|