api: Handle json content-type.

This commit is contained in:
tecnovert 2021-01-28 01:55:42 +02:00
parent 7d0d0687cf
commit 7a9cafb520
No known key found for this signature in database
GPG Key ID: 8ED6D8750C4E3F93
5 changed files with 88 additions and 60 deletions

View File

@ -47,6 +47,8 @@ from .ui import (
inputAmount, inputAmount,
describeBid, describeBid,
setCoinFilter, setCoinFilter,
get_data_entry,
have_data_entry,
) )
@ -315,12 +317,14 @@ class HttpHandler(BaseHTTPRequestHandler):
errors = [] errors = []
parsed_data = {} parsed_data = {}
if b'addr_from' in form_data: if have_data_entry(form_data, 'addr_from'):
page_data['addr_from'] = form_data[b'addr_from'][0].decode('utf-8') page_data['addr_from'] = get_data_entry(form_data, 'addr_from')
parsed_data['addr_from'] = None if page_data['addr_from'] == '-1' else page_data['addr_from'] parsed_data['addr_from'] = None if page_data['addr_from'] == '-1' else page_data['addr_from']
else:
parsed_data['addr_from'] = None
try: try:
page_data['coin_from'] = int(form_data[b'coin_from'][0]) page_data['coin_from'] = int(get_data_entry(form_data, 'coin_from'))
coin_from = Coins(page_data['coin_from']) coin_from = Coins(page_data['coin_from'])
ci_from = swap_client.ci(coin_from) ci_from = swap_client.ci(coin_from)
if coin_from != Coins.XMR: if coin_from != Coins.XMR:
@ -330,7 +334,7 @@ class HttpHandler(BaseHTTPRequestHandler):
errors.append('Unknown Coin From') errors.append('Unknown Coin From')
try: try:
page_data['coin_to'] = int(form_data[b'coin_to'][0]) page_data['coin_to'] = int(get_data_entry(form_data, 'coin_to'))
coin_to = Coins(page_data['coin_to']) coin_to = Coins(page_data['coin_to'])
ci_to = swap_client.ci(coin_to) ci_to = swap_client.ci(coin_to)
parsed_data['coin_to'] = coin_to parsed_data['coin_to'] = coin_to
@ -342,16 +346,16 @@ class HttpHandler(BaseHTTPRequestHandler):
errors.append('Unknown Coin To') errors.append('Unknown Coin To')
try: try:
page_data['amt_from'] = form_data[b'amt_from'][0].decode('utf-8') page_data['amt_from'] = get_data_entry(form_data, 'amt_from')
parsed_data['amt_from'] = inputAmount(page_data['amt_from'], ci_from) parsed_data['amt_from'] = inputAmount(page_data['amt_from'], ci_from)
parsed_data['min_bid'] = int(parsed_data['amt_from']) parsed_data['min_bid'] = int(parsed_data['amt_from'])
except Exception as e: except Exception:
errors.append('Amount From') errors.append('Amount From')
try: try:
page_data['amt_to'] = form_data[b'amt_to'][0].decode('utf-8') page_data['amt_to'] = get_data_entry(form_data, 'amt_to')
parsed_data['amt_to'] = inputAmount(page_data['amt_to'], ci_to) parsed_data['amt_to'] = inputAmount(page_data['amt_to'], ci_to)
except Exception as e: except Exception:
errors.append('Amount To') errors.append('Amount To')
if 'amt_to' in parsed_data and 'amt_from' in parsed_data: if 'amt_to' in parsed_data and 'amt_from' in parsed_data:
@ -364,38 +368,38 @@ class HttpHandler(BaseHTTPRequestHandler):
page_data['step2'] = True page_data['step2'] = True
if b'fee_from_conf' in form_data: if have_data_entry(form_data, 'fee_from_conf'):
page_data['fee_from_conf'] = int(form_data[b'fee_from_conf'][0]) page_data['fee_from_conf'] = int(get_data_entry(form_data, 'fee_from_conf'))
parsed_data['fee_from_conf'] = page_data['fee_from_conf'] parsed_data['fee_from_conf'] = page_data['fee_from_conf']
if b'fee_from_extra' in form_data: if have_data_entry(form_data, 'fee_from_extra'):
page_data['fee_from_extra'] = int(form_data[b'fee_from_extra'][0]) page_data['fee_from_extra'] = int(get_data_entry(form_data, 'fee_from_extra'))
parsed_data['fee_from_extra'] = page_data['fee_from_extra'] parsed_data['fee_from_extra'] = page_data['fee_from_extra']
if b'fee_to_conf' in form_data: if have_data_entry(form_data, 'fee_to_conf'):
page_data['fee_to_conf'] = int(form_data[b'fee_to_conf'][0]) page_data['fee_to_conf'] = int(get_data_entry(form_data, 'fee_to_conf'))
parsed_data['fee_to_conf'] = page_data['fee_to_conf'] parsed_data['fee_to_conf'] = page_data['fee_to_conf']
if b'fee_to_extra' in form_data: if have_data_entry(form_data, 'fee_to_extra'):
page_data['fee_to_extra'] = int(form_data[b'fee_to_extra'][0]) page_data['fee_to_extra'] = int(get_data_entry(form_data, 'fee_to_extra'))
parsed_data['fee_to_extra'] = page_data['fee_to_extra'] parsed_data['fee_to_extra'] = page_data['fee_to_extra']
if b'check_offer' in form_data: if have_data_entry(form_data, 'check_offer'):
page_data['check_offer'] = True page_data['check_offer'] = True
if b'submit_offer' in form_data: if have_data_entry(form_data, 'submit_offer'):
page_data['submit_offer'] = True page_data['submit_offer'] = True
if b'lockhrs' in form_data: if have_data_entry(form_data, 'lockhrs'):
page_data['lockhrs'] = int(form_data[b'lockhrs'][0]) page_data['lockhrs'] = int(get_data_entry(form_data, 'lockhrs'))
parsed_data['lock_seconds'] = page_data['lockhrs'] * 60 * 60 parsed_data['lock_seconds'] = page_data['lockhrs'] * 60 * 60
page_data['autoaccept'] = True if b'autoaccept' in form_data else False page_data['autoaccept'] = True if have_data_entry(form_data, 'autoaccept') else False
parsed_data['autoaccept'] = page_data['autoaccept'] parsed_data['autoaccept'] = page_data['autoaccept']
try: try:
if len(errors) == 0 and page_data['swap_style'] == 'xmr': if len(errors) == 0 and page_data['swap_style'] == 'xmr':
if b'fee_rate_from' in form_data: if have_data_entry(form_data, 'fee_rate_from'):
page_data['from_fee_override'] = form_data[b'fee_rate_from'][0].decode('utf-8') page_data['from_fee_override'] = get_data_entry(form_data, 'fee_rate_from')
parsed_data['from_fee_override'] = page_data['from_fee_override'] parsed_data['from_fee_override'] = page_data['from_fee_override']
else: else:
from_fee_override, page_data['from_fee_src'] = swap_client.getFeeRateForCoin(parsed_data['coin_from'], page_data['fee_from_conf']) from_fee_override, page_data['from_fee_src'] = swap_client.getFeeRateForCoin(parsed_data['coin_from'], page_data['fee_from_conf'])
@ -410,8 +414,8 @@ class HttpHandler(BaseHTTPRequestHandler):
page_data['tla_from'] = ci_from.ticker() page_data['tla_from'] = ci_from.ticker()
if coin_to == Coins.XMR: if coin_to == Coins.XMR:
if b'fee_rate_to' in form_data: if have_data_entry(form_data, 'fee_rate_to'):
page_data['to_fee_override'] = form_data[b'fee_rate_to'][0].decode('utf-8') page_data['to_fee_override'] = get_data_entry(form_data, 'fee_rate_to')
parsed_data['to_fee_override'] = page_data['to_fee_override'] parsed_data['to_fee_override'] = page_data['to_fee_override']
else: else:
to_fee_override, page_data['to_fee_src'] = swap_client.getFeeRateForCoin(parsed_data['coin_to'], page_data['fee_to_conf']) to_fee_override, page_data['to_fee_src'] = swap_client.getFeeRateForCoin(parsed_data['coin_to'], page_data['fee_to_conf'])
@ -616,8 +620,8 @@ class HttpHandler(BaseHTTPRequestHandler):
messages = [] messages = []
form_data = self.checkForm(post_string, 'offers', messages) form_data = self.checkForm(post_string, 'offers', messages)
if form_data and b'applyfilters' in form_data: if form_data and b'applyfilters' in form_data:
filters['coin_from'] = setCoinFilter(form_data, b'coin_from') filters['coin_from'] = setCoinFilter(form_data, 'coin_from')
filters['coin_to'] = setCoinFilter(form_data, b'coin_to') filters['coin_to'] = setCoinFilter(form_data, 'coin_to')
if b'sort_by' in form_data: if b'sort_by' in form_data:
sort_by = form_data[b'sort_by'][0].decode('utf-8') sort_by = form_data[b'sort_by'][0].decode('utf-8')
@ -814,10 +818,10 @@ class HttpHandler(BaseHTTPRequestHandler):
self.send_response(status_code) self.send_response(status_code)
if self.server.allow_cors: if self.server.allow_cors:
self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', content_type) self.send_header('Content-Type', content_type)
self.end_headers() self.end_headers()
def handle_http(self, status_code, path, post_string=''): def handle_http(self, status_code, path, post_string='', is_json=False):
url_split = self.path.split('/') url_split = self.path.split('/')
if len(url_split) > 1 and url_split[1] == 'json': if len(url_split) > 1 and url_split[1] == 'json':
try: try:
@ -832,7 +836,7 @@ class HttpHandler(BaseHTTPRequestHandler):
'network': js_network, 'network': js_network,
'revokeoffer': js_revokeoffer, 'revokeoffer': js_revokeoffer,
}.get(url_split[2], js_index) }.get(url_split[2], js_index)
return func(self, url_split, post_string) return func(self, url_split, post_string, is_json)
except Exception as ex: except Exception as ex:
if self.server.swap_client.debug is True: if self.server.swap_client.debug is True:
traceback.print_exc() traceback.print_exc()
@ -903,8 +907,10 @@ class HttpHandler(BaseHTTPRequestHandler):
self.wfile.write(response) self.wfile.write(response)
def do_POST(self): def do_POST(self):
post_string = self.rfile.read(int(self.headers['Content-Length'])) post_string = self.rfile.read(int(self.headers.get('Content-Length')))
response = self.handle_http(200, self.path, post_string)
is_json = True if 'json' in self.headers.get('Content-Type', '') else False
response = self.handle_http(200, self.path, post_string, is_json)
self.wfile.write(response) self.wfile.write(response)
def do_HEAD(self): def do_HEAD(self):

View File

@ -20,6 +20,7 @@ from .ui import (
inputAmount, inputAmount,
describeBid, describeBid,
setCoinFilter, setCoinFilter,
get_data_entry,
) )
@ -28,17 +29,21 @@ def js_error(self, error_str):
return bytes(error_str_json, 'UTF-8') return bytes(error_str_json, 'UTF-8')
def js_wallets(self, url_split, post_string): def js_wallets(self, url_split, post_string, is_json):
return bytes(json.dumps(self.server.swap_client.getWalletsInfo()), 'UTF-8') return bytes(json.dumps(self.server.swap_client.getWalletsInfo()), 'UTF-8')
def js_offers(self, url_split, post_string, sent=False): def js_offers(self, url_split, post_string, is_json, sent=False):
offer_id = None offer_id = None
if len(url_split) > 3: if len(url_split) > 3:
if url_split[3] == 'new': if url_split[3] == 'new':
if post_string == '': if post_string == '':
raise ValueError('No post data') raise ValueError('No post data')
form_data = urllib.parse.parse_qs(post_string) if is_json:
form_data = json.loads(post_string)
form_data['is_json'] = True
else:
form_data = urllib.parse.parse_qs(post_string)
offer_id = self.postNewOffer(form_data) offer_id = self.postNewOffer(form_data)
rv = {'offer_id': offer_id.hex()} rv = {'offer_id': offer_id.hex()}
return bytes(json.dumps(rv), 'UTF-8') return bytes(json.dumps(rv), 'UTF-8')
@ -57,23 +62,27 @@ def js_offers(self, url_split, post_string, sent=False):
filters['offer_id'] = offer_id filters['offer_id'] = offer_id
if post_string != '': if post_string != '':
post_data = urllib.parse.parse_qs(post_string) if is_json:
filters['coin_from'] = setCoinFilter(post_data, b'coin_from') post_data = json.loads(post_string)
filters['coin_to'] = setCoinFilter(post_data, b'coin_to') post_data['is_json'] = True
else:
post_data = urllib.parse.parse_qs(post_string)
filters['coin_from'] = setCoinFilter(post_data, 'coin_from')
filters['coin_to'] = setCoinFilter(post_data, 'coin_to')
if b'sort_by' in post_data: if b'sort_by' in post_data:
sort_by = post_data[b'sort_by'][0].decode('utf-8') sort_by = get_data_entry(post_data, 'sort_by')
assert(sort_by in ['created_at', 'rate']), 'Invalid sort by' assert(sort_by in ['created_at', 'rate']), 'Invalid sort by'
filters['sort_by'] = sort_by filters['sort_by'] = sort_by
if b'sort_dir' in post_data: if b'sort_dir' in post_data:
sort_dir = post_data[b'sort_dir'][0].decode('utf-8') sort_dir = get_data_entry(post_data, 'sort_dir')
assert(sort_dir in ['asc', 'desc']), 'Invalid sort dir' assert(sort_dir in ['asc', 'desc']), 'Invalid sort dir'
filters['sort_dir'] = sort_dir filters['sort_dir'] = sort_dir
if b'offset' in post_data: if b'offset' in post_data:
filters['offset'] = int(post_data[b'offset'][0]) filters['offset'] = int(get_data_entry(post_data, 'offset'))
if b'limit' in post_data: if b'limit' in post_data:
filters['limit'] = int(post_data[b'limit'][0]) filters['limit'] = int(get_data_entry(post_data, 'limit'))
assert(filters['limit'] > 0 and filters['limit'] <= PAGE_LIMIT), 'Invalid limit' assert(filters['limit'] > 0 and filters['limit'] <= PAGE_LIMIT), 'Invalid limit'
offers = self.server.swap_client.listOffers(sent, filters) offers = self.server.swap_client.listOffers(sent, filters)
@ -94,11 +103,11 @@ def js_offers(self, url_split, post_string, sent=False):
return bytes(json.dumps(rv), 'UTF-8') return bytes(json.dumps(rv), 'UTF-8')
def js_sentoffers(self, url_split, post_string): def js_sentoffers(self, url_split, post_string, is_json):
return self.js_offers(url_split, post_string, True) return self.js_offers(url_split, post_string, is_json, True)
def js_bids(self, url_split, post_string): def js_bids(self, url_split, post_string, is_json):
swap_client = self.server.swap_client swap_client = self.server.swap_client
if len(url_split) > 3: if len(url_split) > 3:
if url_split[3] == 'new': if url_split[3] == 'new':
@ -156,20 +165,20 @@ def js_bids(self, url_split, post_string):
} for b in bids]), 'UTF-8') } for b in bids]), 'UTF-8')
def js_sentbids(self, url_split, post_string): def js_sentbids(self, url_split, post_string, is_json):
return bytes(json.dumps(self.server.swap_client.listBids(sent=True)), 'UTF-8') return bytes(json.dumps(self.server.swap_client.listBids(sent=True)), 'UTF-8')
def js_network(self, url_split, post_string): def js_network(self, url_split, post_string, is_json):
return bytes(json.dumps(self.server.swap_client.get_network_info()), 'UTF-8') return bytes(json.dumps(self.server.swap_client.get_network_info()), 'UTF-8')
def js_revokeoffer(self, url_split, post_string): def js_revokeoffer(self, url_split, post_string, is_json):
offer_id = bytes.fromhex(url_split[3]) offer_id = bytes.fromhex(url_split[3])
assert(len(offer_id) == 28) assert(len(offer_id) == 28)
self.server.swap_client.revokeOffer(offer_id) self.server.swap_client.revokeOffer(offer_id)
return bytes(json.dumps({'revoked_offer': offer_id.hex()}), 'UTF-8') return bytes(json.dumps({'revoked_offer': offer_id.hex()}), 'UTF-8')
def js_index(self, url_split, post_string): def js_index(self, url_split, post_string, is_json):
return bytes(json.dumps(self.server.swap_client.getSummary()), 'UTF-8') return bytes(json.dumps(self.server.swap_client.getSummary()), 'UTF-8')

View File

@ -15,7 +15,7 @@ def callrpc_xmr(rpc_port, auth, method, params=[], rpc_host='127.0.0.1', path='j
'jsonrpc': '2.0' 'jsonrpc': '2.0'
} }
headers = { headers = {
'content-type': 'application/json' 'Content-Type': 'application/json'
} }
p = requests.post(url, data=json.dumps(request_body), auth=requests.auth.HTTPDigestAuth(auth[0], auth[1]), headers=headers, timeout=timeout) p = requests.post(url, data=json.dumps(request_body), auth=requests.auth.HTTPDigestAuth(auth[0], auth[1]), headers=headers, timeout=timeout)
r = json.loads(p.text) r = json.loads(p.text)
@ -38,7 +38,7 @@ def callrpc_xmr_na(rpc_port, method, params=[], rpc_host='127.0.0.1', path='json
'jsonrpc': '2.0' 'jsonrpc': '2.0'
} }
headers = { headers = {
'content-type': 'application/json' 'Content-Type': 'application/json'
} }
p = requests.post(url, data=json.dumps(request_body), headers=headers, timeout=timeout) p = requests.post(url, data=json.dumps(request_body), headers=headers, timeout=timeout)
r = json.loads(p.text) r = json.loads(p.text)
@ -55,7 +55,7 @@ def callrpc_xmr2(rpc_port, method, params=None, rpc_host='127.0.0.1', timeout=12
try: try:
url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, method) url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, method)
headers = { headers = {
'content-type': 'application/json' 'Content-Type': 'application/json'
} }
if params is None: if params is None:
p = requests.post(url, headers=headers, timeout=timeout) p = requests.post(url, headers=headers, timeout=timeout)

View File

@ -37,10 +37,22 @@ def inputAmount(amount_str, ci):
return make_int(amount_str, ci.exp()) return make_int(amount_str, ci.exp())
def get_data_entry(post_data, name):
if 'is_json' in post_data:
return post_data[name]
return post_data[name.encode('utf-8')][0].decode('utf-8')
def have_data_entry(post_data, name):
if 'is_json' in post_data:
return name in post_data
return name.encode('utf-8') in post_data
def setCoinFilter(form_data, field_name): def setCoinFilter(form_data, field_name):
if field_name not in form_data: try:
coin_type = int(get_data_entry(form_data, field_name))
except Exception:
return -1 return -1
coin_type = int(form_data[field_name][0])
if coin_type == -1: if coin_type == -1:
return -1 return -1
try: try:
@ -199,3 +211,4 @@ def describeBid(swap_client, bid, xmr_swap, offer, xmr_offer, bid_events, edit_b
data['events'] = bid_events data['events'] = bid_events
return data return data

View File

@ -53,12 +53,12 @@ class Test(XmrTestBase):
assert(float(wallets1['6']['balance']) > 0.0) assert(float(wallets1['6']['balance']) > 0.0)
offer_data = { offer_data = {
'addr_from': '-1', 'addr_from': -1,
'coin_from': '1', 'coin_from': 1,
'coin_to': '6', 'coin_to': 6,
'amt_from': '1', 'amt_from': 1,
'amt_to': '1', 'amt_to': 1,
'lockhrs': '24', 'lockhrs': 24,
'autoaccept': True} 'autoaccept': True}
rv = json.loads(urlopen('http://127.0.0.1:12700/json/offers/new', data=parse.urlencode(offer_data).encode()).read()) rv = json.loads(urlopen('http://127.0.0.1:12700/json/offers/new', data=parse.urlencode(offer_data).encode()).read())
offer0_id = rv['offer_id'] offer0_id = rv['offer_id']