github.com/amazechain/amc@v0.1.3/cmd/amc/initcmd.go (about) 1 package main 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "github.com/amazechain/amc/cmd/utils" 8 "github.com/amazechain/amc/common/block" 9 "github.com/amazechain/amc/common/types" 10 "github.com/amazechain/amc/conf" 11 "github.com/amazechain/amc/internal/node" 12 "github.com/amazechain/amc/log" 13 "github.com/amazechain/amc/modules/rawdb" 14 "github.com/ledgerwatch/erigon-lib/kv" 15 "github.com/urfave/cli/v2" 16 "os" 17 ) 18 19 var ( 20 initCommand = &cli.Command{ 21 Name: "init", 22 Usage: "Bootstrap and initialize a new genesis block", 23 ArgsUsage: "<genesisPath>", 24 Action: initGenesis, 25 Flags: []cli.Flag{ 26 DataDirFlag, 27 }, 28 Description: ` 29 The init command initializes a new genesis block and definition for the network. 30 This is a destructive action and changes the network in which you will be 31 participating. 32 33 It expects the genesis file as argument.`, 34 } 35 ) 36 37 // initGenesis will initialise the given JSON format genesis file and writes it as 38 // the zero'd block (i.e. genesis) or will fail hard if it can't succeed. 39 func initGenesis(cliCtx *cli.Context) error { 40 var ( 41 err error 42 genesisBlock *block.Block 43 ) 44 45 // Make sure we have a valid genesis JSON 46 genesisPath := cliCtx.Args().First() 47 if len(genesisPath) == 0 { 48 utils.Fatalf("Must supply path to genesis JSON file") 49 } 50 51 file, err := os.Open(genesisPath) 52 if err != nil { 53 utils.Fatalf("Failed to read genesis file: %v", err) 54 } 55 defer file.Close() 56 57 genesis := new(conf.Genesis) 58 if err := json.NewDecoder(file).Decode(genesis); err != nil { 59 utils.Fatalf("invalid genesis file: %v", err) 60 } 61 62 chaindb, err := node.OpenDatabase(&DefaultConfig, nil, kv.ChainDB.String()) 63 if err != nil { 64 utils.Fatalf("Failed to open database: %v", err) 65 } 66 defer chaindb.Close() 67 68 if err := chaindb.Update(context.TODO(), func(tx kv.RwTx) error { 69 storedHash, err := rawdb.ReadCanonicalHash(tx, 0) 70 if err != nil { 71 return err 72 } 73 74 if storedHash != (types.Hash{}) { 75 return fmt.Errorf("genesis state are already exists") 76 77 } 78 genesisBlock, err = node.WriteGenesisBlock(tx, genesis) 79 if nil != err { 80 return err 81 } 82 if err := node.WriteChainConfig(tx, genesisBlock.Hash(), genesis); err != nil { 83 return err 84 } 85 return nil 86 }); err != nil { 87 utils.Fatalf("Failed to wrote genesis state to database: %w", err) 88 } 89 log.Info("Successfully wrote genesis state", "hash", genesisBlock.Hash()) 90 return nil 91 }