forked from Onyx-Protocol/Onyx
/
main.go
395 lines (354 loc) · 11.1 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Command cored provides the Chain Core daemon and API server.
package main
import (
"context"
"crypto/tls"
"encoding/hex"
"expvar"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"runtime"
"time"
"github.com/kr/secureheader"
"chain/core"
"chain/core/accesstoken"
"chain/core/account"
"chain/core/asset"
"chain/core/blocksigner"
"chain/core/config"
"chain/core/fetch"
"chain/core/generator"
"chain/core/leader"
"chain/core/migrate"
"chain/core/mockhsm"
"chain/core/pin"
"chain/core/query"
"chain/core/rpc"
"chain/core/txbuilder"
"chain/core/txdb"
"chain/core/txfeed"
"chain/crypto/ed25519"
"chain/database/sql"
"chain/env"
"chain/errors"
chainlog "chain/log"
"chain/log/rotation"
"chain/log/splunk"
"chain/net/http/limit"
"chain/protocol"
"chain/protocol/bc"
)
const (
httpReadTimeout = 2 * time.Minute
httpWriteTimeout = time.Hour
)
var (
// config vars
tlsCrt = env.String("TLSCRT", "")
tlsKey = env.String("TLSKEY", "")
listenAddr = env.String("LISTEN", ":1999")
dbURL = env.String("DATABASE_URL", "postgres:///core?sslmode=disable")
splunkAddr = os.Getenv("SPLUNKADDR")
logFile = os.Getenv("LOGFILE")
logSize = env.Int("LOGSIZE", 5e6) // 5MB
logCount = env.Int("LOGCOUNT", 9)
logQueries = env.Bool("LOG_QUERIES", false)
maxDBConns = env.Int("MAXDBCONNS", 10) // set to 100 in prod
rpsToken = env.Int("RATELIMIT_TOKEN", 0) // reqs/sec
rpsRemoteAddr = env.Int("RATELIMIT_REMOTE_ADDR", 0) // reqs/sec
indexTxs = env.Bool("INDEX_TRANSACTIONS", true)
// build vars; initialized by the linker
buildTag = "dev"
buildCommit = "?"
buildDate = "?"
race []interface{} // initialized in race.go
httpsRedirect = true // initialized in insecure.go
blockPeriod = 1 * time.Second
expireReservationsPeriod = time.Minute
)
func init() {
expvar.NewString("buildtag").Set(buildTag)
expvar.NewString("builddate").Set(buildDate)
expvar.NewString("buildcommit").Set(buildCommit)
expvar.NewString("runtime.GOOS").Set(runtime.GOOS)
expvar.NewString("runtime.GOARCH").Set(runtime.GOARCH)
expvar.NewString("runtime.Version").Set(runtime.Version())
}
func main() {
maybeMonitorIfOnWindows() // special-case windows
ctx := context.Background()
env.Parse()
sql.EnableQueryLogging(*logQueries)
db, err := sql.Open("hapg", *dbURL)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
db.SetMaxOpenConns(*maxDBConns)
db.SetMaxIdleConns(100)
err = migrate.Run(db)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
resetInDevIfRequested(db)
conf, err := config.Load(ctx, db)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
// Initialize internode rpc clients.
hostname, err := os.Hostname()
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
processID := fmt.Sprintf("chain-%s-%d", hostname, os.Getpid())
if conf != nil {
processID += "-" + conf.ID
}
expvar.NewString("processID").Set(processID)
log.SetPrefix("cored-" + buildTag + ": ")
log.SetFlags(log.Lshortfile)
chainlog.SetPrefix(append([]interface{}{"app", "cored", "buildtag", buildTag, "processID", processID}, race...)...)
chainlog.SetOutput(logWriter())
var h http.Handler
if conf != nil {
h = launchConfiguredCore(ctx, db, conf, processID)
} else {
chainlog.Messagef(ctx, "Launching as unconfigured Core.")
h = &core.Handler{
DB: db,
AltAuth: authLoopbackInDev,
AccessTokens: &accesstoken.CredentialStore{DB: db},
}
}
secureheader.DefaultConfig.PermitClearLoopback = true
secureheader.DefaultConfig.HTTPSRedirect = httpsRedirect
secureheader.DefaultConfig.Next = h
// Give the remainder of this function a second to reach the
// ListenAndServe call, then log a welcome message.
go func() {
time.Sleep(time.Second)
chainlog.Messagef(ctx, "Chain Core online and listening at %s", *listenAddr)
}()
server := &http.Server{
Addr: *listenAddr,
Handler: secureheader.DefaultConfig,
ReadTimeout: httpReadTimeout,
WriteTimeout: httpWriteTimeout,
// Disable HTTP/2 for now until the Go implementation is more stable.
// https://github.com/golang/go/issues/16450
// https://github.com/golang/go/issues/17071
TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
}
if *tlsCrt != "" {
cert, err := tls.X509KeyPair([]byte(*tlsCrt), []byte(*tlsKey))
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, errors.Wrap(err, "parsing tls X509 key pair"))
}
server.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
}
err = server.ListenAndServeTLS("", "") // uses TLS certs from above
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, errors.Wrap(err, "ListenAndServeTLS"))
}
} else {
err = server.ListenAndServe()
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, errors.Wrap(err, "ListenAndServe"))
}
}
}
func launchConfiguredCore(ctx context.Context, db *sql.DB, conf *config.Config, processID string) http.Handler {
var remoteGenerator *rpc.Client
if !conf.IsGenerator {
remoteGenerator = &rpc.Client{
BaseURL: conf.GeneratorURL,
AccessToken: conf.GeneratorAccessToken,
Username: processID,
CoreID: conf.ID,
BuildTag: buildTag,
BlockchainID: conf.BlockchainID.String(),
}
}
txbuilder.Generator = remoteGenerator
heights, err := txdb.ListenBlocks(ctx, *dbURL)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
store, pool := txdb.New(db)
c, err := protocol.NewChain(ctx, conf.BlockchainID, store, pool, heights)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
// Set up the pin store for block processing
pinStore := &pin.Store{DB: db}
err = pinStore.LoadAll(ctx)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
// Start listeners
go pinStore.Pin(account.PinName).Listen(ctx, *dbURL)
go pinStore.Pin(asset.PinName).Listen(ctx, *dbURL)
go pinStore.Pin(query.TxPinName).Listen(ctx, *dbURL)
// Setup the transaction query indexer to index every transaction.
indexer := query.NewIndexer(db, c, pinStore)
assets := asset.NewRegistry(db, c)
accounts := account.NewManager(db, c)
if *indexTxs {
indexer.RegisterAnnotator(assets.AnnotateTxs)
indexer.RegisterAnnotator(accounts.AnnotateTxs)
assets.IndexAssets(indexer, pinStore)
accounts.IndexAccounts(indexer, pinStore)
}
hsm := mockhsm.New(db)
var generatorSigners []generator.BlockSigner
var signBlockHandler func(context.Context, *bc.Block) ([]byte, error)
if conf.IsSigner {
blockPub, err := hex.DecodeString(conf.BlockPub)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
s := blocksigner.New(blockPub, hsm, db, c)
generatorSigners = append(generatorSigners, s) // "local" signer
signBlockHandler = func(ctx context.Context, b *bc.Block) ([]byte, error) {
sig, err := s.ValidateAndSignBlock(ctx, b)
if errors.Root(err) == blocksigner.ErrInvalidKey {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
return sig, err
}
}
if conf.IsGenerator {
for _, signer := range remoteSignerInfo(ctx, processID, buildTag, conf.BlockchainID.String(), conf) {
generatorSigners = append(generatorSigners, signer)
}
c.MaxIssuanceWindow = conf.MaxIssuanceWindow
}
// GC old submitted txs periodically.
go core.CleanupSubmittedTxs(ctx, db)
h := &core.Handler{
Chain: c,
Store: store,
PinStore: pinStore,
Assets: assets,
Accounts: accounts,
HSM: hsm,
TxFeeds: &txfeed.Tracker{DB: db},
Indexer: indexer,
AccessTokens: &accesstoken.CredentialStore{DB: db},
Config: conf,
DB: db,
Addr: *listenAddr,
Signer: signBlockHandler,
AltAuth: authLoopbackInDev,
}
if *rpsToken > 0 {
h.RequestLimits = append(h.RequestLimits, core.RequestLimit{
Key: limit.AuthUserID,
Burst: 2 * (*rpsToken),
PerSecond: *rpsToken,
})
}
if *rpsRemoteAddr > 0 {
h.RequestLimits = append(h.RequestLimits, core.RequestLimit{
Key: limit.RemoteAddrID,
Burst: 2 * (*rpsRemoteAddr),
PerSecond: *rpsRemoteAddr,
})
}
var (
genhealth = h.HealthSetter("generator")
fetchhealth = h.HealthSetter("fetch")
)
// Note, it's important for any services that will install blockchain
// callbacks to be initialized before leader.Run() and the http server,
// otherwise there's a data race within protocol.Chain.
go leader.Run(db, *listenAddr, func(ctx context.Context) {
go h.Accounts.ExpireReservations(ctx, expireReservationsPeriod)
if conf.IsGenerator {
go generator.Generate(ctx, c, generatorSigners, db, blockPeriod, genhealth)
} else {
go fetch.Fetch(ctx, c, remoteGenerator, fetchhealth)
}
if !*indexTxs {
return
}
go h.Accounts.ProcessBlocks(ctx)
go h.Assets.ProcessBlocks(ctx)
go h.Indexer.ProcessBlocks(ctx)
})
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set(rpc.HeaderBlockchainID, conf.BlockchainID.String())
h.ServeHTTP(w, req)
})
}
// remoteSigner defines the address and public key of another Core
// that may sign blocks produced by this generator.
type remoteSigner struct {
Client *rpc.Client
Key ed25519.PublicKey
}
func remoteSignerInfo(ctx context.Context, processID, buildTag, blockchainID string, conf *config.Config) (a []*remoteSigner) {
for _, signer := range conf.Signers {
u, err := url.Parse(signer.URL)
if err != nil {
chainlog.Fatal(ctx, chainlog.KeyError, err)
}
if len(signer.Pubkey) != ed25519.PublicKeySize {
chainlog.Fatal(ctx, chainlog.KeyError, errors.Wrap(err), "at", "decoding signer public key")
}
client := &rpc.Client{
BaseURL: u.String(),
AccessToken: signer.AccessToken,
Username: processID,
CoreID: conf.ID,
BuildTag: buildTag,
BlockchainID: blockchainID,
}
a = append(a, &remoteSigner{Client: client, Key: ed25519.PublicKey(signer.Pubkey)})
}
return a
}
func (s *remoteSigner) SignBlock(ctx context.Context, b *bc.Block) (signature []byte, err error) {
// TODO(kr): We might end up serializing b multiple
// times in multiple calls to different remoteSigners.
// Maybe optimize that if it makes a difference.
err = s.Client.Call(ctx, "/rpc/signer/sign-block", b, &signature)
return
}
func (s *remoteSigner) String() string {
return s.Client.BaseURL
}
func logWriter() io.Writer {
dropmsg := []byte("\nlog data dropped\n")
rotation := &errlog{w: rotation.Create(logFile, *logSize, *logCount)}
splunk := &errlog{w: splunk.New(splunkAddr, dropmsg)}
switch {
case logFile != "" && splunkAddr != "":
return io.MultiWriter(rotation, splunk)
case logFile != "" && splunkAddr == "":
return rotation
case logFile == "" && splunkAddr != "":
return splunk
}
return os.Stdout
}
type errlog struct {
w io.Writer
t time.Time // protected by chain/log mutex
}
func (w *errlog) Write(p []byte) (int, error) {
// We don't want to ruin our performance
// when there's a persistent error
// writing to a log sink.
// Print to stderr at most once per minute.
_, err := w.w.Write(p)
if err != nil && time.Since(w.t) > time.Minute {
log.Println("chain/log:", err)
w.t = time.Now()
}
return len(p), nil // report success for the MultiWriter
}