-
Notifications
You must be signed in to change notification settings - Fork 16
/
payer.go
305 lines (265 loc) · 7.67 KB
/
payer.go
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
package payouts
import (
"fmt"
"log"
"math/big"
"os"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/etclabscore/core-pool/rpc"
"github.com/etclabscore/core-pool/storage"
"github.com/etclabscore/core-pool/util"
)
const txCheckInterval = 5 * time.Second
type PayoutsConfig struct {
Enabled bool `json:"enabled"`
RequirePeers int64 `json:"requirePeers"`
Interval string `json:"interval"`
Daemon string `json:"daemon"`
Timeout string `json:"timeout"`
Address string `json:"address"`
Gas string `json:"gas"`
GasPrice string `json:"gasPrice"`
AutoGas bool `json:"autoGas"`
// In Shannon
Threshold int64 `json:"threshold"`
BgSave bool `json:"bgsave"`
}
func (self PayoutsConfig) GasHex() string {
x := util.String2Big(self.Gas)
return hexutil.EncodeBig(x)
}
func (self PayoutsConfig) GasPriceHex() string {
x := util.String2Big(self.GasPrice)
return hexutil.EncodeBig(x)
}
type PayoutsProcessor struct {
config *PayoutsConfig
backend *storage.RedisClient
rpc *rpc.RPCClient
halt bool
lastFail error
}
func NewPayoutsProcessor(cfg *PayoutsConfig, backend *storage.RedisClient) *PayoutsProcessor {
u := &PayoutsProcessor{config: cfg, backend: backend}
u.rpc = rpc.NewRPCClient("PayoutsProcessor", cfg.Daemon, cfg.Timeout)
return u
}
func (u *PayoutsProcessor) Start() {
log.Println("Starting payouts")
if u.mustResolvePayout() {
log.Println("Running with env RESOLVE_PAYOUT=1, now trying to resolve locked payouts")
u.resolvePayouts()
log.Println("Now you have to restart payouts module with RESOLVE_PAYOUT=0 for normal run")
return
}
intv := util.MustParseDuration(u.config.Interval)
timer := time.NewTimer(intv)
log.Printf("Set payouts interval to %v", intv)
payments := u.backend.GetPendingPayments()
if len(payments) > 0 {
log.Printf("Previous payout failed, you have to resolve it. List of failed payments:\n %v",
formatPendingPayments(payments))
return
}
locked, err := u.backend.IsPayoutsLocked()
if err != nil {
log.Println("Unable to start payouts:", err)
return
}
if locked {
log.Println("Unable to start payouts because they are locked")
return
}
// Immediately process payouts after start
u.process()
timer.Reset(intv)
go func() {
for {
select {
case <-timer.C:
u.process()
timer.Reset(intv)
}
}
}()
}
func (u *PayoutsProcessor) process() {
if u.halt {
log.Println("Payments suspended due to last critical error:", u.lastFail)
return
}
mustPay := 0
minersPaid := 0
totalAmount := big.NewInt(0)
payees, err := u.backend.GetPayees()
if err != nil {
log.Println("Error while retrieving payees from backend:", err)
return
}
for _, login := range payees {
amount, _ := u.backend.GetBalance(login)
amountInShannon := big.NewInt(amount)
// Shannon^2 = Wei
amountInWei := new(big.Int).Mul(amountInShannon, util.Shannon)
if !u.reachedThreshold(amountInShannon) {
continue
}
mustPay++
// Require active peers before processing
if !u.checkPeers() {
break
}
// Require unlocked account
if !u.isUnlockedAccount() {
break
}
// Check if we have enough funds
poolBalance, err := u.rpc.GetBalance(u.config.Address)
if err != nil {
u.halt = true
u.lastFail = err
break
}
if poolBalance.Cmp(amountInWei) < 0 {
err := fmt.Errorf("Not enough balance for payment, need %s Wei, pool has %s Wei",
amountInWei.String(), poolBalance.String())
u.halt = true
u.lastFail = err
break
}
// Lock payments for current payout
err = u.backend.LockPayouts(login, amount)
if err != nil {
log.Printf("Failed to lock payment for %s: %v", login, err)
u.halt = true
u.lastFail = err
break
}
log.Printf("Locked payment for %s, %v Shannon", login, amount)
// Debit miner's balance and update stats
err = u.backend.UpdateBalance(login, amount)
if err != nil {
log.Printf("Failed to update balance for %s, %v Shannon: %v", login, amount, err)
u.halt = true
u.lastFail = err
break
}
value := hexutil.EncodeBig(amountInWei)
txHash, err := u.rpc.SendTransaction(u.config.Address, login, u.config.GasHex(), u.config.GasPriceHex(), value, u.config.AutoGas)
if err != nil {
log.Printf("Failed to send payment to %s, %v Shannon: %v. Check outgoing tx for %s in block explorer and docs/PAYOUTS.md",
login, amount, err, login)
u.halt = true
u.lastFail = err
break
}
// Log transaction hash
err = u.backend.WritePayment(login, txHash, amount)
if err != nil {
log.Printf("Failed to log payment data for %s, %v Shannon, tx: %s: %v", login, amount, txHash, err)
u.halt = true
u.lastFail = err
break
}
minersPaid++
totalAmount.Add(totalAmount, big.NewInt(amount))
log.Printf("Paid %v Shannon to %v, TxHash: %v", amount, login, txHash)
// Wait for TX confirmation before further payouts
for {
log.Printf("Waiting for tx confirmation: %v", txHash)
time.Sleep(txCheckInterval)
receipt, err := u.rpc.GetTxReceipt(txHash)
if err != nil {
log.Printf("Failed to get tx receipt for %v: %v", txHash, err)
continue
}
// Tx has been mined
if receipt != nil && receipt.Confirmed() {
if receipt.Successful() {
log.Printf("Payout tx successful for %s: %s", login, txHash)
} else {
log.Printf("Payout tx failed for %s: %s. Address contract throws on incoming tx.", login, txHash)
}
break
}
}
}
if mustPay > 0 {
log.Printf("Paid total %v Shannon to %v of %v payees", totalAmount, minersPaid, mustPay)
} else {
log.Println("No payees that have reached payout threshold")
}
// Save redis state to disk
if minersPaid > 0 && u.config.BgSave {
u.bgSave()
}
}
func (self PayoutsProcessor) isUnlockedAccount() bool {
_, err := self.rpc.Sign(self.config.Address, "0x0")
if err != nil {
log.Println("Unable to process payouts:", err)
return false
}
return true
}
func (self PayoutsProcessor) checkPeers() bool {
n, err := self.rpc.GetPeerCount()
if err != nil {
log.Println("Unable to start payouts, failed to retrieve number of peers from node:", err)
return false
}
if n < self.config.RequirePeers {
log.Println("Unable to start payouts, number of peers on a node is less than required", self.config.RequirePeers)
return false
}
return true
}
func (self PayoutsProcessor) reachedThreshold(amount *big.Int) bool {
return big.NewInt(self.config.Threshold).Cmp(amount) < 0
}
func formatPendingPayments(list []*storage.PendingPayment) string {
var s string
for _, v := range list {
s += fmt.Sprintf("\tAddress: %s, Amount: %v Shannon, %v\n", v.Address, v.Amount, time.Unix(v.Timestamp, 0))
}
return s
}
func (self PayoutsProcessor) bgSave() {
result, err := self.backend.BgSave()
if err != nil {
log.Println("Failed to perform BGSAVE on backend:", err)
return
}
log.Println("Saving backend state to disk:", result)
}
func (self PayoutsProcessor) resolvePayouts() {
payments := self.backend.GetPendingPayments()
if len(payments) > 0 {
log.Printf("Will credit back following balances:\n%s", formatPendingPayments(payments))
for _, v := range payments {
err := self.backend.RollbackBalance(v.Address, v.Amount)
if err != nil {
log.Printf("Failed to credit %v Shannon back to %s, error is: %v", v.Amount, v.Address, err)
return
}
log.Printf("Credited %v Shannon back to %s", v.Amount, v.Address)
}
err := self.backend.UnlockPayouts()
if err != nil {
log.Println("Failed to unlock payouts:", err)
return
}
} else {
log.Println("No pending payments to resolve")
}
if self.config.BgSave {
self.bgSave()
}
log.Println("Payouts unlocked")
}
func (self PayoutsProcessor) mustResolvePayout() bool {
v, _ := strconv.ParseBool(os.Getenv("RESOLVE_PAYOUT"))
return v
}