forked from tigwyk/accept-banano
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (158 loc) · 4.54 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/tigwyk/accept-banano/internal/hub"
"github.com/tigwyk/accept-banano/internal/banano"
"github.com/tigwyk/accept-banano/internal/price"
"github.com/tigwyk/accept-banano/internal/subscriber"
"github.com/cenkalti/log"
"github.com/ulule/limiter/v3"
"github.com/ulule/limiter/v3/drivers/store/memory"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// These variables are set by goreleaser on build.
var (
version = "0.0.0"
commit = ""
date = ""
)
var (
generateSeed = flag.Bool("seed", false, "generate a seed and exit")
configPath = flag.String("config", "config.toml", "config file path")
versionFlag = flag.Bool("version", false, "display version and exit")
config Config
userclient *mongo.Client
collection *mongo.Collection
server http.Server
rateLimiter *limiter.Limiter
node *banano.Node
worknode *banano.Node
stopCheckPayments = make(chan struct{})
checkPaymentWG sync.WaitGroup
verifications hub.Hub
priceAPI *price.API
subs *subscriber.Subscriber
)
func versionString() string {
const shaLen = 7
if len(commit) > shaLen {
commit = commit[:shaLen]
}
return fmt.Sprintf("%s (%s) [%s]", version, commit, date)
}
func ConnectMongoDB() (*mongo.Client, error) {
if config.MongoDBConnectURI == "" {
return nil, fmt.Errorf("no connection string provided in config")
}
log.Debugln("Connecting to DB")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// user Connection database
// Set client options
clientOptions := options.Client().ApplyURI(config.MongoDBConnectURI)
// Connect to MongoDB
userclient, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return nil, err
}
// Check the connection
err = userclient.Ping(ctx, nil)
if err != nil {
return nil, err
}
log.Debugln("Connected to user MongoDB!")
return userclient, err
}
func main() {
flag.Parse()
if *versionFlag {
fmt.Println(versionString())
return
}
if *generateSeed {
seed, err := NewSeed()
if err != nil {
log.Fatal(err)
}
fmt.Println(seed)
return
}
err := config.Read()
if err != nil {
log.Fatal(err)
}
if config.EnableDebugLog {
log.SetLevel(log.DEBUG)
}
if config.CoinmarketcapAPIKey == "" {
log.Warning("empty CoinmarketcapAPIKey in config, fiat conversions will not work")
}
userclient, err = ConnectMongoDB()
if err != nil {
log.Fatalln("error:", err)
return
}
collection = userclient.Database(config.PaymentsDBName).Collection(config.PaymentsCollectionName)
rate, err := limiter.NewRateFromFormatted(config.RateLimit)
if err != nil {
log.Fatal(err)
}
rateLimiter = limiter.New(memory.NewStore(), rate, limiter.WithTrustForwardHeader(true))
node = banano.New(config.NodeURL, config.NodeTimeout, config.NodeAuthorizationHeader)
if config.WorkNodeURL != "" {
worknode = banano.New(config.NodeURL, config.NodeTimeout, config.NodeAuthorizationHeader)
}
notificationClient.Timeout = config.NotificationRequestTimeout
priceAPI = price.NewAPI(config.CoinmarketcapAPIKey, config.CoinmarketcapRequestTimeout, config.CoinmarketcapCacheDuration)
// Check existing payments.
payments, err := LoadActivePayments()
if err != nil {
log.Fatal(err)
}
log.Debugln("Existing payments:", len(payments))
for _, p := range payments {
p.StartChecking()
}
if !config.DisableWebsocket && config.NodeWebsocketURL != "" {
subs = subscriber.New(config.NodeWebsocketURL, config.NodeWebsocketHandshakeTimeout, config.NodeWebsocketWriteTimeout, config.NodeWebsocketAckTimeout, config.NodeWebsocketKeepAlivePeriod)
go subs.Run()
go runChecker()
}
go runServer()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
close(stopCheckPayments)
shutdownTimeout := config.ShutdownTimeout
log.Noticeln("shutting down with timeout:", shutdownTimeout)
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
err = server.Shutdown(ctx)
if err != nil {
log.Errorln("shutdown error:", err)
}
checkPaymentWG.Wait()
}
func runChecker() {
for account := range subs.Confirmations {
p, err := LoadPayment(account)
if err == errPaymentNotFound {
continue
}
if err != nil {
log.Errorf("cannot load payment: %s", err.Error())
continue
}
log.Debugf("received confirmation from websocket, checking account: %s", account)
go p.checkOnce()
}
}