How to use init method of proxyapp Package

Best Syzkaller code snippet using proxyapp.init

replay_test.go

Source:replay_test.go Github

copy

Full Screen

...24 sm "github.com/tendermint/tendermint/state"25 "github.com/tendermint/tendermint/types"26)27var consensusReplayConfig *cfg.Config28func init() {29 consensusReplayConfig = ResetConfig("consensus_replay_test")30}31// These tests ensure we can always recover from failure at any part of the consensus process.32// There are two general failure scenarios: failure during consensus, and failure while applying the block.33// Only the latter interacts with the app and store,34// but the former has to deal with restrictions on re-use of priv_validator keys.35// The `WAL Tests` are for failures during the consensus;36// the `Handshake Tests` are for failures in applying the block.37// With the help of the WAL, we can recover from it all!38//------------------------------------------------------------------------------------------39// WAL Tests40// TODO: It would be better to verify explicitly which states we can recover from without the wal41// and which ones we need the wal for - then we'd also be able to only flush the42// wal writer when we need to, instead of with every message.43func startNewConsensusStateAndWaitForBlock(t *testing.T, lastBlockHeight int64, blockDB dbm.DB, stateDB dbm.DB) {44 logger := log.TestingLogger()45 state, _ := sm.LoadStateFromDBOrGenesisFile(stateDB, consensusReplayConfig.GenesisFile())46 privValidator := loadPrivValidator(consensusReplayConfig)47 cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)48 cs.SetLogger(logger)49 bytes, _ := ioutil.ReadFile(cs.config.WalFile())50 // fmt.Printf("====== WAL: \n\r%s\n", bytes)51 t.Logf("====== WAL: \n\r%X\n", bytes)52 err := cs.Start()53 require.NoError(t, err)54 defer cs.Stop()55 // This is just a signal that we haven't halted; its not something contained56 // in the WAL itself. Assuming the consensus state is running, replay of any57 // WAL, including the empty one, should eventually be followed by a new58 // block, or else something is wrong.59 newBlockCh := make(chan interface{}, 1)60 err = cs.eventBus.Subscribe(context.Background(), testSubscriber, types.EventQueryNewBlock, newBlockCh)61 require.NoError(t, err)62 select {63 case <-newBlockCh:64 case <-time.After(60 * time.Second):65 t.Fatalf("Timed out waiting for new block (see trace above)")66 }67}68func sendTxs(cs *ConsensusState, ctx context.Context) {69 for i := 0; i < 256; i++ {70 select {71 case <-ctx.Done():72 return73 default:74 tx := []byte{byte(i)}75 cs.mempool.CheckTx(tx, nil)76 i++77 }78 }79}80// TestWALCrash uses crashing WAL to test we can recover from any WAL failure.81func TestWALCrash(t *testing.T) {82 testCases := []struct {83 name string84 initFn func(dbm.DB, *ConsensusState, context.Context)85 heightToStop int6486 }{87 {"empty block",88 func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {},89 1},90 {"many non-empty blocks",91 func(stateDB dbm.DB, cs *ConsensusState, ctx context.Context) {92 go sendTxs(cs, ctx)93 },94 3},95 }96 for _, tc := range testCases {97 t.Run(tc.name, func(t *testing.T) {98 crashWALandCheckLiveness(t, tc.initFn, tc.heightToStop)99 })100 }101}102func crashWALandCheckLiveness(t *testing.T, initFn func(dbm.DB, *ConsensusState, context.Context), heightToStop int64) {103 walPaniced := make(chan error)104 crashingWal := &crashingWAL{panicCh: walPaniced, heightToStop: heightToStop}105 i := 1106LOOP:107 for {108 // fmt.Printf("====== LOOP %d\n", i)109 t.Logf("====== LOOP %d\n", i)110 // create consensus state from a clean slate111 logger := log.NewNopLogger()112 stateDB := dbm.NewMemDB()113 state, _ := sm.MakeGenesisStateFromFile(consensusReplayConfig.GenesisFile())114 privValidator := loadPrivValidator(consensusReplayConfig)115 blockDB := dbm.NewMemDB()116 cs := newConsensusStateWithConfigAndBlockStore(consensusReplayConfig, state, privValidator, kvstore.NewKVStoreApplication(), blockDB)117 cs.SetLogger(logger)118 // start sending transactions119 ctx, cancel := context.WithCancel(context.Background())120 initFn(stateDB, cs, ctx)121 // clean up WAL file from the previous iteration122 walFile := cs.config.WalFile()123 os.Remove(walFile)124 // set crashing WAL125 csWal, err := cs.OpenWAL(walFile)126 require.NoError(t, err)127 crashingWal.next = csWal128 // reset the message counter129 crashingWal.msgIndex = 1130 cs.wal = crashingWal131 // start consensus state132 err = cs.Start()133 require.NoError(t, err)134 i++135 select {136 case err := <-walPaniced:137 t.Logf("WAL paniced: %v", err)138 // make sure we can make blocks after a crash139 startNewConsensusStateAndWaitForBlock(t, cs.Height, blockDB, stateDB)140 // stop consensus state and transactions sender (initFn)141 cs.Stop()142 cancel()143 // if we reached the required height, exit144 if _, ok := err.(ReachedHeightToStopError); ok {145 break LOOP146 }147 case <-time.After(10 * time.Second):148 t.Fatal("WAL did not panic for 10 seconds (check the log)")149 }150 }151}152// crashingWAL is a WAL which crashes or rather simulates a crash during Save153// (before and after). It remembers a message for which we last panicked154// (lastPanicedForMsgIndex), so we don't panic for it in subsequent iterations.155type crashingWAL struct {156 next WAL157 panicCh chan error158 heightToStop int64159 msgIndex int // current message index160 lastPanicedForMsgIndex int // last message for which we panicked161}162// WALWriteError indicates a WAL crash.163type WALWriteError struct {164 msg string165}166func (e WALWriteError) Error() string {167 return e.msg168}169// ReachedHeightToStopError indicates we've reached the required consensus170// height and may exit.171type ReachedHeightToStopError struct {172 height int64173}174func (e ReachedHeightToStopError) Error() string {175 return fmt.Sprintf("reached height to stop %d", e.height)176}177// Write simulate WAL's crashing by sending an error to the panicCh and then178// exiting the cs.receiveRoutine.179func (w *crashingWAL) Write(m WALMessage) {180 if endMsg, ok := m.(EndHeightMessage); ok {181 if endMsg.Height == w.heightToStop {182 w.panicCh <- ReachedHeightToStopError{endMsg.Height}183 runtime.Goexit()184 } else {185 w.next.Write(m)186 }187 return188 }189 if w.msgIndex > w.lastPanicedForMsgIndex {190 w.lastPanicedForMsgIndex = w.msgIndex191 _, file, line, _ := runtime.Caller(1)192 w.panicCh <- WALWriteError{fmt.Sprintf("failed to write %T to WAL (fileline: %s:%d)", m, file, line)}193 runtime.Goexit()194 } else {195 w.msgIndex++196 w.next.Write(m)197 }198}199func (w *crashingWAL) WriteSync(m WALMessage) {200 w.Write(m)201}202func (w *crashingWAL) Group() *auto.Group { return w.next.Group() }203func (w *crashingWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (gr *auto.GroupReader, found bool, err error) {204 return w.next.SearchForEndHeight(height, options)205}206func (w *crashingWAL) Start() error { return w.next.Start() }207func (w *crashingWAL) Stop() error { return w.next.Stop() }208func (w *crashingWAL) Wait() { w.next.Wait() }209//------------------------------------------------------------------------------------------210// Handshake Tests211const (212 NUM_BLOCKS = 6213)214var (215 mempool = sm.MockMempool{}216 evpool = sm.MockEvidencePool{}217)218//---------------------------------------219// Test handshake/replay220// 0 - all synced up221// 1 - saved block but app and state are behind222// 2 - save block and committed but state is behind223var modes = []uint{0, 1, 2}224// Sync from scratch225func TestHandshakeReplayAll(t *testing.T) {226 for _, m := range modes {227 testHandshakeReplay(t, 0, m)228 }229}230// Sync many, not from scratch231func TestHandshakeReplaySome(t *testing.T) {232 for _, m := range modes {233 testHandshakeReplay(t, 1, m)234 }235}236// Sync from lagging by one237func TestHandshakeReplayOne(t *testing.T) {238 for _, m := range modes {239 testHandshakeReplay(t, NUM_BLOCKS-1, m)240 }241}242// Sync from caught up243func TestHandshakeReplayNone(t *testing.T) {244 for _, m := range modes {245 testHandshakeReplay(t, NUM_BLOCKS, m)246 }247}248func tempWALWithData(data []byte) string {249 walFile, err := ioutil.TempFile("", "wal")250 if err != nil {251 panic(fmt.Errorf("failed to create temp WAL file: %v", err))252 }253 _, err = walFile.Write(data)254 if err != nil {255 panic(fmt.Errorf("failed to write to temp WAL file: %v", err))256 }257 if err := walFile.Close(); err != nil {258 panic(fmt.Errorf("failed to close temp WAL file: %v", err))259 }260 return walFile.Name()261}262// Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks263func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {264 config := ResetConfig("proxy_test_")265 walBody, err := WALWithNBlocks(NUM_BLOCKS)266 if err != nil {267 t.Fatal(err)268 }269 walFile := tempWALWithData(walBody)270 config.Consensus.SetWalFile(walFile)271 privVal := privval.LoadFilePV(config.PrivValidatorFile())272 wal, err := NewWAL(walFile)273 if err != nil {274 t.Fatal(err)275 }276 wal.SetLogger(log.TestingLogger())277 if err := wal.Start(); err != nil {278 t.Fatal(err)279 }280 defer wal.Stop()281 chain, commits, err := makeBlockchainFromWAL(wal)282 if err != nil {283 t.Fatalf(err.Error())284 }285 stateDB, state, store := stateAndStore(config, privVal.GetPubKey())286 store.chain = chain287 store.commits = commits288 // run the chain through state.ApplyBlock to build up the tendermint state289 state = buildTMStateFromChain(config, stateDB, state, chain, mode)290 latestAppHash := state.AppHash291 // make a new client creator292 kvstoreApp := kvstore.NewPersistentKVStoreApplication(path.Join(config.DBDir(), "2"))293 clientCreator2 := proxy.NewLocalClientCreator(kvstoreApp)294 if nBlocks > 0 {295 // run nBlocks against a new client to build up the app state.296 // use a throwaway tendermint state297 proxyApp := proxy.NewAppConns(clientCreator2)298 stateDB, state, _ := stateAndStore(config, privVal.GetPubKey())299 buildAppStateFromChain(proxyApp, stateDB, state, chain, nBlocks, mode)300 }301 // now start the app using the handshake - it should sync302 genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())303 handshaker := NewHandshaker(stateDB, state, store, genDoc)304 proxyApp := proxy.NewAppConns(clientCreator2)305 if err := proxyApp.Start(); err != nil {306 t.Fatalf("Error starting proxy app connections: %v", err)307 }308 defer proxyApp.Stop()309 if err := handshaker.Handshake(proxyApp); err != nil {310 t.Fatalf("Error on abci handshake: %v", err)311 }312 // get the latest app hash from the app313 res, err := proxyApp.Query().InfoSync(abci.RequestInfo{Version: ""})314 if err != nil {315 t.Fatal(err)316 }317 // the app hash should be synced up318 if !bytes.Equal(latestAppHash, res.LastBlockAppHash) {319 t.Fatalf("Expected app hashes to match after handshake/replay. got %X, expected %X", res.LastBlockAppHash, latestAppHash)320 }321 expectedBlocksToSync := NUM_BLOCKS - nBlocks322 if nBlocks == NUM_BLOCKS && mode > 0 {323 expectedBlocksToSync++324 } else if nBlocks > 0 && mode == 1 {325 expectedBlocksToSync++326 }327 if handshaker.NBlocks() != expectedBlocksToSync {328 t.Fatalf("Expected handshake to sync %d blocks, got %d", expectedBlocksToSync, handshaker.NBlocks())329 }330}331func applyBlock(stateDB dbm.DB, st sm.State, blk *types.Block, proxyApp proxy.AppConns) sm.State {332 testPartSize := types.BlockPartSizeBytes333 blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)334 blkID := types.BlockID{blk.Hash(), blk.MakePartSet(testPartSize).Header()}335 newState, err := blockExec.ApplyBlock(st, blkID, blk)336 if err != nil {337 panic(err)338 }339 return newState340}341func buildAppStateFromChain(proxyApp proxy.AppConns, stateDB dbm.DB,342 state sm.State, chain []*types.Block, nBlocks int, mode uint) {343 // start a new app without handshake, play nBlocks blocks344 if err := proxyApp.Start(); err != nil {345 panic(err)346 }347 defer proxyApp.Stop()348 validators := types.TM2PB.ValidatorUpdates(state.Validators)349 if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{350 Validators: validators,351 }); err != nil {352 panic(err)353 }354 switch mode {355 case 0:356 for i := 0; i < nBlocks; i++ {357 block := chain[i]358 state = applyBlock(stateDB, state, block, proxyApp)359 }360 case 1, 2:361 for i := 0; i < nBlocks-1; i++ {362 block := chain[i]363 state = applyBlock(stateDB, state, block, proxyApp)364 }365 if mode == 2 {366 // update the kvstore height and apphash367 // as if we ran commit but not368 state = applyBlock(stateDB, state, chain[nBlocks-1], proxyApp)369 }370 }371}372func buildTMStateFromChain(config *cfg.Config, stateDB dbm.DB, state sm.State, chain []*types.Block, mode uint) sm.State {373 // run the whole chain against this client to build up the tendermint state374 clientCreator := proxy.NewLocalClientCreator(kvstore.NewPersistentKVStoreApplication(path.Join(config.DBDir(), "1")))375 proxyApp := proxy.NewAppConns(clientCreator) // sm.NewHandshaker(config, state, store, ReplayLastBlock))376 if err := proxyApp.Start(); err != nil {377 panic(err)378 }379 defer proxyApp.Stop()380 validators := types.TM2PB.ValidatorUpdates(state.Validators)381 if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{382 Validators: validators,383 }); err != nil {384 panic(err)385 }386 switch mode {387 case 0:388 // sync right up389 for _, block := range chain {390 state = applyBlock(stateDB, state, block, proxyApp)391 }392 case 1, 2:393 // sync up to the penultimate as if we stored the block.394 // whether we commit or not depends on the appHash395 for _, block := range chain[:len(chain)-1] {396 state = applyBlock(stateDB, state, block, proxyApp)397 }398 // apply the final block to a state copy so we can399 // get the right next appHash but keep the state back400 applyBlock(stateDB, state, chain[len(chain)-1], proxyApp)401 }402 return state403}404//--------------------------405// utils for making blocks406func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {407 // Search for height marker408 gr, found, err := wal.SearchForEndHeight(0, &WALSearchOptions{})409 if err != nil {410 return nil, nil, err411 }412 if !found {413 return nil, nil, fmt.Errorf("WAL does not contain height %d.", 1)414 }415 defer gr.Close() // nolint: errcheck416 // log.Notice("Build a blockchain by reading from the WAL")417 var blocks []*types.Block418 var commits []*types.Commit419 var thisBlockParts *types.PartSet420 var thisBlockCommit *types.Commit421 var height int64422 dec := NewWALDecoder(gr)423 for {424 msg, err := dec.Decode()425 if err == io.EOF {426 break427 } else if err != nil {428 return nil, nil, err429 }430 piece := readPieceFromWAL(msg)431 if piece == nil {432 continue433 }434 switch p := piece.(type) {435 case EndHeightMessage:436 // if its not the first one, we have a full block437 if thisBlockParts != nil {438 var block = new(types.Block)439 _, err = cdc.UnmarshalBinaryReader(thisBlockParts.GetReader(), block, 0)440 if err != nil {441 panic(err)442 }443 if block.Height != height+1 {444 panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))445 }446 commitHeight := thisBlockCommit.Precommits[0].Height447 if commitHeight != height+1 {448 panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))449 }450 blocks = append(blocks, block)451 commits = append(commits, thisBlockCommit)452 height++453 }454 case *types.PartSetHeader:455 thisBlockParts = types.NewPartSetFromHeader(*p)456 case *types.Part:457 _, err := thisBlockParts.AddPart(p)458 if err != nil {459 return nil, nil, err460 }461 case *types.Vote:462 if p.Type == types.VoteTypePrecommit {463 thisBlockCommit = &types.Commit{464 BlockID: p.BlockID,465 Precommits: []*types.Vote{p},466 }467 }468 }469 }470 // grab the last block too471 var block = new(types.Block)472 _, err = cdc.UnmarshalBinaryReader(thisBlockParts.GetReader(), block, 0)473 if err != nil {474 panic(err)475 }476 if block.Height != height+1 {477 panic(fmt.Sprintf("read bad block from wal. got height %d, expected %d", block.Height, height+1))478 }479 commitHeight := thisBlockCommit.Precommits[0].Height480 if commitHeight != height+1 {481 panic(fmt.Sprintf("commit doesnt match. got height %d, expected %d", commitHeight, height+1))482 }483 blocks = append(blocks, block)484 commits = append(commits, thisBlockCommit)485 return blocks, commits, nil486}487func readPieceFromWAL(msg *TimedWALMessage) interface{} {488 // for logging489 switch m := msg.Msg.(type) {490 case msgInfo:491 switch msg := m.Msg.(type) {492 case *ProposalMessage:493 return &msg.Proposal.BlockPartsHeader494 case *BlockPartMessage:495 return msg.Part496 case *VoteMessage:497 return msg.Vote498 }499 case EndHeightMessage:500 return m501 }502 return nil503}504// fresh state and mock store505func stateAndStore(config *cfg.Config, pubKey crypto.PubKey) (dbm.DB, sm.State, *mockBlockStore) {506 stateDB := dbm.NewMemDB()507 state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile())508 store := NewMockBlockStore(config, state.ConsensusParams)509 return stateDB, state, store510}511//----------------------------------512// mock block store513type mockBlockStore struct {514 config *cfg.Config515 params types.ConsensusParams516 chain []*types.Block517 commits []*types.Commit518}519// TODO: NewBlockStore(db.NewMemDB) ...520func NewMockBlockStore(config *cfg.Config, params types.ConsensusParams) *mockBlockStore {521 return &mockBlockStore{config, params, nil, nil}522}523func (bs *mockBlockStore) Height() int64 { return int64(len(bs.chain)) }524func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain[height-1] }525func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta {526 block := bs.chain[height-1]527 return &types.BlockMeta{528 BlockID: types.BlockID{block.Hash(), block.MakePartSet(types.BlockPartSizeBytes).Header()},529 Header: block.Header,530 }531}532func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil }533func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {534}535func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit {536 return bs.commits[height-1]537}538func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit {539 return bs.commits[height-1]540}541//----------------------------------------542func TestInitChainUpdateValidators(t *testing.T) {543 val, _ := types.RandValidator(true, 10)544 vals := types.NewValidatorSet([]*types.Validator{val})545 app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}546 clientCreator := proxy.NewLocalClientCreator(app)547 config := ResetConfig("proxy_test_")548 privVal := privval.LoadFilePV(config.PrivValidatorFile())549 stateDB, state, store := stateAndStore(config, privVal.GetPubKey())550 oldValAddr := state.Validators.Validators[0].Address551 // now start the app using the handshake - it should sync552 genDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())553 handshaker := NewHandshaker(stateDB, state, store, genDoc)554 proxyApp := proxy.NewAppConns(clientCreator)555 if err := proxyApp.Start(); err != nil {556 t.Fatalf("Error starting proxy app connections: %v", err)557 }558 defer proxyApp.Stop()559 if err := handshaker.Handshake(proxyApp); err != nil {560 t.Fatalf("Error on abci handshake: %v", err)561 }562 // reload the state, check the validator set was updated563 state = sm.LoadState(stateDB)564 newValAddr := state.Validators.Validators[0].Address565 expectValAddr := val.Address566 assert.NotEqual(t, oldValAddr, newValAddr)567 assert.Equal(t, newValAddr, expectValAddr)568}569func newInitChainApp(vals []abci.ValidatorUpdate) *initChainApp {570 return &initChainApp{571 vals: vals,572 }573}574// returns the vals on InitChain575type initChainApp struct {576 abci.BaseApplication577 vals []abci.ValidatorUpdate578}579func (ica *initChainApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {580 return abci.ResponseInitChain{581 Validators: ica.vals,582 }583}...

Full Screen

Full Screen

replay.go

Source:replay.go Github

copy

Full Screen

1package main2import (3 "fmt"4 "io"5 "os"6 "path/filepath"7 "time"8 cpm "github.com/otiai10/copy"9 "github.com/spf13/cobra"10 abci "github.com/tendermint/tendermint/abci/types"11 cmn "github.com/tendermint/tendermint/libs/common"12 "github.com/tendermint/tendermint/proxy"13 tmsm "github.com/tendermint/tendermint/state"14 tmstore "github.com/tendermint/tendermint/store"15 tm "github.com/tendermint/tendermint/types"16 "github.com/cosmos/gaia/app"17 "github.com/cosmos/cosmos-sdk/baseapp"18 "github.com/cosmos/cosmos-sdk/server"19 "github.com/cosmos/cosmos-sdk/store"20 sdk "github.com/cosmos/cosmos-sdk/types"21)22func replayCmd() *cobra.Command {23 return &cobra.Command{24 Use: "replay <root-dir>",25 Short: "Replay gaia transactions",26 RunE: func(_ *cobra.Command, args []string) error {27 return replayTxs(args[0])28 },29 Args: cobra.ExactArgs(1),30 }31}32func replayTxs(rootDir string) error {33 if false {34 // Copy the rootDir to a new directory, to preserve the old one.35 fmt.Fprintln(os.Stderr, "Copying rootdir over")36 oldRootDir := rootDir37 rootDir = oldRootDir + "_replay"38 if cmn.FileExists(rootDir) {39 cmn.Exit(fmt.Sprintf("temporary copy dir %v already exists", rootDir))40 }41 if err := cpm.Copy(oldRootDir, rootDir); err != nil {42 return err43 }44 }45 configDir := filepath.Join(rootDir, "config")46 dataDir := filepath.Join(rootDir, "data")47 ctx := server.NewDefaultContext()48 // App DB49 // appDB := dbm.NewMemDB()50 fmt.Fprintln(os.Stderr, "Opening app database")51 appDB, err := sdk.NewLevelDB("application", dataDir)52 if err != nil {53 return err54 }55 // TM DB56 // tmDB := dbm.NewMemDB()57 fmt.Fprintln(os.Stderr, "Opening tendermint state database")58 tmDB, err := sdk.NewLevelDB("state", dataDir)59 if err != nil {60 return err61 }62 // Blockchain DB63 fmt.Fprintln(os.Stderr, "Opening blockstore database")64 bcDB, err := sdk.NewLevelDB("blockstore", dataDir)65 if err != nil {66 return err67 }68 // TraceStore69 var traceStoreWriter io.Writer70 var traceStoreDir = filepath.Join(dataDir, "trace.log")71 traceStoreWriter, err = os.OpenFile(72 traceStoreDir,73 os.O_WRONLY|os.O_APPEND|os.O_CREATE,74 0666,75 )76 if err != nil {77 return err78 }79 // Application80 fmt.Fprintln(os.Stderr, "Creating application")81 gapp := app.NewGaiaApp(82 ctx.Logger, appDB, traceStoreWriter, true, uint(1),83 baseapp.SetPruning(store.PruneEverything), // nothing84 )85 // Genesis86 var genDocPath = filepath.Join(configDir, "genesis.json")87 genDoc, err := tm.GenesisDocFromFile(genDocPath)88 if err != nil {89 return err90 }91 genState, err := tmsm.MakeGenesisState(genDoc)92 if err != nil {93 return err94 }95 // tmsm.SaveState(tmDB, genState)96 cc := proxy.NewLocalClientCreator(gapp)97 proxyApp := proxy.NewAppConns(cc)98 err = proxyApp.Start()99 if err != nil {100 return err101 }102 defer func() {103 _ = proxyApp.Stop()104 }()105 state := tmsm.LoadState(tmDB)106 if state.LastBlockHeight == 0 {107 // Send InitChain msg108 fmt.Fprintln(os.Stderr, "Sending InitChain msg")109 validators := tm.TM2PB.ValidatorUpdates(genState.Validators)110 csParams := tm.TM2PB.ConsensusParams(genDoc.ConsensusParams)111 req := abci.RequestInitChain{112 Time: genDoc.GenesisTime,113 ChainId: genDoc.ChainID,114 ConsensusParams: csParams,115 Validators: validators,116 AppStateBytes: genDoc.AppState,117 }118 res, err := proxyApp.Consensus().InitChainSync(req)119 if err != nil {120 return err121 }122 newValidatorz, err := tm.PB2TM.ValidatorUpdates(res.Validators)123 if err != nil {124 return err125 }126 newValidators := tm.NewValidatorSet(newValidatorz)127 // Take the genesis state.128 state = genState129 state.Validators = newValidators130 state.NextValidators = newValidators131 }132 // Create executor133 fmt.Fprintln(os.Stderr, "Creating block executor")134 blockExec := tmsm.NewBlockExecutor(tmDB, ctx.Logger, proxyApp.Consensus(), nil, tmsm.MockEvidencePool{})135 // Create block store136 fmt.Fprintln(os.Stderr, "Creating block store")137 blockStore := tmstore.NewBlockStore(bcDB)138 tz := []time.Duration{0, 0, 0}139 for i := int(state.LastBlockHeight) + 1; ; i++ {140 fmt.Fprintln(os.Stderr, "Running block ", i)141 t1 := time.Now()142 // Apply block143 fmt.Printf("loading and applying block %d\n", i)144 blockmeta := blockStore.LoadBlockMeta(int64(i))145 if blockmeta == nil {146 fmt.Printf("Couldn't find block meta %d... done?\n", i)147 return nil148 }149 block := blockStore.LoadBlock(int64(i))150 if block == nil {151 return fmt.Errorf("couldn't find block %d", i)152 }153 t2 := time.Now()154 state, err = blockExec.ApplyBlock(state, blockmeta.BlockID, block)155 if err != nil {156 return err157 }158 t3 := time.Now()159 tz[0] += t2.Sub(t1)160 tz[1] += t3.Sub(t2)161 fmt.Fprintf(os.Stderr, "new app hash: %X\n", state.AppHash)162 fmt.Fprintln(os.Stderr, tz)163 }164}...

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello from 2.go")4 fmt.Println("golenv.GetEnv(\"http_proxy\"):", golenv.GetEnv("http_proxy"))5 fmt.Println("golenv.GetEnv(\"https_proxy\"):", golenv.GetEnv("https_proxy"))6 fmt.Println("golenv.GetEnv(\"no_proxy\"):", golenv.GetEnv("no_proxy"))7 fmt.Println("golenv.GetEnv(\"HTTP_PROXY\"):", golenv.GetEnv("HTTP_PROXY"))8 fmt.Println("golenv.GetEnv(\"HTTPS_PROXY\"):", golenv.GetEnv("HTTPS_PROXY"))9 fmt.Println("golenv.GetEnv(\"NO_PROXY\"):", golenv.GetEnv("NO_PROXY"))10 fmt.Println("golenv.GetEnv(\"http_proxy\"):", golenv.GetEnv("http_proxy"))11 fmt.Println("golenv.GetEnv(\"https_proxy\"):", golenv.GetEnv("https_proxy"))12 fmt.Println("golenv.GetEnv(\"no_proxy\"):", golenv.GetEnv("no_proxy"))13 fmt.Println("golenv.GetEnv(\"HTTP_PROXY\"):", golenv.GetEnv("HTTP_PROXY"))14 fmt.Println("golenv.GetEnv(\"HTTPS_PROXY\"):", golenv.GetEnv("HTTPS_PROXY"))15 fmt.Println("golenv.GetEnv(\"NO_PROXY\"):", golenv.GetEnv("NO_PROXY"))16 fmt.Println("golenv.GetEnv(\"http_proxy\"):", golenv.GetEnv("http_proxy"))17 fmt.Println("golenv.GetEnv(\"https_proxy\"):", golenv.GetEnv("https_proxy"))18 fmt.Println("golenv.GetEnv(\"no_proxy\"):", golenv.GetEnv("no_proxy"))19 fmt.Println("golenv.GetEnv(\"HTTP_PROXY\"):", golenv.GetEnv("HTTP_PROXY"))20 fmt.Println("golenv.GetEnv(\"HTTPS_PROXY\"):", golenv.GetEnv("HTTPS_PROXY"))21 fmt.Println("golenv.GetEnv(\"NO_PROXY\"):", golenv.GetEnv("NO_PROXY"))22 fmt.Println("golenv.GetEnv(\"http_proxy\"):", golenv.GetEnv("http_proxy"))23 fmt.Println("golenv.GetEnv(\"https_proxy\"):", golenv.GetEnv("https_proxy"))24 fmt.Println("

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 beego.Run()4}5import (6func main() {7 beego.Run()8}9import (10func main() {11 beego.Run()12}13import (

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Cron started")4 c := cron.New()5 c.AddFunc("0/5 * * * * ?", proxyapp)6 c.Start()7 select {}8}9func proxyapp() {10 fmt.Println("Proxy app called")11}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2type ProxyApp struct {3}4func (p *ProxyApp) init() {5 fmt.Println("ProxyApp init")6}7func main() {8 proxyApp := &ProxyApp{}9 method := reflect.ValueOf(proxyApp).MethodByName("init")10 if method.IsValid() {11 methodType := method.Type()12 if methodType.NumIn() == 0 {13 if methodType.NumOut() == 0 {14 method.Call([]reflect.Value{})15 } else {16 fmt.Println("Method has return values")17 }18 } else {19 fmt.Println("Method has parameters")20 }21 } else {22 fmt.Println("Method not found")23 }24}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("main")4 proxyapp.ProxyApp.Init("test")5 proxyapp.ProxyApp.Print()6}7import (8type ProxyApp struct {9}10func (p ProxyApp) Init(name string) {11}12func (p ProxyApp) Print() {13 fmt.Println(p.name)14}15func init() {16 fmt.Println("init")17}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(proxyapp.ProxyApp())4}5import (6func main() {7 fmt.Println(proxyapp.ProxyApp())8}9import (10func main() {11 fmt.Println(proxyapp.ProxyApp())12}13import (14func main() {15 fmt.Println(proxyapp.ProxyApp())16}17import (18func main() {19 fmt.Println(proxyapp.ProxyApp())20}21import (22func main() {23 fmt.Println(proxyapp.ProxyApp())24}25import (26func main() {27 fmt.Println(proxyapp.ProxyApp())28}29import (30func main() {31 fmt.Println(proxyapp.ProxyApp())32}33import (34func main() {35 fmt.Println(proxyapp.ProxyApp())36}37import (38func main() {39 fmt.Println(proxyapp.ProxyApp())40}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 proxyapp.Init()5}6import (7func main() {8 fmt.Println("Hello, playground")9 proxyapp.Init()10}11import (12func main() {13 fmt.Println("Hello, playground")14 proxyapp.Init()15}16import (17func main() {18 fmt.Println("Hello, playground")19 proxyapp.Init()20}21import (22func main() {23 fmt.Println("Hello, playground")24 proxyapp.Init()25}26import (27func main() {28 fmt.Println("Hello, playground")29 proxyapp.Init()30}31import (32func main() {33 fmt.Println("Hello, playground")34 proxyapp.Init()35}36import (37func main() {38 fmt.Println("Hello, playground")39 proxyapp.Init()40}41import (

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxyapp := golproxyapp.New()4 proxyapp.Init()5 proxyapp.Run()6 os.Exit(0)7}8import (9func main() {10 proxyapp := golproxyapp.New()11 proxyapp.Init()12 proxyapp.Run()13 os.Exit(0)14}15import (16func main() {17 proxyapp := golproxyapp.New()18 proxyapp.Init()19 proxyapp.Run()20 os.Exit(0)21}22import (23func main() {24 proxyapp := golproxyapp.New()25 proxyapp.Init()26 proxyapp.Run()27 os.Exit(0)28}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("main method of 2.go")4 fmt.Println("main method of 2.go")5}6import (7func main() {8 fmt.Println("main method of 3.go")9 fmt.Println("main method of 3.go")10}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful