-
Notifications
You must be signed in to change notification settings - Fork 10
/
pi_python.py
252 lines (205 loc) · 8.31 KB
/
pi_python.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
# -*- coding: utf-8 -*-
"""
For more information visit https://github.com/pi-apps/pi-python
"""
import requests
import json
import stellar_sdk as s_sdk
class PiNetwork:
api_key = ""
client = ""
account = ""
base_url = ""
from_address = ""
open_payments = {}
network = ""
server = ""
keypair = ""
fee = ""
def initialize(self, api_key, wallet_private_key, network):
try:
if not self.validate_private_seed_format(wallet_private_key):
print("No valid private seed!")
self.api_key = api_key
self.load_account(wallet_private_key, network)
self.base_url = "https://api.minepi.com"
self.open_payments = {}
self.network = network
self.fee = self.server.fetch_base_fee()
#self.fee = fee
except:
return False
def get_balance(self):
try:
balances = self.server.accounts().account_id(self.keypair.public_key).call()["balances"]
balance_found = False
for i in balances:
if i["asset_type"] == "native":
return float(i["balance"])
return 0
except:
return 0
def get_payment(self, payment_id):
url = self.base_url + "/v2/payments/" + payment_id
re = requests.get(url,headers=self.get_http_headers())
self.handle_http_response(re)
def create_payment(self, payment_data):
try:
if not self.validate_payment_data(payment_data):
if __debug__:
print("No valid payments found. Creating a new one...")
balances = self.server.accounts().account_id(self.keypair.public_key).call()["balances"]
balance_found = False
for i in balances:
if i["asset_type"] == "native":
balance_found = True
if (float(payment_data["amount"]) + (float(self.fee) / 10000000)) > float(i["balance"]):
return ""
break
if balance_found == False:
return ""
obj = {
'payment': payment_data,
}
obj = json.dumps(obj)
url = self.base_url + "/v2/payments"
res = requests.post(url, data=obj, json=obj, headers=self.get_http_headers())
parsed_response = self.handle_http_response(res)
identifier = ""
identifier_data = {}
if 'error' in parsed_response:
identifier = parsed_response['payment']["identifier"]
identifier_data = parsed_response['payment']
else:
identifier = parsed_response["identifier"]
identifier_data = parsed_response
self.open_payments[identifier] = identifier_data
return identifier
except:
return ""
def submit_payment(self, payment_id, pending_payment):
if payment_id not in self.open_payments:
return False
if pending_payment == False or payment_id in self.open_payments:
payment = self.open_payments[payment_id]
else:
payment = pending_payment
balances = self.server.accounts().account_id(self.keypair.public_key).call()["balances"]
balance_found = False
for i in balances:
if i["asset_type"] == "native":
balance_found = True
if (float(payment["amount"]) + (float(self.fee)/10000000)) > float(i["balance"]):
return ""
break
if balance_found == False:
return ""
if __debug__:
print("Debug_Data: Payment information\n" + str(payment))
self.set_horizon_client(payment["network"])
from_address = payment["from_address"]
transaction_data = {
"amount": payment["amount"],
"identifier": payment["identifier"],
"recipient": payment["to_address"]
}
transaction = self.build_a2u_transaction(payment)
txid = self.submit_transaction(transaction)
if payment_id in self.open_payments:
del self.open_payments[payment_id]
return txid
def complete_payment(self, identifier, txid):
if not txid:
obj = {}
else:
obj = {"txid": txid}
obj = json.dumps(obj)
url = self.base_url + "/v2/payments/" + identifier + "/complete"
re = requests.post(url,data=obj,json=obj,headers=self.get_http_headers())
self.handle_http_response(re)
def cancel_payment(self, identifier):
obj = {}
obj = json.dumps(obj)
url = self.base_url + "/v2/payments/" + identifier + "/cancel"
re = requests.post(url,data=obj,json=obj,headers=self.get_http_headers())
self.handle_http_response(re)
def get_incomplete_server_payments(self):
url = self.base_url + "/v2/payments/incomplete_server_payments"
re = requests.get(url,headers=self.get_http_headers())
res = self.handle_http_response(re)
if not res:
res = {"incomplete_server_payments": []}
return res["incomplete_server_payments"]
def get_http_headers(self):
return {'Authorization': "Key " + self.api_key, "Content-Type": "application/json"}
def handle_http_response(self, re):
try:
result = re.json()
result_dict = json.loads(str(json.dumps(result)))
if __debug__:
print("HTTP-Response: " + str(re))
print("HTTP-Response Data: " + str(result_dict))
return result_dict
except:
return False
def set_horizon_client(self, network):
self.client = self.server
pass
def load_account(self, private_seed, network):
self.keypair = s_sdk.Keypair.from_secret(private_seed)
if network == "Pi Network":
host = "api.mainnet.minepi.com"
horizon = "https://api.mainnet.minepi.com"
else:
host = "api.testnet.minepi.com"
horizon = "https://api.testnet.minepi.com"
self.server = s_sdk.Server(horizon)
self.account = self.server.load_account(self.keypair.public_key)
def build_a2u_transaction(self, transaction_data):
if not self.validate_payment_data(transaction_data):
print("No valid transaction!")
amount = str(transaction_data["amount"])
# TODO: get this from horizon
fee = self.fee # 100000 # 0.01π
to_address = transaction_data["to_address"]
memo = transaction_data["identifier"]
if __debug__:
print("MEMO " + str(memo))
from_address = transaction_data["from_address"]
transaction = (
s_sdk.TransactionBuilder(
source_account=self.account,
network_passphrase=self.network,
base_fee=fee,
)
.add_text_memo(memo)
.append_payment_op(to_address, s_sdk.Asset.native(), amount)
.set_timeout(180)
.build()
)
return transaction
def submit_transaction(self, transaction):
transaction.sign(self.keypair)
response = self.server.submit_transaction(transaction)
txid = response["id"]
return txid
def validate_payment_data(self, data):
if "amount" not in data:
return False
elif "memo" not in data:
return False
elif "metadata" not in data:
return False
elif "user_uid" not in data:
return False
elif "identifier" not in data:
return False
elif "to_address" not in data:
return False
return True
def validate_private_seed_format(self, seed):
if not seed.upper().startswith("S"):
return False
elif len(seed) != 56:
return False
return True