-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
262 lines (238 loc) · 7.32 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
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
package main
import (
"context"
_ "embed"
"log"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum/ethclient"
auth "github.com/iden3/go-iden3-auth/v2"
"github.com/iden3/go-iden3-auth/v2/loaders"
"github.com/iden3/go-iden3-auth/v2/pubsignals"
"github.com/iden3/go-iden3-auth/v2/state"
schemaLoaders "github.com/iden3/go-schema-processor/v2/loaders"
"github.com/iden3/go-schema-processor/v2/merklize"
"github.com/iden3/go-service-template/config"
"github.com/iden3/go-service-template/pkg/ipfs"
"github.com/iden3/go-service-template/pkg/logger"
"github.com/iden3/go-service-template/pkg/packagemanager"
"github.com/iden3/go-service-template/pkg/repository"
httprouter "github.com/iden3/go-service-template/pkg/router/http"
"github.com/iden3/go-service-template/pkg/router/http/handlers"
"github.com/iden3/go-service-template/pkg/services/authentication"
"github.com/iden3/go-service-template/pkg/services/iden3comm"
"github.com/iden3/go-service-template/pkg/services/issuer"
"github.com/iden3/go-service-template/pkg/services/system"
"github.com/iden3/go-service-template/pkg/shutdown"
httptransport "github.com/iden3/go-service-template/pkg/transport/http"
libiden3comm "github.com/iden3/iden3comm/v2"
"github.com/piprate/json-gold/ld"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
//go:embed cache/w3cCredentialSchemaV1.json
w3cCredentialSchemaV1 []byte
)
func main() {
cfg, err := config.Parse()
if err != nil {
log.Fatalf("failed to parse config: %v", err)
}
if err = logger.SetDefaultLogger(
cfg.Log.Environment,
cfg.Log.LogLevel(),
); err != nil {
log.Fatalf("failed to set default logger: %v", err)
}
// init dependencies
authverifier, err := initializationAuthVerifier(cfg)
if err != nil {
logger.WithError(err).Fatal("error creating auth verifier")
}
pkgmanager, err := packagemanager.NewPackageManager(
cfg.SupportedRPC,
cfg.SupportedStateContracts,
cfg.KeysDirPath,
)
if err != nil {
logger.WithError(err).Fatal("error creating package manager")
}
//nolint:govet //resource leak is handled by shutdown manager
mongoConnectTimeout, _ := context.WithTimeout(context.Background(), time.Second*20)
reg := bson.NewRegistry()
reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(bson.M{}))
opts := options.Client().ApplyURI(cfg.MongoDBConnectionString).SetRegistry(reg)
mongoClient, err := mongo.Connect(mongoConnectTimeout, opts)
if err != nil {
logger.WithError(err).Fatal("error connecting to mongodb")
}
credentialRepository, err := repository.NewCredentialRepository(mongoClient.Database("credentials"))
if err != nil {
logger.WithError(err).Fatal("error creating credential repository")
}
ethclients, err := initializationEthClients(cfg.SupportedRPC)
if err != nil {
logger.WithError(err).Fatal("error creating eth clients")
}
ipfsCli := ipfs.NewIPFSClient(cfg.IPFSURL)
documentLoader, err := initDocumentLoaderWithCache(ipfsCli)
if err != nil {
logger.WithError(err).Fatal("error creating document loader")
}
httpserver := newHTTPServer(
cfg,
authverifier,
pkgmanager,
credentialRepository,
ethclients,
cfg.IssuersPrivateKey,
ipfsCli,
merklize.WithDocumentLoader(documentLoader),
)
newShutdownManager(httpserver).HandleShutdownSignal()
}
func newHTTPServer(
cfg *config.Config,
authverifier *auth.Verifier,
pkgmanager *libiden3comm.PackageManager,
credentialRepository *repository.CredentialRepository,
ethclients map[string]*ethclient.Client,
privateKeys map[string]string,
ipfsCli issuer.IPFSCli,
merklizeOpts ...merklize.MerklizeOption,
) *httptransport.Server {
// init services
authenticationService := authentication.NewAuthenticationService(
authverifier,
)
iden3commService := iden3comm.NewIden3commService(
pkgmanager,
credentialRepository,
)
issuerService := issuer.NewIssuerService(
credentialRepository,
ethclients,
sanitizePrivateKeys(privateKeys),
ipfsCli,
merklizeOpts...,
)
// init handlers
systemHandlers := handlers.NewSystemHandler(
system.NewReadinessService(),
system.NewLivenessService(),
)
authenticationHandlers := handlers.NewAuthenticationHandlers(
cfg.ExternalHost,
authenticationService,
)
iden3commHandlers := handlers.NewIden3commHandlers(
iden3commService,
)
issuerHandlers := handlers.NewIssuerHandlers(
issuerService,
cfg.ExternalHost,
)
// init routers
h := httprouter.NewHandlers(
systemHandlers,
authenticationHandlers,
iden3commHandlers,
issuerHandlers,
)
routers := h.NewRouter(
httprouter.WithOrigins(cfg.HTTPServer.Origins),
)
// run http server
httpserver := httptransport.New(
routers,
httptransport.WithWriteTimeout(0),
httptransport.WithHost(cfg.HTTPServer.Host, cfg.HTTPServer.Port),
)
go func() {
err := httpserver.Start()
if errors.Is(err, http.ErrServerClosed) {
logger.Info("HTTP server closed by request")
} else {
logger.WithError(err).Fatal("http server closed with error")
}
}()
return httpserver
}
func newShutdownManager(toclose ...shutdown.Shutdown) *shutdown.Manager {
m := shutdown.NewManager()
for _, s := range toclose {
m.Register(s)
}
return m
}
func chainIDToDIDPrefix(chainID int) string {
p := map[int]string{
137: "polygon:main",
80002: "polygon:amoy",
21000: "privado:main",
21001: "privado:test",
}
return p[chainID]
}
func initializationAuthVerifier(configuration *config.Config) (*auth.Verifier, error) {
var resolvers = make(map[string]pubsignals.StateResolver, len(configuration.SupportedStateContracts))
for network, contractAddress := range configuration.SupportedStateContracts {
rpcURL, ok := configuration.SupportedRPC[network]
if !ok {
return nil, errors.Errorf("no rpc for network %s", network)
}
chainID, _ := strconv.Atoi(network)
resolvers[chainIDToDIDPrefix(chainID)] = state.NewETHResolver(rpcURL, contractAddress)
}
verifier, err := auth.NewVerifier(loaders.FSKeyLoader{
Dir: configuration.KeysDirPath,
}, resolvers)
if err != nil {
return nil, errors.Errorf("error creating verifier: %v", err)
}
return verifier, nil
}
func initializationEthClients(supportedRPC map[string]string) (map[string]*ethclient.Client, error) {
ethClients := make(map[string]*ethclient.Client, len(supportedRPC))
for network, rpcURL := range supportedRPC {
ec, err := ethclient.Dial(rpcURL)
if err != nil {
return nil, errors.Errorf("error creating eth client: %v", err)
}
ethClients[network] = ec
}
return ethClients, nil
}
func initDocumentLoaderWithCache(ipfsCli schemaLoaders.IPFSClient) (ld.DocumentLoader, error) {
opts := schemaLoaders.WithEmbeddedDocumentBytes(
"https://www.w3.org/2018/credentials/v1",
w3cCredentialSchemaV1,
)
memoryCacheEngine, err := schemaLoaders.NewMemoryCacheEngine(opts)
if err != nil {
return nil, err
}
l := schemaLoaders.NewDocumentLoader(ipfsCli, "", schemaLoaders.WithCacheEngine(memoryCacheEngine))
return l, nil
}
func sanitizePrivateKeys(privateKeys map[string]string) map[string]string {
sanitized := make(map[string]string, len(privateKeys))
for k, v := range privateKeys {
v := strings.TrimSpace(v)
switch {
case strings.HasPrefix(v, "0x"):
sanitized[k] = strings.TrimPrefix(v, "0x")
case strings.HasPrefix(v, "0X"):
sanitized[k] = strings.TrimPrefix(v, "0X")
default:
sanitized[k] = v
}
}
return sanitized
}