Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating PHP to Python (Rest-API connection) [closed]

I am learning Python and as an exercise I tried to make a program to make transactions on bitcoin market: https://bitcurex.com. Here is an API reference: https://bitcurex.com/reading-room/API . There is a PHP client example, so I tried to translate it to Python, so I've got:

import math
import time
import simplejson
import urllib
import urllib2
import hmac,hashlib

def microtime():
    return '%f %d' % math.modf(time.time())

def query( path, key, secret, data={} ):
    mt = microtime().split()
    nonce = mt[1] + mt[0][2:]
    data['nonce'] = nonce

    post_data = urllib.urlencode( data )

    sign = hmac.new( secret.decode('base64'), post_data, hashlib.sha512 ).digest()

    headers = {'Rest-Key' : key,
               'Rest-Sign': sign.encode('base64').strip(),
               'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
               'Content-type': 'application/x-www-form-urlencoded'}
    print headers

    url = 'https://bitcurex.com/api/0/' + path

    req = urllib2.Request( url, post_data, headers )
    response = urllib2.urlopen(req)

    return simplejson.loads(response.read())

print query('getFunds', '29a28e8fe234537056a8b256c0df50413f50da9c49ca61991ea8b8f108a88e09',  'y2NDxKGa/xvhtXrDP+3oscbBUFSac9+T8jzu2nRmt0vBdHbbl8NRqdmxKFr2IwwY5LAskTQZGyy2XONaNN6Jrg==')

These API keys are working - you can only make getFunds query with them.

It keeps returning error "Must me logged in". I tried to look on that request through Fiddler Proxy Debugger, and here you have the headers of that attempt:

POST /api/0/getFunds HTTP/1.1
Accept-Encoding: identity
Rest-Sign: Dd1WBn2T5SYTbqMMohOxr46IaLDrkelgH7AgkrrB0mT0PxKfv15vSJ3b6xNdc5PO2Yz9cDpu0u/H
WIc7bH56sQ==: 
Content-Length: 22
Rest-Key: 29a28e8fe234537056a8b256c0df50413f50da9c49ca61991ea8b8f108a88e09
Connection: close
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)
Host: bitcurex.com
Content-Type: application/x-www-form-urlencoded

Fiddler is showing me an error:

Incorrectly formed request headers.
Missing colon in header #3, WIc7bH56sQ==

Any Ideas? It seems like my Rest-Sign is too long or something like that. I think that my code should do exactly the same as PHP example. What I'm doing wrong?

like image 594
TigerInALoop Avatar asked Nov 04 '22 08:11

TigerInALoop


1 Answers

This line is suspicious:

'Rest-Sign': sign.encode('base64').strip()

Do you really want a header's value to contain literal '\n' signs? This is what encode('base64') returns --- in your example, this string:

'Dd1WBn2T5SYTbqMMohOxr46IaLDrkelgH7AgkrrB0mT0PxKfv15vSJ3b6xNdc5PO2Yz9cDpu0u/H\nWIc7bH56sQ=='

Note the \n in the middle. I'm unsure, but probably removing all \n signs gives you what you need.

like image 154
Armin Rigo Avatar answered Nov 12 '22 17:11

Armin Rigo