forked from terra-money/mantlemint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sync.go
273 lines (230 loc) · 7.07 KB
/
sync.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
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"log"
"os"
"runtime/debug"
"github.com/CosmWasm/wasmd/x/wasm"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
terra "github.com/classic-terra/core/v3/app"
core "github.com/classic-terra/core/v3/types"
tmlog "github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/proxy"
tendermint "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/baseapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/mux"
blockFeeder "github.com/terra-money/mantlemint/block_feed"
"github.com/terra-money/mantlemint/config"
"github.com/terra-money/mantlemint/db/heleveldb"
"github.com/terra-money/mantlemint/db/hld"
"github.com/terra-money/mantlemint/db/safe_batch"
"github.com/terra-money/mantlemint/indexer"
"github.com/terra-money/mantlemint/indexer/block"
"github.com/terra-money/mantlemint/indexer/tx"
"github.com/terra-money/mantlemint/mantlemint"
"github.com/terra-money/mantlemint/rpc"
"github.com/terra-money/mantlemint/store/rootmulti"
dbm "github.com/cometbft/cometbft-db"
)
// initialize mantlemint for v0.34.x
func main() {
mantlemintConfig := config.NewConfig()
mantlemintConfig.Print()
sdkConfig := sdk.GetConfig()
sdkConfig.SetCoinType(core.CoinType)
sdkConfig.SetBech32PrefixForAccount(core.Bech32PrefixAccAddr, core.Bech32PrefixAccPub)
sdkConfig.SetBech32PrefixForValidator(core.Bech32PrefixValAddr, core.Bech32PrefixValPub)
sdkConfig.SetBech32PrefixForConsensusNode(core.Bech32PrefixConsAddr, core.Bech32PrefixConsPub)
sdkConfig.SetAddressVerifier(wasmtypes.VerifyAddressLen())
sdkConfig.Seal()
ldb, ldbErr := heleveldb.NewLevelDBDriver(&heleveldb.DriverConfig{
Name: mantlemintConfig.MantlemintDB,
Dir: mantlemintConfig.Home,
Mode: heleveldb.DriverModeKeySuffixDesc,
})
if ldbErr != nil {
panic(ldbErr)
}
hldb := hld.ApplyHeightLimitedDB(
ldb,
&hld.HeightLimitedDBConfig{
Debug: true,
},
)
batched := safe_batch.NewSafeBatchDB(hldb)
batchedOrigin := batched.(safe_batch.SafeBatchDBCloser)
logger := tmlog.NewTMLogger(os.Stdout)
codec := terra.MakeEncodingConfig()
// customize CMS to limit kv store's read height on query
cms := rootmulti.NewStore(batched, logger, hldb)
//vpr := viper.GetViper()
appOptions := make(simtestutil.AppOptionsMap, 0)
var wasmOpts []wasm.Option
app := terra.NewTerraApp(
logger,
batched,
nil,
true, // need this so KVStores are set
make(map[int64]bool),
mantlemintConfig.Home,
codec,
appOptions,
wasmOpts,
fauxMerkleModeOpt,
func(ba *baseapp.BaseApp) {
ba.SetCMS(cms)
},
baseapp.SetChainID(mantlemintConfig.ChainID),
)
// create app...
appCreator := mantlemint.NewConcurrentQueryClientCreator(app)
appMetrics := proxy.NopMetrics()
appConns := proxy.NewAppConns(appCreator, appMetrics)
appConns.SetLogger(logger)
if startErr := appConns.OnStart(); startErr != nil {
panic(startErr)
}
go func() {
a := <-appConns.Quit()
fmt.Println(a)
}()
executor := mantlemint.NewMantlemintExecutor(batched, appConns.Consensus())
mm := mantlemint.NewMantlemint(
batched,
appConns,
executor,
// run before
nil,
// RunAfter Inject callback
nil,
)
// initialize using provided genesis
genesisDoc := getGenesisDoc(mantlemintConfig.GenesisPath)
initialHeight := genesisDoc.InitialHeight
// set target initial write height to genesis.initialHeight;
// this is safe as upon Inject it will be set with block.Height
hldb.SetWriteHeight(initialHeight)
batchedOrigin.Open()
// initialize state machine with genesis
if initErr := mm.Init(genesisDoc); initErr != nil {
panic(initErr)
}
// flush to db; panic upon error (can't proceed)
if rollback, flushErr := batchedOrigin.Flush(); flushErr != nil {
debug.PrintStack()
panic(flushErr)
} else if rollback != nil {
rollback.Close()
}
// load initial state to mantlemint
if loadErr := mm.LoadInitialState(); loadErr != nil {
panic(loadErr)
}
// initialization is done; clear write height
hldb.ClearWriteHeight()
// get blocks over some sort of transport, inject to mantlemint
blockFeed := blockFeeder.NewAggregateBlockFeed(
mm.GetCurrentHeight(),
mantlemintConfig.RPCEndpoints,
mantlemintConfig.WSEndpoints,
)
// create indexer service
indexerInstance, indexerInstanceErr := indexer.NewIndexer(mantlemintConfig.IndexerDB, mantlemintConfig.Home)
if indexerInstanceErr != nil {
panic(indexerInstanceErr)
}
indexerInstance.RegisterIndexerService("tx", tx.IndexTx)
indexerInstance.RegisterIndexerService("block", block.IndexBlock)
abcicli, _ := appCreator.NewABCIClient()
rpccli := rpc.NewRpcClient(abcicli)
// rest cache invalidate channel
cacheInvalidateChan := make(chan int64)
// start RPC server
rpcErr := rpc.StartRPC(
app,
rpccli,
mantlemintConfig.ChainID,
codec,
cacheInvalidateChan,
// callback for registering custom routers; primarily for indexers
// default: noop,
// todo: make this part injectable
func(router *mux.Router) {
indexerInstance.RegisterRESTRoute(router, tx.RegisterRESTRoute)
indexerInstance.RegisterRESTRoute(router, block.RegisterRESTRoute)
},
// inject flag checker for synced
blockFeed.IsSynced,
)
if rpcErr != nil {
panic(rpcErr)
}
// start subscribing to block
if mantlemintConfig.DisableSync {
fmt.Println("running without sync...")
forever()
} else if cBlockFeed, blockFeedErr := blockFeed.Subscribe(0); blockFeedErr != nil {
panic(blockFeedErr)
} else {
var rollbackBatch dbm.Batch
for {
feed := <-cBlockFeed
// open db batch
hldb.SetWriteHeight(feed.Block.Height)
batchedOrigin.Open()
if injectErr := mm.Inject(feed.Block); injectErr != nil {
// rollback last block
if rollbackBatch != nil {
fmt.Println("rollback previous block")
rollbackBatch.WriteSync()
rollbackBatch.Close()
}
debug.PrintStack()
panic(injectErr)
}
// last block is okay -> dispose rollback batch
if rollbackBatch != nil {
rollbackBatch.Close()
rollbackBatch = nil
}
// run indexer BEFORE batch flush
if indexerErr := indexerInstance.Run(feed.Block, feed.BlockID, mm.GetCurrentEventCollector()); indexerErr != nil {
debug.PrintStack()
panic(indexerErr)
}
// flush db batch
// returns rollback batch that reverts current block injection
if rollback, flushErr := batchedOrigin.Flush(); flushErr != nil {
debug.PrintStack()
panic(flushErr)
} else {
rollbackBatch = rollback
}
hldb.ClearWriteHeight()
cacheInvalidateChan <- feed.Block.Height
}
}
}
// Pass this in as an option to use a dbStoreAdapter instead of an IAVLStore for simulation speed.
func fauxMerkleModeOpt(app *baseapp.BaseApp) {
app.SetFauxMerkleMode()
}
func getGenesisDoc(genesisPath string) *tendermint.GenesisDoc {
jsonBlob, _ := os.ReadFile(genesisPath)
shasum := sha1.New()
shasum.Write(jsonBlob)
sum := hex.EncodeToString(shasum.Sum(nil))
log.Printf("[sync] genesis shasum=%s", sum)
if genesis, genesisErr := tendermint.GenesisDocFromFile(genesisPath); genesisErr != nil {
panic(genesisErr)
} else {
return genesis
}
}
func forever() {
<-(chan int)(nil)
}