Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: multi entry #223

Merged
merged 6 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"[go]": {
"editor.defaultFormatter": "golang.go"
},
"editor.formatOnSave": true
}
"editor.formatOnSave": true,
"go.buildTags": "http,wails"
}
29 changes: 12 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ Connect applications like [Damus](https://damus.io/) or [Amethyst](https://linkt

## Supported Backends

- [Alby](https://getalby.com) (see: alby.go)
- LND (see: lnd.go)
- Breez (see: breez.go)
- want more? please open an issue.

## Installation
Expand All @@ -27,35 +27,30 @@ To get a new random Nostr key use `openssl rand -hex 32` or similar.

## Development

### Server (LND)
### Server (HTTP mode)

1. Create a Lightning Polar setup with two LND nodes and uncomment the Polar LND section in your `.env` file.

2. Compile the frontend or run `touch frontend/dist/tmp` to ensure there are embeddable files available.

3. `go run .` or `gow -e=go,mod,html,css run .` using [gow](https://github.com/mitranim/gow)
3. `go run .`

### Server (Alby Wallet API)

Generate a new OAuth client for <http://localhost:8080> from the [Alby developer portal](https://getalby.com/developer) and set `ALBY_CLIENT_ID` and `ALBY_CLIENT_SECRET` in your .env file.

### React Frontend (LND)
### React Frontend (HTTP mode)

Go to `/frontend`

1. `cp .env.example .env.local`
2. `yarn install`
3. `yarn dev`
1. `yarn install`
2. `yarn dev`

### React Frontend (Alby Wallet API)
### Wails (Backend + Frontend)

Follow standard LND instructions. After logging in, you will be redirected to the wrong port (8080), so manually re-open <http://localhost:5173>.
`unset GTK_PATH && wails dev -tags "wails"`

### Wails (Backend + Frontend)
#### Wails Production build

`unset GTK_PATH && wails dev`
`wails build -tags "wails"`

### Build and run locally
### Build and run locally (HTTP mode)

`mkdir tmp`
`go build -o main`
Expand All @@ -64,7 +59,7 @@ Follow standard LND instructions. After logging in, you will be redirected to th
`cd tmp`
`./main`

### Run dockerfile locally
### Run dockerfile locally (HTTP mode)

`docker build . -t nwc-local`

Expand Down
3 changes: 1 addition & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ type Config struct {
// database config always takes preference.
db.Config
NostrSecretKey string `envconfig:"NOSTR_PRIVKEY"`
CookieSecret string `envconfig:"COOKIE_SECRET" required:"true"`
CookieSecret string `envconfig:"COOKIE_SECRET"`
CookieDomain string `envconfig:"COOKIE_DOMAIN"`
ClientPubkey string `envconfig:"CLIENT_NOSTR_PUBKEY"`
Relay string `envconfig:"RELAY" default:"wss://relay.getalby.com/v1"`
PublicRelay string `envconfig:"PUBLIC_RELAY"`
AppType string `envconfig:"APP_TYPE" default:"HTTP"`
BreezAPIKey string `envconfig:"BREEZ_API_KEY"`
BreezWorkdir string `envconfig:"BREEZ_WORK_DIR" default:".breez"`
BasicAuthUser string `envconfig:"BASIC_AUTH_USER"`
Expand Down
2 changes: 0 additions & 2 deletions frontend/.env.example

This file was deleted.

2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:wails": "VITE_NWC_APP_TYPE=WAILS vite",
"build": "tsc && vite build",
"build:wails": "tsc && VITE_NWC_APP_TYPE=WAILS vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
Expand Down
7 changes: 3 additions & 4 deletions frontend/src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ export const request = async <T>(
...args: Parameters<typeof fetch>
): Promise<T | undefined> => {
try {
const appType = import.meta.env.VITE_NWC_APP_TYPE || "HTTP";
// TODO: can we use a different request file at build time so no conditional / env variable is needed?
switch (import.meta.env.VITE_APP_TYPE) {
switch (appType) {
case "WAILS": {
const res = await WailsRequestRouter(
args[0].toString(),
Expand Down Expand Up @@ -43,9 +44,7 @@ export const request = async <T>(
return body;
}
default:
throw new Error(
"Unsupported app type: " + import.meta.env.VITE_APP_TYPE
);
throw new Error("Unsupported app type: " + appType);
}
} catch (error) {
console.error("Failed to fetch", error);
Expand Down
68 changes: 8 additions & 60 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,17 @@ import (
"context"
"database/sql"
"errors"
"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/getAlby/nostr-wallet-connect/models/db"
"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"
Expand All @@ -31,8 +27,8 @@ import (
gormtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gorm.io/gorm.v1"
)

func main() {

// TODO: move to service.go
func NewService(wg *sync.WaitGroup) *Service {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • why do we need this WaitGroup passed in here. This feels a bit strange

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the service is run on a separate process. The go process exits before that process is gracefully shut down (e.g. disconnect from the relay). The app wasn't actually exiting gracefully though. I have fixed these now, maybe we can review it together?

// Load config from environment variables / .env file
godotenv.Load(".env")
cfg := &Config{}
Expand Down Expand Up @@ -148,59 +144,10 @@ func main() {
logger.SetLevel(log.InfoLevel)
svc.Logger = logger

var wg sync.WaitGroup
wg.Add(1)
// TODO: can we move these into two separate entrypoint files?
switch cfg.AppType {
case WailsAppType:
err := svc.launchLNBackend()
if err != nil {
// LN backend not needed immediately, just log errors
svc.Logger.Warnf("Failed to launch LN backend: %v", err)
}
go func() {
app := NewApp(svc)
LaunchWailsApp(app)
wg.Done()
svc.Logger.Info("Wails app exited")
}()
case HttpAppType:
// using echo
echologrus.Logger = logger
e := echo.New()

// Alby backend only supported in HTTP app type
if svc.cfg.LNBackendType == AlbyBackendType {
oauthService, err := NewAlbyOauthService(svc, e)
if err != nil {
svc.Logger.Fatal(err)
}
svc.lnClient = oauthService
} else {
err := svc.launchLNBackend()
if err != nil {
// LN backend not needed immediately, just log errors
svc.Logger.Warnf("Failed to launch LN backend: %v", err)
}
}

//register shared routes
svc.RegisterSharedRoutes(e)
//start Echo server
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()
}()
default:
svc.Logger.Fatalf("Unknown app type: %s", cfg.AppType)
err = svc.launchLNBackend()
if err != nil {
// LN backend not needed immediately, just log errors
svc.Logger.Warnf("Failed to launch LN backend: %v", err)
}

go func() {
Expand Down Expand Up @@ -246,7 +193,8 @@ func main() {
svc.Logger.Info("Graceful shutdown completed. Goodbye.")
wg.Done()
}()
wg.Wait()

return svc
}

func (svc *Service) setupDbConfig() error {
Expand Down
53 changes: 53 additions & 0 deletions main_http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//go:build !wails || http
// +build !wails http

// (http tag above is simply to fix go language server issue and is not needed to build the app)

package main

import (
"context"
"fmt"
"net/http"
"sync"
"time"

echologrus "github.com/davrux/echo-logrus/v4"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)

// ignore this warning: we use build tags
// this function will only be executed if no wails tag is set
func main() {
log.Info("NWC Starting in HTTP mode")
var wg sync.WaitGroup
wg.Add(1)

svc := NewService(&wg)

if svc.cfg.CookieSecret == "" {
svc.Logger.Fatalf("required key COOKIE_SECRET missing value")
}

echologrus.Logger = svc.Logger
e := echo.New()

//register shared routes
svc.RegisterSharedRoutes(e)
//start Echo server
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
<-svc.ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
e.Shutdown(ctx)
svc.Logger.Info("Echo server exited")
wg.Done()
}()

wg.Wait()
}
29 changes: 29 additions & 0 deletions main_wails.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//go:build wails
// +build wails

package main

import (
"sync"

log "github.com/sirupsen/logrus"
)

// ignore this warning: we use build tags
// this function will only be executed if the wails tag is set
func main() {
log.Info("NWC Starting in WAILS mode")
var wg sync.WaitGroup
wg.Add(1)

svc := NewService(&wg)

go func() {
app := NewApp(svc)
LaunchWailsApp(app)
wg.Done()
svc.Logger.Info("Wails app exited")
}()

wg.Wait()
}
4 changes: 2 additions & 2 deletions wails.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"name": "nostr-wallet-connect",
"outputfilename": "Nostr-Wallet-Connect",
"frontend:install": "yarn install",
"frontend:build": "yarn build",
"frontend:dev:watcher": "yarn dev",
"frontend:build": "yarn build:wails",
"frontend:dev:watcher": "yarn dev:wails",
"frontend:dev:serverUrl": "auto",
"author": {
"name": "Alby Contributors",
Expand Down
Loading