빗썸 api인데요, 몇몇 코드의 이유가 궁금합니다.

조회수 2616회

가상화폐 거래소인 빗썸에서 api를 사용해보려 합니다.
아직 초보인지라 모르는 부분이 많아, 여기저기 찾아가며 어떤 함수가 무슨 작동을 하는지 찾아보고는 있지만, 그 이유에 대해서 잘 해석이 안되는 부분이 있습니다.

코드가 길지만 복잡한 내용이 아니라, 아시는 분들은 한번에 쭉 읽으실 수 있을 것 같은데요.. 부디 지나치지 마시고 도움좀 부탁드립니다. 전체 코드는 맨 아래에 있습니다.

질문입니다.

  1. xcoinApiCall함수 안에서, data라는 변수를 만드는데 거기서 chr(0)이 하는 역할이 뭔지 궁금합니다.
  2. 그 아래를 쭉 보시면 다음과 같은 코드들이 있습니다. 왜 이런 작업들을 해주는지 잘 모르겠는데 이 부분 자세한 설명 부탁드립니다 ㅠㅠ 뭐 하나 할 때마다 자꾸 utf-8로 바꿔주고.. 인코딩하고 디코딩하고 왜 이런 복잡한 작업이 필요한지 잘 모르겠습니다.
        data = endpoint + chr(0) + str_data + chr(0) + nonce;
        utf8_data = data.encode('utf-8');

        key = self.api_secret;
        utf8_key = key.encode('utf-8');

        h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512);
        hex_output = h.hexdigest();
        utf8_hex_output = hex_output.encode('utf-8');

        api_sign = base64.b64encode(utf8_hex_output);
        utf8_api_sign = api_sign.decode('utf-8');

아래는 전체 코드입니다.

#
# XCoin API-call related functions
#
# @author   btckorea
# @date 2017-04-12
#
# Compatible with python3 version.

import sys
import time
import math
import base64
import hmac, hashlib
import urllib.parse
import pycurl
import json


class XCoinAPI:
    api_url = "https://api.bithumb.com";
    api_key = "";
    api_secret = "";

    def __init__(self, api_key, api_secret):
        self.api_key = api_key;
        self.api_secret = api_secret;

    def body_callback(self, buf):
        self.contents = buf;

    def microtime(self, get_as_float = False):
        if get_as_float:
            return time.time()
        else:
            return '%f %d' % math.modf(time.time())

    def usecTime(self) :
        mt = self.microtime(False)
        mt_array = mt.split(" ")[:2];
        return mt_array[1] + mt_array[0][2:5];

    def xcoinApiCall(self, endpoint, rgParams):
        # 1. Api-Sign and Api-Nonce information generation.
        # 2. Request related information from the Bithumb API server.
        #
        # - nonce: it is an arbitrary number that may only be used once.
        # - api_sign: API signature information created in various combinations values.

        endpoint_item_array = {
            "endpoint" : endpoint
        };

        uri_array = dict(endpoint_item_array, **rgParams); # Concatenate the two arrays.

        str_data = urllib.parse.urlencode(uri_array);

        nonce = self.usecTime();

        data = endpoint + chr(0) + str_data + chr(0) + nonce;
        utf8_data = data.encode('utf-8');

        key = self.api_secret;
        utf8_key = key.encode('utf-8');

        h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512);
        hex_output = h.hexdigest();
        utf8_hex_output = hex_output.encode('utf-8');

        api_sign = base64.b64encode(utf8_hex_output);
        utf8_api_sign = api_sign.decode('utf-8');


        curl_handle = pycurl.Curl();
        curl_handle.setopt(pycurl.POST, 1);
        #curl_handle.setopt(pycurl.VERBOSE, 1); # vervose mode :: 1 => True, 0 => False
        curl_handle.setopt(pycurl.POSTFIELDS, str_data);

        url = self.api_url + endpoint;
        curl_handle.setopt(curl_handle.URL, url);
        curl_handle.setopt(curl_handle.HTTPHEADER, ['Api-Key: ' + self.api_key, 'Api-Sign: ' + utf8_api_sign, 'Api-Nonce: ' + nonce]);
        curl_handle.setopt(curl_handle.WRITEFUNCTION, self.body_callback);
        curl_handle.perform();

        #response_code = curl_handle.getinfo(pycurl.RESPONSE_CODE); # Get http response status code.

        curl_handle.close();

        return (json.loads(self.contents));

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • chr(0)이면 ascii code 값으로 NULL일텐데요.

    nullendpointstr_data, nonce를 구분하기 위한 용도가 아닐까 추측됩니다.

    utf-8 변환은 받아주는 곳에서 UTF-8 인코딩 포멧을 사용해서 그런게 아닌가 싶고 HMAC 은 Hash based Message Authentication Code 를 말하는 것 같아요.

    통신에 암호화가 필요할테고 그걸 HASH 기반으로 키와 sign등을 가지고 있는 것 같아보입니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)