forked from breez/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transactions.go
315 lines (292 loc) · 8.62 KB
/
transactions.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
306
307
308
309
310
311
312
313
314
315
package main
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"strconv"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/gomodule/redigo/redis"
"github.com/lightningnetwork/lnd/lnrpc"
"golang.org/x/sync/singleflight"
)
const (
receivePaymentType = "receivePayment"
channelOpenedType = "channelOpened"
transactionNotificationExpiry = 3600 * 6
)
var (
txGroup singleflight.Group
txNotificationGroup singleflight.Group
notificationTypes = map[string]map[string]string{
receivePaymentType: map[string]string{
"title": "Receive Payment",
"body": "You are now ready to receive payments using Breez. Open to continue with a previously shared payment link.",
},
channelOpenedType: map[string]string{
"title": "Breez",
"body": "You can now use Breez to send and receive Bitcoin payments!",
},
}
)
func handlePastTransactions(ctx context.Context, c lnrpc.LightningClient) error {
transactionDetails, err := c.GetTransactions(ctx, &lnrpc.GetTransactionsRequest{})
if err != nil {
log.Println("handlePastTransactions error:", err)
return err
}
for _, t := range transactionDetails.Transactions {
key := t.TxHash
if t.NumConfirmations == 0 {
key = key + "-unconfirmed"
} else {
key = key + "-confirmed"
}
_, err, _ = txGroup.Do(key, func() (interface{}, error) {
err := handleTransaction(t)
return nil, err
})
if err != nil {
log.Println("handleTransaction error:", err)
}
}
return nil
}
func subscribeTransactions(ctx context.Context, c lnrpc.LightningClient) {
for {
log.Println("new subscribe")
err := subscribeTransactionsOnce(ctx, c)
if err != nil {
log.Println("subscribeTransactions:", err)
}
time.Sleep(5 * time.Second)
}
}
func destAddresses(tx *lnrpc.Transaction) ([]string, error) {
if len(tx.DestAddresses) > 0 {
return tx.DestAddresses, nil
}
if tx.RawTxHex == "" {
return nil, nil
}
rawTx, err := hex.DecodeString(tx.RawTxHex)
if err != nil {
return nil, err
}
wireTx := &wire.MsgTx{}
txReader := bytes.NewReader(rawTx)
if err := wireTx.Deserialize(txReader); err != nil {
return nil, err
}
var destAddresses []btcutil.Address
chainParams := &chaincfg.MainNetParams
for _, txOut := range wireTx.TxOut {
_, outAddresses, _, err :=
txscript.ExtractPkScriptAddrs(txOut.PkScript, chainParams)
if err != nil {
return nil, err
}
destAddresses = append(destAddresses, outAddresses...)
}
dest := make([]string, 0, len(destAddresses))
for _, destAddress := range destAddresses {
dest = append(dest, destAddress.EncodeAddress())
}
return dest, nil
}
func subscribeTransactionsOnce(ctx context.Context, c lnrpc.LightningClient) error {
transactionStream, err := c.SubscribeTransactions(ctx, &lnrpc.GetTransactionsRequest{})
if err != nil {
log.Println("SubscribeTransactions:", err)
return err
}
for {
log.Println("new Recv call")
t, err := transactionStream.Recv()
if err == io.EOF {
log.Println("Stream stopped. Need to re-registser")
break
}
if err != nil {
log.Printf("Error in stream: %v", err)
return err
}
//log.Printf("t:%#v", t)
t.DestAddresses, err = destAddresses(t)
if err != nil {
log.Printf("transactionStream - Error in destAddresses: %v", err)
}
key := t.TxHash
if t.NumConfirmations == 0 {
key = key + "-unconfirmed"
} else {
key = key + "-confirmed"
}
_, err, _ = txGroup.Do(key, func() (interface{}, error) {
err := handleTransaction(t)
return nil, err
})
if err != nil {
log.Println("handleTransaction error:", err)
}
}
return nil
}
func handleTransaction(tx *lnrpc.Transaction) error {
if err := handleTransactionNotifications(tx); err != nil {
log.Println("handleTransactionNotifications error:", err)
return err
}
return handleTransactionAddreses(tx)
}
func registerTransacionConfirmation(txID, token, notifyType string) error {
redisConn := redisPool.Get()
defer redisConn.Close()
registrationKey := fmt.Sprintf("tx-notify-%v", txID)
registrationData := map[string]string{"token": token, "type": notifyType}
marshalled, err := json.Marshal(registrationData)
if err != nil {
return err
}
_, err = redisConn.Do("SADD", registrationKey, string(marshalled))
if err != nil {
return err
}
err = setKeyExpiration(registrationKey, transactionNotificationExpiry)
return err
}
func handleTransactionNotifications(tx *lnrpc.Transaction) error {
if tx.NumConfirmations == 0 {
return nil
}
registrationKey := fmt.Sprintf("tx-notify-%v", tx.TxHash)
redisConn := redisPool.Get()
defer redisConn.Close()
for {
registrations, err := redis.Strings(redisConn.Do("SPOP", registrationKey, 10))
if err != nil {
return err
}
for _, r := range registrations {
var regData map[string]string
if err = json.Unmarshal([]byte(r), ®Data); err != nil {
log.Printf("Failed to decode json registration %v", r)
continue
}
notificationType := regData["type"]
notificationToken := regData["token"]
go func() {
err := notifyAlertMessage(
notificationTypes[notificationType]["title"],
notificationTypes[notificationType]["body"],
map[string]string{}, notificationToken)
if err != nil {
log.Printf("Error sending transaction confirmation %v", err)
}
}()
}
if len(registrations) < 10 {
break
}
}
return nil
}
func handleTransactionAddreses(tx *lnrpc.Transaction) error {
//log.Printf("t:%#v", tx)
redisConn := redisPool.Get()
defer redisConn.Close()
for i, a := range tx.DestAddresses {
n, err := redis.Int(redisConn.Do("SISMEMBER", "fund-addresses", a))
if err != nil {
log.Println("handleTransaction error:", err)
return err
}
if n > 0 {
if tx.NumConfirmations > 0 {
err = handleTransactionAddress(tx, i)
if err != nil {
return err
}
go notifyClientTransaction(tx, i, "Action Required", "Breez", "Received funds are now confirmed. Please open the app to complete your transaction.", true)
break // There is only one address concerning us per transaction
} else {
redisConn := redisPool.Get()
defer redisConn.Close()
_, err := redisConn.Do("HMSET", "input-address:"+tx.DestAddresses[i],
"utx:TxHash", tx.TxHash,
"utx:Amount", tx.Amount,
)
if err != nil {
log.Println("handleTransactionAddreses error:", err)
return err
}
amt := strconv.FormatInt(tx.Amount, 10)
go notifyClientTransaction(tx, i, "Unconfirmed transaction", "Breez", "Breez is waiting for "+amt+" sat to be confirmed.", false)
break
}
}
}
return nil
}
func notifyClientTransaction(tx *lnrpc.Transaction, index int, msg, title, body string, delete bool) {
key := tx.TxHash + "-notification"
_, _, _ = txNotificationGroup.Do(key, func() (interface{}, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
tokens, err := redis.Strings(redisConn.Do("SMEMBERS", "input-address-notification:"+tx.DestAddresses[index]))
if err != nil {
log.Println("notifyUnconfirmed error:", err)
return nil, nil
}
data := map[string]string{
"msg": msg,
"tx": tx.TxHash,
"address": tx.DestAddresses[index],
"value": strconv.FormatInt(tx.Amount, 10),
}
for _, tok := range tokens {
err = notifyAlertMessage(title, body, data, tok)
log.Println("Error in send:", err)
unregistered := err != nil && isUnregisteredError(err)
if unregistered || delete {
_, err = redisConn.Do("SREM", "input-address-notification:"+tx.DestAddresses[index], tok)
if err != nil {
log.Printf("Error in notifyClientTransaction (SREM); set:%v member:%v error:%v", "input-address-notification:"+tx.DestAddresses[index], tok, err)
}
card, err := redis.Int(redisConn.Do("SCARD", "input-address-notification:"+tx.DestAddresses[index]))
if err != nil {
log.Printf("Error in notifyClientTransaction (SCARD); set:%v error:%v", "input-address-notification:"+tx.DestAddresses[index], err)
} else {
if card == 0 {
_, err = redisConn.Do("DEL", "input-address-notification:"+tx.DestAddresses[index])
if err != nil {
log.Printf("Error in notifyClientTransaction (DEL); set:%v error:%v", "input-address-notification:"+tx.DestAddresses[index], err)
}
}
}
}
}
return nil, nil
})
}
func handleTransactionAddress(tx *lnrpc.Transaction, index int) error {
redisConn := redisPool.Get()
defer redisConn.Close()
_, err := redisConn.Do("HMSET", "input-address:"+tx.DestAddresses[index],
"tx:TxHash", tx.TxHash,
"tx:Amount", tx.Amount,
"tx:BlockHash", tx.BlockHash,
)
if err != nil {
log.Println("handleTransactionAddress error:", err)
return err
}
return nil
}