forked from getAlby/nostr-wallet-connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
230 lines (210 loc) · 6.57 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
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
package main
import (
"context"
"database/sql"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
echologrus "github.com/davrux/echo-logrus/v4"
"github.com/getAlby/nostr-wallet-connect/migrations"
"github.com/glebarez/sqlite"
"github.com/joho/godotenv"
"github.com/kelseyhightower/envconfig"
"github.com/labstack/echo/v4"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
log "github.com/sirupsen/logrus"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"github.com/jackc/pgx/v5/stdlib"
sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
gormtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gorm.io/gorm.v1"
)
func main() {
// Load config from environment variables / .env file
godotenv.Load(".env")
cfg := &Config{}
err := envconfig.Process("", cfg)
if err != nil {
log.Fatalf("Error loading environment variables: %v", err)
}
var db *gorm.DB
var sqlDb *sql.DB
if strings.HasPrefix(cfg.DatabaseUri, "postgres://") || strings.HasPrefix(cfg.DatabaseUri, "postgresql://") || strings.HasPrefix(cfg.DatabaseUri, "unix://") {
if os.Getenv("DATADOG_AGENT_URL") != "" {
sqltrace.Register("pgx", &stdlib.Driver{}, sqltrace.WithServiceName("nostr-wallet-connect"))
sqlDb, err = sqltrace.Open("pgx", cfg.DatabaseUri)
if err != nil {
log.Fatalf("Failed to open DB %v", err)
}
db, err = gormtrace.Open(postgres.New(postgres.Config{Conn: sqlDb}), &gorm.Config{}, gormtrace.WithServiceName("nostr-wallet-connect"))
if err != nil {
log.Fatalf("Failed to open DB %v", err)
}
} else {
db, err = gorm.Open(postgres.Open(cfg.DatabaseUri), &gorm.Config{})
if err != nil {
log.Fatalf("Failed to open DB %v", err)
}
sqlDb, err = db.DB()
if err != nil {
log.Fatalf("Failed to set DB config: %v", err)
}
}
} else {
db, err = gorm.Open(sqlite.Open(cfg.DatabaseUri), &gorm.Config{})
if err != nil {
log.Fatalf("Failed to open DB %v", err)
}
// Override SQLite config to max one connection
cfg.DatabaseMaxConns = 1
// Enable foreign keys for sqlite
db.Exec("PRAGMA foreign_keys=ON;")
sqlDb, err = db.DB()
if err != nil {
log.Fatalf("Failed to set DB config: %v", err)
}
}
sqlDb.SetMaxOpenConns(cfg.DatabaseMaxConns)
sqlDb.SetMaxIdleConns(cfg.DatabaseMaxIdleConns)
sqlDb.SetConnMaxLifetime(time.Duration(cfg.DatabaseConnMaxLifetime) * time.Second)
err = migrations.Migrate(db)
if err != nil {
log.Fatalf("Migration failed: %v", err)
}
log.Println("Any pending migrations ran successfully")
if cfg.NostrSecretKey == "" {
if cfg.LNBackendType == AlbyBackendType {
//not allowed
log.Fatal("Nostr private key is required with this backend type.")
}
//first look up if we already have the private key in the database
//else, generate and store private key
identity := &Identity{}
err = db.FirstOrInit(identity).Error
if err != nil {
log.WithError(err).Fatal("Error retrieving private key from database")
}
if identity.Privkey == "" {
log.Info("No private key found in database, generating & saving.")
identity.Privkey = nostr.GeneratePrivateKey()
err = db.Save(identity).Error
if err != nil {
log.WithError(err).Fatal("Error saving private key to database")
}
}
cfg.NostrSecretKey = identity.Privkey
}
identityPubkey, err := nostr.GetPublicKey(cfg.NostrSecretKey)
if err != nil {
log.Fatalf("Error converting nostr privkey to pubkey: %v", err)
}
cfg.IdentityPubkey = identityPubkey
npub, err := nip19.EncodePublicKey(identityPubkey)
if err != nil {
log.Fatalf("Error converting nostr privkey to pubkey: %v", err)
}
log.Infof("Starting nostr-wallet-connect. npub: %s hex: %s", npub, identityPubkey)
svc := &Service{
cfg: cfg,
db: db,
}
if os.Getenv("DATADOG_AGENT_URL") != "" {
tracer.Start(tracer.WithService("nostr-wallet-connect"))
defer tracer.Stop()
}
echologrus.Logger = log.New()
echologrus.Logger.SetFormatter(&log.JSONFormatter{})
echologrus.Logger.SetOutput(os.Stdout)
echologrus.Logger.SetLevel(log.InfoLevel)
svc.Logger = echologrus.Logger
e := echo.New()
ctx := context.Background()
ctx, _ = signal.NotifyContext(ctx, os.Interrupt)
var wg sync.WaitGroup
switch cfg.LNBackendType {
case LNDBackendType:
lndClient, err := NewLNDService(ctx, svc, e)
if err != nil {
svc.Logger.Fatal(err)
}
svc.lnClient = lndClient
case AlbyBackendType:
oauthService, err := NewAlbyOauthService(svc, e)
if err != nil {
svc.Logger.Fatal(err)
}
svc.lnClient = oauthService
}
//register shared routes
svc.RegisterSharedRoutes(e)
//start Echo server
wg.Add(1)
go func() {
if err := e.Start(fmt.Sprintf(":%v", svc.cfg.Port)); err != nil && err != http.ErrServerClosed {
e.Logger.Fatal("shutting down the server")
}
//handle graceful shutdown
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
e.Shutdown(ctx)
svc.Logger.Info("Echo server exited")
wg.Done()
}()
//connect to the relay
svc.Logger.Infof("Connecting to the relay: %s", cfg.Relay)
relay, err := nostr.RelayConnect(ctx, cfg.Relay, nostr.WithNoticeHandler(svc.noticeHandler))
if err != nil {
svc.Logger.Fatal(err)
}
//publish event with NIP-47 info
err = svc.PublishNip47Info(ctx, relay)
if err != nil {
svc.Logger.WithError(err).Error("Could not publish NIP47 info")
}
//Start infinite loop which will be only broken by canceling ctx (SIGINT)
//TODO: we can start this loop for multiple relays
for {
svc.Logger.Info("Subscribing to events")
sub, err := relay.Subscribe(ctx, svc.createFilters())
if err != nil {
svc.Logger.Fatal(err)
}
err = svc.StartSubscription(ctx, sub)
if err != nil {
//err being non-nil means that we have an error on the websocket error channel. In this case we just try to reconnect.
svc.Logger.WithError(err).Error("Got an error from the relay while listening to subscription. Reconnecting...")
relay, err = nostr.RelayConnect(ctx, cfg.Relay)
if err != nil {
svc.Logger.Fatal(err)
}
continue
}
//err being nil means that the context was canceled and we should exit the program.
break
}
err = relay.Close()
if err != nil {
svc.Logger.Error(err)
}
svc.Logger.Info("Graceful shutdown completed. Goodbye.")
}
func (svc *Service) createFilters() nostr.Filters {
filter := nostr.Filter{
Tags: nostr.TagMap{"p": []string{svc.cfg.IdentityPubkey}},
Kinds: []int{NIP_47_REQUEST_KIND},
}
if svc.cfg.ClientPubkey != "" {
filter.Authors = []string{svc.cfg.ClientPubkey}
}
return []nostr.Filter{filter}
}
func (svc *Service) noticeHandler(notice string) {
svc.Logger.Infof("Received a notice %s", notice)
}