Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement exchange API. #77

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions oss_server/base/urls.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
from django.conf.urls import url

from .v1.views import (CreateLicenseRawTxView,
CreateLicenseTransferRawTxView,
CreateMintRawTxView,
CreateSmartContractRawTxView,
CreateRawTxView,
GetBalanceView,
GetLicenseInfoView,
GetRawTxView,
SendRawTxView)
from .v1.views import *

urlpatterns = [
url('^v1/balance/(?P<address>[a-zA-Z0-9]+)$', GetBalanceView.as_view()),
Expand All @@ -22,5 +14,6 @@
url('^v1/smartcontract/send$', SendRawTxView.as_view()),
url('^v1/transaction/prepare$', CreateRawTxView.as_view()),
url('^v1/transaction/send$', SendRawTxView.as_view()),
url('^v1/exchange/prepare$', CreateExchangeRawTxView.as_view()),
url('^v1/transaction/(?P<tx_id>[a-z0-9]+)$', GetRawTxView.as_view()),
]
75 changes: 74 additions & 1 deletion oss_server/base/v1/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import httplib
import json
import logging
from decimal import Decimal

from django.conf import settings
from django.http import JsonResponse
Expand All @@ -11,9 +13,9 @@
from gcoinrpc import connect_to_remote
from gcoinrpc.exceptions import InvalidAddressOrKey, InvalidParameter

from ..utils import balance_from_utxos, select_utxo, utxo_to_txin
from .forms import (CreateLicenseRawTxForm, CreateLicenseTransferRawTxForm,
CreateSmartContractRawTxForm, MintRawTxForm, RawTxForm)
from ..utils import balance_from_utxos, select_utxo, utxo_to_txin

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -315,3 +317,74 @@ def _get_license_utxo(self, utxos, color):
if utxo['color'] == color:
return utxo
return None


class CreateExchangeRawTxView(CsrfExemptMixin, View):

def post(self, request, *args, **kwargs):
if request.META['CONTENT_TYPE'] != 'application/json':
return JsonResponse({'error': "only accept 'application/json' as Content-Type"})

json_obj = json.loads(request.body, parse_float=Decimal)
print(json_obj)
try:
self._validate_json_obj(json_obj)
except KeyError as e:
return JsonResponse({'error': e.message})

addr_in_map = {}
addr_out_map = {}

ins = []
outs = []

# check if fee_address has enough fee.
utxos = get_rpc_connection().gettxoutaddress(json_obj['fee_address'])
inputs = select_utxo(utxos=utxos, color=1, sum=1)
if not inputs:
return JsonResponse({'error': 'insufficient fee in address {}'.format(json_obj['fee_address'])})
ins += [utxo_to_txin(utxo) for utxo in inputs]
# the exchange part
for tx in json_obj['txs']:
addr1_in = addr_in_map.setdefault(tx['address1'], {})
addr1_in[tx['color1']] = addr1_in.get(tx['color1'], 0) + tx['amount1']
addr2_in = addr_in_map.setdefault(tx['address2'], {})
addr2_in[tx['color2']] = addr1_in.get(tx['color2'], 0) + tx['amount2']

addr1_out = addr_out_map.setdefault(tx['address1'], {})
Copy link

@Jsying Jsying Oct 7, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

希望vouts不要加起來,才有辦法在transaction裡,看到比較清楚的交換內容。

addr1_out[tx['color2']] = addr1_in.get(tx['color2'], 0) + tx['amount2']
addr2_out = addr_out_map.setdefault(tx['address2'], {})
addr2_out[tx['color1']] = addr1_in.get(tx['color1'], 0) + tx['amount1']

for addr, color_amount_map in addr_in_map.items():
utxos = get_rpc_connection().gettxoutaddress(addr)
for color, amount in color_amount_map.items():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

如果color是1且這個addr=fee_address可能會有問題,color 1其實不夠,選到重複的utxo

inputs = select_utxo(utxos=utxos, color=color, sum=amount)
if not inputs:
return JsonResponse({
'error': 'address {} does not have enough color {} to exchange'.format(addr, color)
})
ins += [utxo_to_txin(utxo) for utxo in inputs]

for addr, color_amount_map in addr_out_map.items():
for color, amount in color_amount_map.items():
outs = [{'address': addr, 'value': int(amount * 10**8), 'color': color}]

raw_tx = make_raw_tx(ins, outs)
Copy link

@Jsying Jsying Oct 7, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ins裡的utxo的amount應該大於或等於outs的amount。這邊要算找錢

return JsonResponse({'raw_tx': raw_tx})

def _validate_json_obj(self, json_obj):
for key in ('fee_address', 'txs'):
if key not in json_obj:
raise KeyError('missing key: {}'.format(key))
for tx in json_obj['txs']:
for key in ('address1', 'color1', 'amount1', 'address2', 'color2', 'amount2'):
if key not in tx:
raise KeyError('missing key in tx: {}'.format(key))

def _extract_addr_in_json(self, json_obj):
addr_set = set(json_obj['fee_address'])
for tx in json_obj['txs']:
addr_set.add(tx['address1'])
addr_set.add(tx['address2'])
return addr_set
10 changes: 5 additions & 5 deletions oss_server/oss_server/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@
# Gcoin RPC

GCOIN_RPC = {
'user': '<user>',
'password': '<passwrod>',
'host': '<host>',
'port': '<port>',
'user': 'gcoin',
'password': 'abc123',
'host': 'store1.diqi.us',
'port': '9876',
}


Expand Down Expand Up @@ -135,7 +135,7 @@

STATIC_URL = '/static/'

LOG_DIR = os.path.dirname(BASE_DIR) + '/log/'
LOG_DIR = os.path.dirname(BASE_DIR) + '/log/'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ mock==1.0.1
MySQL-python==1.2.5
tornado==4.4.1

git+ssh://[email protected]/OpenNetworking/gcoin-rpc.git@develop#egg=gcoin-python
git+ssh://[email protected]/OpenNetworking/gcoin-rpc.git@develop
git+ssh://[email protected]/OpenNetworking/pygcointools@master