Block chain development command line operation module


Link: Blockchain project github address
Current progress of the project:
insert image description here

Features

Compared with the graphical user interface, using the command line to operate the blockchain is easier to write code, and it can also implement complex functions. The functions of the command line module should meet the following requirements:
1. Input without any parameters: output command line support function information
insert image description here

2. Input parameter addBlock -data "Alice send 100 eth to Bob" : Output
insert image description here3. Input parameter create:
Genesis block does not exist: Output Genesis block information
insert image description hereGenesis block exists: Output prompt
insert image description here4. Input parameter printChain
insert image description here

Introduction to flag usage in go language

The go language obtains command-line parameters and command-line operations through flags, and the steps can be classified into the following steps:
1. To create a new flagSet, you need to pass in named parameters

addBlockcmd := flag.NewFlagSet("addBlock", flag.ExitOnError)

2. The parameter default value setting
"data" indicates the parameter name, "Alice send 100 eth to Bob" indicates the default value, and "add data to block" indicates the parameter prompt information.

flagAddBlockArg := addBlockcmd.String("data", "Alice send 100 eth to Bob", "add data to block")

3. Determine the command type and activate the target flag.
os.args[1] indicates the parameters of the command, and os.args[0] is the name of the file to be executed, so it needs to be judged from the subscript 1.

switch os.Args[1] {
    
    
	case "addBlock":
		err := addBlockcmd.Parse(os.Args[2:])
		if err != nil {
    
    
			log.Panicf("parse the addBlockcmd failed%v\n", err)
		}
	}

4. Determine which flags are activated, and execute the target function
addBlockcmd.Parsed() to determine whether the flag is parsed, addBlockcmd is the flagset type

	if addBlockcmd.Parsed() {
    
    
		if *flagAddBlockArg == "" {
    
    
			//未输入-data的参数
			PrintUsage()
			os.Exit(1)
		}
		cli.addBlock(*flagAddBlockArg)
	}

Specific implementation of the project command line

1. Encapsulate the command line class to reduce the coupling between modules.

type CLI struct {
    
    
	BC *BlockChain
}

2. Create a new command line prompt, and use the command line to prompt if you don’t know the usage of the command line

// 命令行提示用法展示
func PrintUsage() {
    
    
	fmt.Println("Usage:  go run file.exe <command> [arguments]")
	//初始化区块链
	fmt.Printf("\tcreate              create a new blockchain\n")
	//添加区块
	fmt.Printf("\taddBlock   -data  	 add a new block\n")
	//遍历区块链
	fmt.Printf("\tprintChain          print the all message of blockchain\n")
}

3. Complete the function writing of the above three functions

// 初始化区块链
func (cli *CLI) createBlockchain() {
    
    
	CreateBlockChainWithGenesisBlock()
}

// 添加区块
func (cli *CLI) addBlock(data string) {
    
    
	if !DBExist() {
    
    
		fmt.Printf("DB haven't existed")
		os.Exit(1)
	}
	block := BlockChainObject()
	block.AddBlock([]byte(data))
}

// 打印区块完整信息
func (cli *CLI) printChain() {
    
    
	if !DBExist() {
    
    
		fmt.Printf("DB haven't existed")
		os.Exit(1)
	}
	block := BlockChainObject()
	block.PrintBlockChain()
}

4. Create a command line operation interface function run(), which is convenient to run in the main function. The specific idea of ​​run() is as follows:

  1. Create flagSet
  2. Set the parameters of the flagSet with parameters to default values
  3. Determine the command line string and parse the corresponding flag
  4. For the successfully parsed flag, find the corresponding function and run it

Compared with the introduction to flag usage , here is a new file judgment function and command line character judgment function when the genesis block is created, as follows:

// 参数数量检测函数
func IsValidArgs() {
    
    
//未输入任何功能需求
	if len(os.Args) < 2 {
    
    
		PrintUsage()
		os.Exit(1)
	}
}

os.Stat is a function for obtaining file information encapsulated by go language. If the file exists, various information about the file can be returned, and if the file does not exist, an error will be returned. You can use the returned error to detect and determine whether the file exists.

// 判断数据库文件是否存在
func DBExist() bool {
    
    
	if _, err := os.Stat(dbName); os.IsNotExist(err) {
    
    
		//数据库文件不存在
		return false
	}
	return true
}

Guess you like

Origin blog.csdn.net/qq_45931661/article/details/128546327