-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
236 lines (216 loc) · 6.72 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
231
232
233
234
235
236
package main
import (
"embed"
_ "embed"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/SundaeSwap-finance/toolkit-for-cardano/internal/cardano"
"github.com/SundaeSwap-finance/toolkit-for-cardano/internal/gql"
"github.com/SundaeSwap-finance/toolkit-for-cardano/internal/gql/graphiql"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/savaki/zapctx"
"github.com/segmentio/ksuid"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
)
//go:embed internal/built.txt
var built string
//go:embed internal/version.txt
var version string
//go:embed ui/dist/*
var dist embed.FS
var opts struct {
Assets string // Assets contains optional directory for static assets
Debug bool // Debug mode for additional logging
Dir string // Dir to store data in
PoolDir string // Dir where the pool keys are found
Port int // Port to listen on
Cardano struct {
CLI cli.StringSlice // Cardano cli invocation e.g. cardano-cli or ssh hostname cardano-cli
SocketPath string // SocketPath holds ${CARDANO_NODE_SOCKET_PATH}
TestnetMagic string // TestnetMagic
TreasuryAddr string // TreasuryAddr is the address of the treasury wallet
TreasuryAddrFile string // TreasuryAddrFile is a file that holds the address of the treasury wallet
TreasurySkeyFile string // TreasurySkeyFile is a pointer to the skey file for the treasury wallet
}
}
func main() {
app := cli.NewApp()
app.Usage = "launch toolkit-for-cardano server"
app.Version = strings.TrimSpace(version)
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "assets",
Usage: "optional path to static assets",
EnvVars: []string{"ASSETS"},
Destination: &opts.Assets,
},
&cli.StringSliceFlag{
Name: "cardano-cli",
Usage: "command to invoke cardano-cli",
Value: cli.NewStringSlice("cardano-cli"),
EnvVars: []string{"CARDANO_CLI"},
Destination: &opts.Cardano.CLI,
},
&cli.BoolFlag{
Name: "debug",
Usage: "debug mode",
Destination: &opts.Debug,
},
&cli.StringFlag{
Name: "dir",
Usage: "path to data directory",
Value: os.ExpandEnv("data"),
EnvVars: []string{"DATA_DIR"},
Destination: &opts.Dir,
},
&cli.StringFlag{
Name: "pool-dir",
Usage: "path to the node-pool1 directory",
EnvVars: []string{"POOL_DIR"},
Required: true,
Destination: &opts.PoolDir,
},
&cli.IntFlag{
Name: "port",
Usage: "port to listen on",
Value: 3000,
EnvVars: []string{"PORT"},
Destination: &opts.Port,
},
&cli.StringFlag{
Name: "socket-path",
Usage: "socket path for cardano node e.g. node.sock",
EnvVars: []string{"CARDANO_NODE_SOCKET_PATH"},
Required: true,
Destination: &opts.Cardano.SocketPath,
},
&cli.StringFlag{
Name: "testnet-magic",
Usage: "testnet-magic value",
Value: "8",
EnvVars: []string{"TESTNET_MAGIC"},
Destination: &opts.Cardano.TestnetMagic,
},
&cli.StringFlag{
Name: "treasury-addr",
Usage: "address with lovelace to fund other addresses from",
EnvVars: []string{"TREASURY_ADDR"},
Destination: &opts.Cardano.TreasuryAddr,
},
&cli.StringFlag{
Name: "treasury-addr-file",
Usage: "load the treasury address from the specified file",
EnvVars: []string{"TREASURY_ADDR_FILE"},
Destination: &opts.Cardano.TreasuryAddrFile,
},
&cli.StringFlag{
Name: "treasury-skey-file",
Usage: "file containing treasury signing key",
EnvVars: []string{"TREASURY_SIGNING_KEY_FILE"},
Required: true,
Destination: &opts.Cardano.TreasurySkeyFile,
},
}
app.Action = action
err := app.Run(os.Args)
if err != nil {
log.Fatalln(err)
}
}
func action(_ *cli.Context) error {
dir, err := filepath.Abs(opts.Dir)
if err != nil {
return fmt.Errorf("failed to start toolkit-for-cardano: %w", err)
}
poolDir, err := filepath.Abs(opts.PoolDir)
if err != nil {
return fmt.Errorf("failed to start toolkit-for-cardano: %w", err)
}
if err := os.MkdirAll(filepath.Join(dir, "tmp"), 0755); err != nil {
return fmt.Errorf("failed to start toolkit-for-cardano: failed to create tmp dir: %w", err)
}
// allow the treasury addr to be either provided or read from file
addr := opts.Cardano.TreasuryAddr
if addr == "" {
data, err := ioutil.ReadFile(opts.Cardano.TreasuryAddrFile)
if err != nil {
return fmt.Errorf("failed to start toolkit-for-cardano: unable to read treasury-addr-file: %w", err)
}
addr = strings.TrimSpace(string(data))
}
cardanoCLI := cardano.CLI{
Cmd: opts.Cardano.CLI.Value(),
Dir: dir,
PoolDir: poolDir,
SocketPath: opts.Cardano.SocketPath,
TestnetMagic: opts.Cardano.TestnetMagic,
TreasuryAddr: addr,
TreasurySkeyFile: opts.Cardano.TreasurySkeyFile,
Debug: opts.Debug,
}
config := gql.Config{
Built: strings.TrimSpace(built),
CLI: &cardanoCLI,
Version: strings.TrimSpace(version),
}
handler, err := gql.New(config)
if err != nil {
return fmt.Errorf("failed to create server: %w", err)
}
logger, err := zap.NewDevelopment()
if err != nil {
return err
}
router := chi.NewRouter()
router.Use(
withLogger(logger),
withCORS(),
)
router.Get("/graphql", graphiql.New("/graphql"))
router.Post("/graphql", handler.ServeHTTP)
if opts.Assets != "" {
fs := http.FileServer(http.Dir(opts.Assets))
router.NotFound(fs.ServeHTTP)
} else {
fs := withRoot("ui/dist", http.FS(dist))
router.NotFound(http.FileServer(fs).ServeHTTP)
}
logger.Info("started server", zap.Int("port", opts.Port))
defer logger.Info("stopped server")
return http.ListenAndServe(fmt.Sprintf(":%v", opts.Port), router)
}
type fileSystemFunc func(name string) (http.File, error)
func (fn fileSystemFunc) Open(name string) (http.File, error) {
return fn(name)
}
func withRoot(root string, fs http.FileSystem) fileSystemFunc {
return func(name string) (http.File, error) {
path := filepath.Join(root, name)
return fs.Open(path)
}
}
func withCORS() func(next http.Handler) http.Handler {
return cors.Handler(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
})
}
func withLogger(logger *zap.Logger) func(handler http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := zapctx.NewContext(req.Context(),
logger.With(zap.String("tid", ksuid.New().String())),
)
req = req.WithContext(ctx)
handler.ServeHTTP(w, req)
})
}
}