-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhodl_server.py
More file actions
executable file
·190 lines (155 loc) · 6.02 KB
/
hodl_server.py
File metadata and controls
executable file
·190 lines (155 loc) · 6.02 KB
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
#!/usr/bin/env python3
from flask import Flask, jsonify, abort, make_response, request, abort
from flask_restful import Api, Resource, reqparse, fields
import hodl_api
import requests
import json
import time
from math import log
from mq import to_queue, send_process_queues_signal
MIN_AMOUNT = 500
MAX_AMOUNT = 10000000
TOLERANCE_SEC = 43200
MAX_VEST_TIME = 120
MIN_VEST_TIME = 60
MIN_AMOUNT_SAT = MIN_AMOUNT * 100000000
MAX_AMOUNT_SAT = MAX_AMOUNT * 100000000
MAX_VEST_TIME_SEC = MAX_VEST_TIME * 86400
MIN_VEST_TIME_SEC = MIN_VEST_TIME * 86400
def REWARD_RATIO(time):
if time < 1: return(0)
percentage = 2.0197738315 * log(time/86400) - 7.26965
return(percentage * 0.01)
app = Flask(__name__, static_url_path="")
api = Api(app)
class Create(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('pubkey', type=str, location='json')
self.reqparse.add_argument('nlocktime', type=int, location='json')
super(Create, self).__init__()
def get(self, pubkey, nlocktime):
output = hodl_api.create_command(pubkey=pubkey, nLockTime=nlocktime)
return(output)
class Spend(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument(
'prevouts',
action='append',
type=str,
location='form'
)
super(Spend, self).__init__()
def post(self, pubkey, nlocktime):
args = self.reqparse.parse_args()
output = hodl_api.spend_command(
pubkey=pubkey,
nLockTime=nlocktime,
prevOuts=args['prevouts']
)
return(output)
def get(self, pubkey, nlocktime):
redeem_script = hodl_api.create_command(
pubkey=pubkey,
nLockTime=nlocktime
)
script_addr = redeem_script['address']
url = hodl_api.CoinParams.EXPLORER
url += '/insight-api-komodo/addr/' + script_addr + '/utxo'
utxos = []
try:
r = requests.get(
url,
headers={'Content-type': 'text/plain; charset=utf-8'})
utxos = json.loads(r.text)
except Exception as e:
print("Couldn't connect to " + url, e)
prevouts = []
for utxo in utxos:
vout = str(utxo['vout'])
prevouts.append(utxo['txid'] + ':' + vout)
output = hodl_api.spend_command(
pubkey=pubkey,
nLockTime=nlocktime,
prevOuts=prevouts
)
return(output)
class SubmitTx(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('rawtx', type=str, location='json')
super(SubmitTx, self).__init__()
def post(self):
args = self.reqparse.parse_args()
# analyze transaction
try:
analysis = hodl_api.analyze_tx(args['rawtx'])
except Exception as e:
error_msg = "couldn't analyze this transaction"
return({'error': error_msg, 'exception': str(e)})
# check if it complies with minimum allowed locked amount
if analysis['lockedSatoshis'] < MIN_AMOUNT_SAT:
error_msg = 'minimum amount is ' + str(MIN_AMOUNT)
return({'error': error_msg})
elif analysis['lockedSatoshis'] > MAX_AMOUNT_SAT:
error_msg = 'maximum amount is ' + str(MAX_AMOUNT)
return({'error': error_msg})
# check if tx is not trying to get rewards for less than
# the minimum allowed vesting period, or more than maximum
nLockTime = analysis['nLockTime']
now = int(time.time())
min_unlock_time = now + MIN_VEST_TIME_SEC
max_unlock_time = now + MAX_VEST_TIME_SEC
if nLockTime < (min_unlock_time - TOLERANCE_SEC):
error_msg = 'Code expired or vesting period is too short.'
return({'error': error_msg})
elif nLockTime > (max_unlock_time + MAX_VEST_TIME_SEC):
error_msg = "You're hodling yourself out of existence!"
return({'error': error_msg})
elif nLockTime > (max_unlock_time + TOLERANCE_SEC):
error_msg = 'Vesting period too long.'
return({'error': error_msg})
else:
try:
tx_broadcast_output = hodl_api.tx_broadcast(args['rawtx'])
if 'error' in tx_broadcast_output:
raise Exception("something wrong!")
except Exception as e:
print(e)
error_msg = ("There was a problem " +
"broadcasting this transaction.")
return({'error': error_msg})
else:
try:
payee_data = {}
payee_data['hodlFundTxId'] = tx_broadcast_output['txid']
payee_data['payeeAddress'] = analysis['hodlAddress']
payee_data['reward'] = int(
analysis['lockedSatoshis'] *
REWARD_RATIO(nLockTime - now))
to_queue(payee_data, 'transactions')
except Exception as e:
print(e)
error_msg = ("There was a problem " +
"scheduling reward payment, please report.")
return({'error': error_msg})
return(tx_broadcast_output)
class ProcessRewards(Resource):
def __init__(self):
super(ProcessRewards, self).__init__()
def get(self):
if request.remote_addr != '127.0.0.1':
abort(403)
try:
result = send_process_queues_signal()
return({"result": "success"})
except Exception as e:
print(e)
return({"result": "failure"})
api.add_resource(Create, '/create/<pubkey>/<int:nlocktime>')
api.add_resource(Spend, '/spend/<pubkey>/<int:nlocktime>')
api.add_resource(SubmitTx, '/submit-tx/')
api.add_resource(ProcessRewards, '/process-rewards/')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)