go-ethereum – How to Customize Commands in Geth Console

go-ethereumjavascriptjson-rpc

How to customize my own commands in geth console?

We know that in geth console, we can type eth.accounts and other commands.
I found that there is a JavaScript parser/interpreter named Otto which does this, But how to add a new command such as eth.mycommand in geth console?

Thank you very much.

Best Answer

You can modify source code to achieve, creating a local private chain.

  1. Install go

  2. Clone go-ethereum project by git clone https://github.com/ethereum/go-ethereum.git

  3. Rebuild all commands by make all, for instance geth
  4. Test whether everything is ok. ./build/bin/geth --datadir=./dev/data0 --networkid 2 console. At first you should create directory ./dev/data0 to save chain data. If Ok, now you have entered geth console.

Now, we modify the source code. when geth starting, a thread will be created to interact with console by Interactive method, and last console.Evaluate() will deal with input command. So you can implement your logic in here. Now we define a eth.custom(params) command to show say-hello. Modify source code as follows:

// Evaluate executes code and pretty prints the result to the specified output
// stream.
func (c *Console) Evaluate(statement string) error {
    //fmt.Println(isCustomCommand(statement))
    if (isCustomCommand(statement)) {//custom command,return
        result := "Hello " + statement[strings.Index(statement,"\"")+1:len(statement)-3]
        log.Info(result)
        return nil
    }
    defer func() {
        if r := recover(); r != nil {
            fmt.Fprintf(c.printer, "[native] error: %v\n", r)
        }
    }()
    return c.jsre.Evaluate(statement, c.printer)
}

//our custom is eth.custom(param)
func isCustomCommand(input string) bool{
    return strings.HasPrefix(input,"eth.custom")
}

If you input eth.custom("BinBin"), it shows Hello BinBin on terminal. Now execute

make all

command to rebuild, and then execute command to enter console:

./build/bin/geth --datadir=./dev/data0 --networkid 2  console

Now, we start test, input command as follows:

eth.custom("BinBin")

and the result is

enter image description here

perfect!
Hope it helps~

Related Topic