forked from includeleec/mixin-python3-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mixin_api.py
567 lines (441 loc) · 16.5 KB
/
mixin_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# -*- coding: utf-8 -*-
"""
Mixin API for Python 3.x
This SDK base on 'https://github.com/myrual/mixin_client_demo/blob/master/mixin_api.py'
some method note '?', because can't run right result, may be it will be resolved later.
env: python 3.x
code by lee.c
update at 2018.12.2
"""
from Crypto.PublicKey import RSA
import base64
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
import Crypto
import time
from Crypto import Random
from Crypto.Cipher import AES
import hashlib
import datetime
import jwt
import uuid
import json
import requests
from urllib.parse import urlencode
class MIXIN_API:
def __init__(self, mixin_config):
# robot's config
self.client_id = mixin_config.client_id
self.client_secret = mixin_config.client_secret
self.pay_session_id = mixin_config.pay_session_id
self.pay_pin = mixin_config.pay_pin
self.pin_token = mixin_config.pin_token
self.private_key = mixin_config.private_key
self.keyForAES = ""
# mixin api base url
self.api_base_url = 'https://api.mixin.one'
"""
BASE METHON
"""
def generateSig(self, method, uri, body):
hashresult = hashlib.sha256((method + uri+body).encode('utf-8')).hexdigest()
return hashresult
def genGETPOSTSig(self, methodstring, uristring, bodystring):
jwtSig = self.generateSig(methodstring, uristring, bodystring)
return jwtSig
def genGETSig(self, uristring, bodystring):
return self.genGETPOSTSig("GET", uristring, bodystring)
def genPOSTSig(self, uristring, bodystring):
return self.genGETPOSTSig("POST", uristring, bodystring)
def genGETJwtToken(self, uristring, bodystring, jti):
jwtSig = self.genGETSig(uristring, bodystring)
iat = datetime.datetime.utcnow()
exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=200)
encoded = jwt.encode({'uid':self.client_id, 'sid':self.pay_session_id,'iat':iat,'exp': exp, 'jti':jti,'sig':jwtSig}, self.private_key, algorithm='RS512')
return encoded
def genGETListenSignedToken(self, uristring, bodystring, jti):
jwtSig = self.genGETSig(uristring, bodystring)
iat = datetime.datetime.utcnow()
exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=200)
encoded = jwt.encode({'uid':self.client_id, 'sid':self.pay_session_id,'iat':iat,'exp': exp, 'jti':jti,'sig':jwtSig}, self.private_key, algorithm='RS512')
privKeyObj = RSA.importKey(self.private_key)
signer = PKCS1_v1_5.new(privKeyObj)
signature = signer.sign(encoded)
return signature
def genPOSTJwtToken(self, uristring, bodystring, jti):
jwtSig = self.genPOSTSig(uristring, bodystring)
iat = datetime.datetime.utcnow()
exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=200)
encoded = jwt.encode({'uid':self.client_id, 'sid':self.pay_session_id,'iat':iat,'exp': exp, 'jti':jti,'sig':jwtSig}, self.private_key, algorithm='RS512')
return encoded
def genEncrypedPin(self, iterString = None):
if self.keyForAES == "":
privKeyObj = RSA.importKey(self.private_key)
decoded_result = base64.b64decode(self.pin_token)
cipher = PKCS1_OAEP.new(key=privKeyObj, hashAlgo=Crypto.Hash.SHA256, label=self.pay_session_id.encode("utf-8"))
decrypted_msg = cipher.decrypt(decoded_result)
self.keyForAES = decrypted_msg
ts = int(time.time())
tszero = ts % 0x100
tsone = (ts % 0x10000) >> 8
tstwo = (ts % 0x1000000) >> 16
tsthree = (ts % 0x100000000) >> 24
tszero = chr(tszero).encode('latin1').decode('latin1')
tsone = chr(tsone)
tstwo = chr(tstwo)
tsthree = chr(tsthree)
tsstring = tszero + tsone + tstwo + tsthree + '\0\0\0\0'
if iterString is None:
ts = int(time.time() * 100000)
tszero = ts % 0x100
tsone = (ts % 0x10000) >> 8
tstwo = (ts % 0x1000000) >> 16
tsthree = (ts % 0x100000000) >> 24
tsfour= (ts % 0x10000000000) >> 32
tsfive= (ts % 0x10000000000) >> 40
tssix = (ts % 0x1000000000000) >> 48
tsseven= (ts % 0x1000000000000) >> 56
tszero = chr(tszero).encode('latin1').decode('latin1')
tsone = chr(tsone)
tstwo = chr(tstwo)
tsthree = chr(tsthree)
tsfour = chr(tsfour)
tsfive= chr(tsfive)
tssix = chr(tssix)
tsseven = chr(tsseven)
iterStringByTS = tszero + tsone + tstwo + tsthree + tsfour + tsfive + tssix + tsseven
toEncryptContent = self.pay_pin + tsstring + iterStringByTS
else:
toEncryptContent = self.pay_pin + tsstring + iterString
lenOfToEncryptContent = len(toEncryptContent)
toPadCount = 16 - lenOfToEncryptContent % 16
if toPadCount > 0:
paddedContent = toEncryptContent + chr(toPadCount) * toPadCount
else:
paddedContent = toEncryptContent
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.keyForAES, AES.MODE_CBC,iv)
encrypted_result = cipher.encrypt(paddedContent.encode('latin1'))
msg = iv + encrypted_result
encrypted_pin = base64.b64encode(msg)
return encrypted_pin
"""
COMMON METHON
"""
"""
generate API url
"""
def __genUrl(self, path):
return self.api_base_url + path
"""
generate GET http request
"""
def __genGetRequest(self, path, auth_token=""):
url = self.__genUrl(path)
if auth_token == "":
r = requests.get(url)
else:
r = requests.get(url, headers={"Authorization": "Bearer " + auth_token})
result_obj = r.json()
print(result_obj)
return result_obj['data']
"""
generate POST http request
"""
def __genPostRequest(self, path, body, auth_token=""):
# generate url
url = self.__genUrl(path)
# transfer obj => json string
body_in_json = json.dumps(body)
if auth_token == "":
r = requests.post(url, json=body_in_json)
else:
r = requests.post(url, json=body_in_json, headers={"Authorization": "Bearer " + auth_token})
result_obj = r.json()
print(result_obj)
return result_obj
"""
generate Mixin Network GET http request
"""
def __genNetworkGetRequest(self, path, body=None, auth_token=""):
url = self.__genUrl(path)
if body is not None:
body = urlencode(body)
else:
body = ""
if auth_token == "":
token = self.genGETJwtToken(path, body, str(uuid.uuid4()))
auth_token = token.decode('utf8')
r = requests.get(url, headers={"Authorization": "Bearer " + auth_token})
result_obj = r.json()
return result_obj
"""
generate Mixin Network POST http request
"""
# TODO: request
def __genNetworkPostRequest(self, path, body, auth_token=""):
# transfer obj => json string
body_in_json = json.dumps(body)
# generate robot's auth token
if auth_token == "":
token = self.genPOSTJwtToken(path, body_in_json, str(uuid.uuid4()))
auth_token = token.decode('utf8')
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer ' + auth_token,
}
# generate url
url = self.__genUrl(path)
r = requests.post(url, json=body, headers=headers)
# {'error': {'status': 202, 'code': 20118, 'description': 'Invalid PIN format.'}}
# r = requests.post(url, data=body, headers=headers)
# {'error': {'status': 202, 'code': 401, 'description': 'Unauthorized, maybe invalid token.'}}
result_obj = r.json()
print(result_obj)
return result_obj
"""
============
MESSENGER PRIVATE APIs
============
auth token need request 'https://api.mixin.one/me' to get.
"""
"""
Read user's all assets.
"""
def getMyAssets(self, auth_token=""):
return self.__genGetRequest('/assets', auth_token)
"""
Read self profile.
"""
def getMyProfile(self, auth_token):
return self.__genGetRequest('/me', auth_token)
"""
?
Update my preferences.
"""
def updateMyPerference(self,receive_message_source="EVERYBODY",accept_conversation_source="EVERYBODY"):
body = {
"receive_message_source": receive_message_source,
"accept_conversation_source": accept_conversation_source
}
return self.__genPostRequest('/me/preferences', body)
"""
?
Update my profile.
"""
def updateMyProfile(self, full_name, auth_token, avatar_base64=""):
body = {
"full_name": full_name,
"avatar_base64": avatar_base64
}
return self.__genPostRequest('/me', body, auth_token)
"""
Get users information by IDs.
"""
def getUsersInfo(self, user_ids, auth_token):
return self.__genPostRequest('/users/fetch', user_ids, auth_token)
"""
Get user's information by ID.
"""
def getUserInfo(self, user_id, auth_token):
return self.__genGetRequest('/users/' + user_id, auth_token)
"""
Search user by Mixin ID or Phone Number.
"""
def SearchUser(self, q, auth_token=""):
return self.__genGetRequest('/search/' + q, auth_token)
"""
Rotate user’s code_id.
"""
def rotateUserQR(self, auth_token):
return self.__genGetRequest('/me/code', auth_token)
"""
Get my friends.
"""
def getMyFriends(self, auth_token):
return self.__genGetRequest('/friends', auth_token)
"""
Create a GROUP or CONTACT conversation.
"""
def createConv(self, category, conversation_id, participants, action, role, user_id, auth_token):
body = {
"category": category,
"conversation_id": conversation_id,
"participants": participants,
"action": action,
"role": role,
"user_id": user_id
}
return self.__genPostRequest('/conversations', body, auth_token)
"""
Read conversation by conversation_id.
"""
def getConv(self, conversation_id, auth_token):
return self.__genGetRequest('/conversations/' + conversation_id, auth_token)
"""
============
NETWORK PRIVATE APIs
============
auth token need robot related param to generate.
"""
"""
PIN is used to manage user’s addresses, assets and etc. There’s no default PIN for a Mixin Network user (except APP).
if auth_token is empty, it create robot' pin.
if auth_token is set, it create messenger user pin.
"""
def updatePin(self, new_pin, old_pin, auth_token=""):
old_inside_pay_pin = self.pay_pin
self.pay_pin = new_pin
newEncrypedPin = self.genEncrypedPin()
if old_pin == "":
body = {
"old_pin": "",
"pin": newEncrypedPin.decode()
}
else:
self.pay_pin = old_pin
oldEncryptedPin = self.genEncrypedPin()
body = {
"old_pin": oldEncryptedPin.decode(),
"pin": newEncrypedPin.decode()
}
self.pay_pin = old_inside_pay_pin
return self.__genNetworkPostRequest('/pin/update', body, auth_token)
"""
Verify PIN if is valid or not. For example, you can verify PIN before updating it.
if auth_token is empty, it verify robot' pin.
if auth_token is set, it verify messenger user pin.
"""
def verifyPin(self, auth_token=""):
enPin = self.genEncrypedPin()
body = {
"pin": enPin.decode()
}
return self.__genNetworkPostRequest('/pin/verify', body, auth_token)
"""
Grant an asset's deposit address, usually it is public_key, but account_name and account_tag is used for EOS.
"""
def deposit(self, asset_id):
return self.__genNetworkGetRequest(' /assets/' + asset_id)
"""
withdrawals robot asset to address_id
Tips:Get assets out of Mixin Network, neet to create an address for withdrawal.
"""
def withdrawals(self, address_id, amount, memo, trace_id=""):
encrypted_pin = self.genEncrypedPin()
if trace_id == "":
trace_id = str(uuid.uuid1())
body = {
"address_id": address_id,
"pin": encrypted_pin,
"amount": amount,
"trace_id": trace_id,
"memo": memo
}
return self.__genNetworkPostRequest('/withdrawals/', body)
"""
Create an address for withdrawal, you can only withdraw through an existent address.
"""
def createAddress(self, asset_id, public_key = "", label = "", account_name = "", account_tag = ""):
body = {
"asset_id": asset_id,
"pin": self.genEncrypedPin().decode(),
"public_key": public_key,
"label": label,
"account_name": account_name,
"account_tag": account_tag,
}
return self.__genNetworkPostRequest('/addresses', body)
"""
Delete an address by ID.
"""
def delAddress(self, address_id):
encrypted_pin = self.genEncrypedPin().decode()
body = {"pin": encrypted_pin}
return self.__genNetworkPostRequest('/addresses/' + address_id + '/delete', body)
"""
Read an address by ID.
"""
def getAddress(self, address_id):
return self.__genNetworkGetRequest('/addresses/' + address_id)
"""
Transfer of assets between Mixin Network users.
"""
def transferTo(self, to_user_id, to_asset_id, to_asset_amount, memo, trace_uuid=""):
# generate encrypted pin
encrypted_pin = self.genEncrypedPin()
body = {'asset_id': to_asset_id, 'counter_user_id': to_user_id, 'amount': str(to_asset_amount),
'pin': encrypted_pin.decode('utf8'), 'trace_id': trace_uuid, 'memo': memo}
if trace_uuid == "":
body['trace_id'] = str(uuid.uuid1())
return self.__genNetworkPostRequest('/transfers', body)
"""
Read transfer by trace ID.
"""
def getTransfer(self, trace_id):
return self.__genNetworkGetRequest('/transfers/trace/' + trace_id)
"""
Verify a transfer, payment status if it is 'paid' or 'pending'.
"""
def verifyPayment(self, asset_id, opponent_id, amount, trace_id):
body = {
"asset_id": asset_id,
"opponent_id": opponent_id,
"amount": amount,
"trace_id": trace_id
}
return self.__genNetworkPostRequest('/payments', body)
"""
Read asset by asset ID.
"""
def getAsset(self, asset_id):
return self.__genNetworkGetRequest('/assets/' + asset_id)
"""
Read external transactions (pending deposits) by public_key and asset_id, use account_tag for EOS.
"""
def extTrans(self, asset_id, public_key, account_tag, account_name, limit, offset):
body = {
"asset": asset_id,
"public_key": public_key,
"account_tag": account_tag,
"account_name": account_name,
"limit": limit,
"offset": offset
}
return self.__genNetworkGetRequest('/external/transactions', body)
"""
Create a new Mixin Network user (like a normal Mixin Messenger user). You should keep PrivateKey which is used to sign an AuthenticationToken and encrypted PIN for the user.
"""
def createUser(self, session_secret, full_name):
body = {
"session_secret": session_secret,
"full_name": full_name
}
return self.__genNetworkPostRequest('/users', body)
"""
===========
NETWORK PUBLIC APIs
===========
"""
"""
Read top valuable assets of Mixin Network.
"""
def topAssets(self):
return self.__genGetRequest('/network')
"""
Read public snapshots of Mixin Network.
"""
def snapshots(self, offset, asset_id, order='DESC',limit=100):
# TODO: SET offset default(UTC TIME)
body = {
"limit":limit,
"offset":offset,
"asset":asset_id,
"order":order
}
return self.__genGetRequest('/network/snapshots', body)
"""
Read public snapshots of Mixin Network by ID.
"""
def snapshot(self, snapshot_id):
return self.__genGetRequest('/network/snapshots/' + snapshot_id)