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

View file

@ -20,6 +20,7 @@ from .ui import (
inputAmount,
describeBid,
setCoinFilter,
get_data_entry,
)
@ -28,16 +29,20 @@ def js_error(self, error_str):
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')
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
if len(url_split) > 3:
if url_split[3] == 'new':
if post_string == '':
raise ValueError('No post data')
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)
rv = {'offer_id': offer_id.hex()}
@ -57,23 +62,27 @@ def js_offers(self, url_split, post_string, sent=False):
filters['offer_id'] = offer_id
if post_string != '':
if is_json:
post_data = json.loads(post_string)
post_data['is_json'] = True
else:
post_data = urllib.parse.parse_qs(post_string)
filters['coin_from'] = setCoinFilter(post_data, b'coin_from')
filters['coin_to'] = setCoinFilter(post_data, b'coin_to')
filters['coin_from'] = setCoinFilter(post_data, 'coin_from')
filters['coin_to'] = setCoinFilter(post_data, 'coin_to')
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'
filters['sort_by'] = sort_by
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'
filters['sort_dir'] = sort_dir
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:
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'
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')
def js_sentoffers(self, url_split, post_string):
return self.js_offers(url_split, post_string, True)
def js_sentoffers(self, url_split, post_string, is_json):
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
if len(url_split) > 3:
if url_split[3] == 'new':
@ -156,20 +165,20 @@ def js_bids(self, url_split, post_string):
} 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')
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')
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])
assert(len(offer_id) == 28)
self.server.swap_client.revokeOffer(offer_id)
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')

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'
}
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)
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'
}
headers = {
'content-type': 'application/json'
'Content-Type': 'application/json'
}
p = requests.post(url, data=json.dumps(request_body), headers=headers, timeout=timeout)
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:
url = 'http://{}:{}/{}'.format(rpc_host, rpc_port, method)
headers = {
'content-type': 'application/json'
'Content-Type': 'application/json'
}
if params is None:
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())
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):
if field_name not in form_data:
try:
coin_type = int(get_data_entry(form_data, field_name))
except Exception:
return -1
coin_type = int(form_data[field_name][0])
if coin_type == -1:
return -1
try:
@ -199,3 +211,4 @@ def describeBid(swap_client, bid, xmr_swap, offer, xmr_offer, bid_events, edit_b
data['events'] = bid_events
return data

View file

@ -53,12 +53,12 @@ class Test(XmrTestBase):
assert(float(wallets1['6']['balance']) > 0.0)
offer_data = {
'addr_from': '-1',
'coin_from': '1',
'coin_to': '6',
'amt_from': '1',
'amt_to': '1',
'lockhrs': '24',
'addr_from': -1,
'coin_from': 1,
'coin_to': 6,
'amt_from': 1,
'amt_to': 1,
'lockhrs': 24,
'autoaccept': True}
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']