forked from terra-money/mantlemint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
288 lines (241 loc) · 7.63 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"os"
"runtime/debug"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/mux"
"github.com/spf13/viper"
tmlog "github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/proxy"
tendermint "github.com/tendermint/tendermint/types"
terra "github.com/terra-money/core/v2/app"
coreconfig "github.com/terra-money/core/v2/app/config"
wasmconfig "github.com/terra-money/core/v2/app/wasmconfig"
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/richlist"
"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"
tmdb "github.com/tendermint/tm-db"
)
// initialize mantlemint for v0.34.x
func main() {
mantlemintConfig := config.GetConfig()
mantlemintConfig.Print()
sdkConfig := sdk.GetConfig()
sdkConfig.SetCoinType(coreconfig.CoinType)
accountPubKeyPrefix := coreconfig.AccountAddressPrefix + "pub"
validatorAddressPrefix := coreconfig.AccountAddressPrefix + "valoper"
validatorPubKeyPrefix := coreconfig.AccountAddressPrefix + "valoperpub"
consNodeAddressPrefix := coreconfig.AccountAddressPrefix + "valcons"
consNodePubKeyPrefix := coreconfig.AccountAddressPrefix + "valconspub"
sdkConfig.SetBech32PrefixForAccount(coreconfig.AccountAddressPrefix, accountPubKeyPrefix)
sdkConfig.SetBech32PrefixForValidator(validatorAddressPrefix, validatorPubKeyPrefix)
sdkConfig.SetBech32PrefixForConsensusNode(consNodeAddressPrefix, consNodePubKeyPrefix)
sdkConfig.SetAddressVerifier(wasmtypes.VerifyAddressLen())
err := sdk.RegisterDenom(coreconfig.BondDenom, sdk.NewDecWithPrec(1, 6))
if err != nil {
panic(err)
}
sdkConfig.Seal()
ldb, ldbErr := heleveldb.NewLevelDBDriver(&heleveldb.DriverConfig{
Name: mantlemintConfig.MantlemintDB,
Dir: mantlemintConfig.Home,
Mode: heleveldb.DriverModeKeySuffixDesc,
})
if ldbErr != nil {
panic(ldbErr)
}
var 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, hldb, logger)
vpr := viper.GetViper()
var app = terra.NewTerraApp(
logger,
batched,
nil,
true, // need this so KVStores are set
make(map[int64]bool),
mantlemintConfig.Home,
0,
codec,
vpr,
wasmconfig.GetConfig(vpr),
fauxMerkleModeOpt,
func(ba *baseapp.BaseApp) {
ba.SetCMS(cms)
},
)
// create app...
var appCreator = mantlemint.NewConcurrentQueryClientCreator(app)
appConns := proxy.NewAppConns(appCreator)
appConns.SetLogger(logger)
if startErr := appConns.OnStart(); startErr != nil {
panic(startErr)
}
go func() {
a := <-appConns.Quit()
fmt.Println(a)
}()
var executor = mantlemint.NewMantlemintExecutor(batched, appConns.Consensus())
var 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, app)
if indexerInstanceErr != nil {
panic(indexerInstanceErr)
}
indexerInstance.RegisterIndexerService("tx", tx.IndexTx)
indexerInstance.RegisterIndexerService("block", block.IndexBlock)
indexerInstance.RegisterIndexerService("richlist", richlist.IndexRichlist)
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)
indexerInstance.RegisterRESTRoute(router, richlist.RegisterRESTRoute)
},
// inject flag checker for synced
blockFeed.IsSynced,
mantlemintConfig,
)
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 tmdb.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, _ := ioutil.ReadFile(genesisPath)
shasum := sha1.New()
shasum.Write(jsonBlob)
sum := hex.EncodeToString(shasum.Sum(nil))
log.Printf("[v0.34.x/sync] genesis shasum=%s", sum)
if genesis, genesisErr := tendermint.GenesisDocFromFile(genesisPath); genesisErr != nil {
panic(genesisErr)
} else {
return genesis
}
}
func forever() {
<-(chan int)(nil)
}