-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.go
314 lines (281 loc) · 9.96 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
package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
_ "net/http/pprof"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/RiemaLabs/modular-indexer-committee/apis"
"github.com/RiemaLabs/modular-indexer-committee/checkpoint"
"github.com/RiemaLabs/modular-indexer-committee/internal/metrics"
"github.com/RiemaLabs/modular-indexer-committee/ord"
"github.com/RiemaLabs/modular-indexer-committee/ord/getter"
"github.com/RiemaLabs/modular-indexer-committee/ord/stateless"
)
var (
version = "latest"
gitHash = "unknown"
)
func CatchupStage(ordGetter getter.OrdGetter, arguments *RuntimeArguments, initHeight uint, latestHeight uint) (*stateless.Queue, error) {
metrics.Stage.Set(metrics.StageCatchup)
// Fetch the latest block height.
header := stateless.LoadHeader(arguments.EnableStateRootCache, initHeight)
curHeight := header.Height
log.Printf("Fast catchup to the lateset block height! From %d to %d \n", curHeight, latestHeight)
catchupHeight := latestHeight - ord.BitcoinConfirmations
// Create a channel to listen for SIGINT (Ctrl+C) signal
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
// Start to catch-up
// TODO: Medium. Refine the catchup performance by batching query.
if catchupHeight > curHeight {
for i := curHeight + 1; i <= catchupHeight; i++ {
select {
case <-sigChan:
// SIGINT received, stop the catch-up process
log.Printf("Saving cache file. Please don't force exit.")
_ = stateless.StoreHeader(header, header.Height-2000)
os.Exit(0)
default:
ordTransfer, err := ordGetter.GetOrdTransfers(i)
if err != nil {
return nil, err
}
header.Lock()
stateless.Exec(header, ordTransfer, i)
_ = header.Paging(ordGetter, false, stateless.NodeResolveFn)
header.Unlock()
if i%1000 == 0 {
log.Printf("Blocks: %d / %d \n", i, catchupHeight)
if arguments.EnableStateRootCache {
err := stateless.StoreHeader(header, header.Height-2000)
if err != nil {
log.Printf("Failed to store the cache at height: %d", i)
}
}
}
}
}
} else if catchupHeight == curHeight {
// stateRoot is located at catchupHeight.
} else if catchupHeight < curHeight {
return nil, errors.New("the stored stateRoot is too advanced to handle reorg situations")
}
// Currently, header.Height equals to catchupHeight.
ots, err := ordGetter.GetOrdTransfers(catchupHeight)
if err != nil {
return nil, err
}
header.OrdTrans = ots
if arguments.EnableStateRootCache {
err := stateless.StoreHeader(header, header.Height-2000)
if err != nil {
log.Printf("Failed to store the cache at height: %d", header.Height)
}
}
queue, err := stateless.NewQueues(ordGetter, header, true, catchupHeight+1)
if err != nil {
return nil, err
}
if queue.LatestHeight() != latestHeight {
return nil, fmt.Errorf("mismatched state height: %d and catchup height: %d", queue.LatestHeight(), latestHeight)
}
return queue, nil
}
func ServiceStage(ordGetter getter.OrdGetter, arguments *RuntimeArguments, queue *stateless.Queue, interval time.Duration) {
metrics.Stage.Set(metrics.StageServing)
// Create a channel to listen for SIGINT (Ctrl+C) signal
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
var history = make(map[string]checkpoint.UploadRecord)
if arguments.EnableService {
if arguments.CommitteeIndexerURL != "" {
log.Printf("Providing API service at: %s", arguments.CommitteeIndexerURL)
} else {
log.Printf("Providing API service at: %s", GlobalConfig.Service.URL)
}
go apis.StartService(queue, arguments.EnableCommittee, arguments.EnableTest, arguments.EnablePprof)
}
for {
select {
case <-sigChan:
// TODO: High. Save the latest state is unsound if reorg happened.
// log.Printf("Saving cache file. Please don't force exit.")
// stateless.StoreHeader(queue.Header, queue.Header.Height-2000)
os.Exit(0)
default:
curHeight := queue.LatestHeight()
latestHeight, err := ordGetter.GetLatestBlockHeight()
if err != nil {
log.Fatalf("Failed to get the latest block height: %v", err)
}
if curHeight < latestHeight {
metrics.Stage.Set(metrics.StageUpdating)
err := queue.Update(ordGetter, latestHeight)
if err != nil {
log.Fatalf("Failed to update the queue: %v", err)
}
metrics.Stage.Set(metrics.StageServing)
}
reorgHeight, err := queue.CheckForReorg(ordGetter)
if err != nil {
log.Fatalf("Failed to check the reorganization: %v", err)
}
if reorgHeight != 0 {
metrics.Stage.Set(metrics.StageReorg)
err := queue.Recovery(ordGetter, reorgHeight)
if err != nil {
log.Fatalf("Failed to update the queue: %v", err)
}
metrics.Stage.Set(metrics.StageServing)
}
if arguments.EnableCommittee {
latestHistory := stateless.DiffState{
Height: queue.Header.Height,
Hash: queue.Header.Hash,
VerkleCommit: queue.Header.Root.Commit().Bytes(),
Access: stateless.AccessList{},
}
hs := make([]*stateless.DiffState, 0)
for _, i := range queue.History {
hs = append(hs, &i)
}
hs = append(hs, &latestHistory)
for _, i := range hs {
key := fmt.Sprintf("%d", i.Height) + i.Hash
if curRecord, found := history[key]; !(found && curRecord.Success) {
committeeIndexerName := GlobalConfig.Service.Name
if arguments.CommitteeIndexerName != "" {
committeeIndexerName = arguments.CommitteeIndexerName
}
serviceURL := GlobalConfig.Service.URL
if arguments.CommitteeIndexerURL != "" {
serviceURL = arguments.CommitteeIndexerURL
}
metaProtocol := GlobalConfig.Service.MetaProtocol
if arguments.ProtocolName != "" {
metaProtocol = arguments.ProtocolName
}
indexerID := checkpoint.IndexerIdentification{
URL: serviceURL,
Name: committeeIndexerName,
Version: version,
MetaProtocol: metaProtocol,
}
commitment := base64.StdEncoding.EncodeToString(i.VerkleCommit[:])
c := checkpoint.NewCheckpoint(&indexerID, i.Height, i.Hash, commitment)
timeout := time.Duration(GlobalConfig.Report.Timeout) * time.Millisecond
if GlobalConfig.Report.Method == "S3" {
log.Printf("Uploading the checkpoint by S3 at height: %s\n", c.Height)
s3cfg := GlobalConfig.Report.S3
err = checkpoint.UploadCheckpointByS3(&c,
s3cfg.AccessKey, s3cfg.SecretKey, s3cfg.Region, s3cfg.Bucket, timeout)
if err != nil {
log.Printf("Unable to upload the checkpoint by S3 due to: %v", err)
} else {
log.Printf("Succeed to upload the checkpoint by S3 at height: %s\n", c.Height)
}
} else if GlobalConfig.Report.Method == "DA" {
log.Printf("Uploading the checkpoint by DA at height: %s\n", c.Height)
dacfg := GlobalConfig.Report.Da
err = checkpoint.UploadCheckpointByDA(&c,
dacfg.PrivateKey, dacfg.GasCoupon, dacfg.NamespaceID, dacfg.Network, timeout)
if err != nil {
log.Printf("Unable to upload the checkpoint by DA due to: %v", err)
} else {
log.Printf("Succeed to upload the checkpoint by DA at height: %s\n", c.Height)
}
}
history[key] = checkpoint.UploadRecord{
Success: true,
}
}
}
}
if !arguments.EnableTest {
log.Printf("Listening for new Bitcoin block, current height: %d\n", latestHeight)
}
time.Sleep(interval)
}
}
}
func Execution(arguments *RuntimeArguments) {
go metrics.ListenAndServe(arguments.MetricAddr)
metrics.Version.WithLabelValues(version).Set(1)
metrics.Stage.Set(metrics.StageInitializing)
// Get the configuration.
configFile, err := os.ReadFile(arguments.ConfigFilePath)
if err != nil {
log.Fatalf("Failed to read config file: %v", err)
}
err = json.Unmarshal(configFile, &GlobalConfig)
if err != nil {
log.Fatalf("Failed to parse config file: %v", err)
}
if GlobalConfig.Report.Method == "DA" && arguments.EnableCommittee {
if !checkpoint.IsValidNamespaceID(GlobalConfig.Report.Da.NamespaceID) {
log.Printf("Got invalid Namespace ID from the config.json. Initializing a new namespace.")
scanner := bufio.NewScanner(os.Stdin)
namespaceName := ""
for {
fmt.Print("Please enter the namespace name: ")
if scanner.Scan() {
namespaceName = scanner.Text()
if strings.TrimSpace(namespaceName) == "" {
fmt.Print("Namespace name couldn't be empty!")
} else {
break
}
}
}
nid, err := checkpoint.CreateNamespace(GlobalConfig.Report.Da.PrivateKey, GlobalConfig.Report.Da.GasCoupon, namespaceName, GlobalConfig.Report.Da.Network)
if err != nil {
log.Fatalf("Failed to create namespace due to %v", err)
}
GlobalConfig.Report.Da.NamespaceID = nid
bytes, err := json.Marshal(GlobalConfig)
if err != nil {
log.Fatalf("Failed to save namespace ID to local file due to %v", err)
}
err = os.WriteFile("config.json", bytes, 0644)
if err != nil {
log.Fatalf("Failed to save namespace ID to local file due to %v", err)
}
fmt.Printf("Succeed to create namespace, ID: %s!", nid)
}
}
// Use OPI database as the ordGetter.
gd := getter.DatabaseConfig(GlobalConfig.Database)
var ordGetter getter.OrdGetter
if arguments.EnableTest {
ordGetter, err = getter.NewOPIOrdGetterTest(&gd, arguments.TestBlockHeightLimit, arguments.TestBlockHeightLimit)
} else {
ordGetter, err = getter.NewOPIOrdGetter(&gd)
}
if err != nil {
log.Fatalf("Failed to initial getter from opi database: %v", err)
}
latestHeight, err := ordGetter.GetLatestBlockHeight()
if err != nil {
log.Fatalf("Failed to get the latest block height: %v", err)
}
queue, err := CatchupStage(ordGetter, arguments, stateless.BRC20StartHeight-1, latestHeight)
if err != nil {
log.Fatalf("Failed to catchup the latest state: %v", err)
}
ServiceStage(ordGetter, arguments, queue, 60*time.Second)
}
func main() {
arguments := NewRuntimeArguments()
rootCmd := arguments.MakeCmd()
if err := rootCmd.Execute(); err != nil {
log.Fatalf("Failed to execute: %v", err)
}
}