github.com/bcnmy/go-ethereum@v1.10.27/cmd/abigen/main.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  	"os"
    24  	"regexp"
    25  	"strings"
    26  
    27  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    28  	"github.com/ethereum/go-ethereum/cmd/utils"
    29  	"github.com/ethereum/go-ethereum/common/compiler"
    30  	"github.com/ethereum/go-ethereum/crypto"
    31  	"github.com/ethereum/go-ethereum/internal/flags"
    32  	"github.com/ethereum/go-ethereum/log"
    33  	"github.com/urfave/cli/v2"
    34  )
    35  
    36  var (
    37  	// Git SHA1 commit hash of the release (set via linker flags)
    38  	gitCommit = ""
    39  	gitDate   = ""
    40  
    41  	app *cli.App
    42  )
    43  
    44  var (
    45  	// Flags needed by abigen
    46  	abiFlag = &cli.StringFlag{
    47  		Name:  "abi",
    48  		Usage: "Path to the Ethereum contract ABI json to bind, - for STDIN",
    49  	}
    50  	binFlag = &cli.StringFlag{
    51  		Name:  "bin",
    52  		Usage: "Path to the Ethereum contract bytecode (generate deploy method)",
    53  	}
    54  	typeFlag = &cli.StringFlag{
    55  		Name:  "type",
    56  		Usage: "Struct name for the binding (default = package name)",
    57  	}
    58  	jsonFlag = &cli.StringFlag{
    59  		Name:  "combined-json",
    60  		Usage: "Path to the combined-json file generated by compiler, - for STDIN",
    61  	}
    62  	excFlag = &cli.StringFlag{
    63  		Name:  "exc",
    64  		Usage: "Comma separated types to exclude from binding",
    65  	}
    66  	pkgFlag = &cli.StringFlag{
    67  		Name:  "pkg",
    68  		Usage: "Package name to generate the binding into",
    69  	}
    70  	outFlag = &cli.StringFlag{
    71  		Name:  "out",
    72  		Usage: "Output file for the generated binding (default = stdout)",
    73  	}
    74  	langFlag = &cli.StringFlag{
    75  		Name:  "lang",
    76  		Usage: "Destination language for the bindings (go, java, objc)",
    77  		Value: "go",
    78  	}
    79  	aliasFlag = &cli.StringFlag{
    80  		Name:  "alias",
    81  		Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2",
    82  	}
    83  )
    84  
    85  func init() {
    86  	app = flags.NewApp(gitCommit, gitDate, "ethereum checkpoint helper tool")
    87  	app.Name = "abigen"
    88  	app.Flags = []cli.Flag{
    89  		abiFlag,
    90  		binFlag,
    91  		typeFlag,
    92  		jsonFlag,
    93  		excFlag,
    94  		pkgFlag,
    95  		outFlag,
    96  		langFlag,
    97  		aliasFlag,
    98  	}
    99  	app.Action = abigen
   100  }
   101  
   102  func abigen(c *cli.Context) error {
   103  	utils.CheckExclusive(c, abiFlag, jsonFlag) // Only one source can be selected.
   104  
   105  	if c.String(pkgFlag.Name) == "" {
   106  		utils.Fatalf("No destination package specified (--pkg)")
   107  	}
   108  	var lang bind.Lang
   109  	switch c.String(langFlag.Name) {
   110  	case "go":
   111  		lang = bind.LangGo
   112  	case "java":
   113  		lang = bind.LangJava
   114  	case "objc":
   115  		lang = bind.LangObjC
   116  		utils.Fatalf("Objc binding generation is uncompleted")
   117  	default:
   118  		utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.String(langFlag.Name))
   119  	}
   120  	// If the entire solidity code was specified, build and bind based on that
   121  	var (
   122  		abis    []string
   123  		bins    []string
   124  		types   []string
   125  		sigs    []map[string]string
   126  		libs    = make(map[string]string)
   127  		aliases = make(map[string]string)
   128  	)
   129  	if c.String(abiFlag.Name) != "" {
   130  		// Load up the ABI, optional bytecode and type name from the parameters
   131  		var (
   132  			abi []byte
   133  			err error
   134  		)
   135  		input := c.String(abiFlag.Name)
   136  		if input == "-" {
   137  			abi, err = io.ReadAll(os.Stdin)
   138  		} else {
   139  			abi, err = os.ReadFile(input)
   140  		}
   141  		if err != nil {
   142  			utils.Fatalf("Failed to read input ABI: %v", err)
   143  		}
   144  		abis = append(abis, string(abi))
   145  
   146  		var bin []byte
   147  		if binFile := c.String(binFlag.Name); binFile != "" {
   148  			if bin, err = os.ReadFile(binFile); err != nil {
   149  				utils.Fatalf("Failed to read input bytecode: %v", err)
   150  			}
   151  			if strings.Contains(string(bin), "//") {
   152  				utils.Fatalf("Contract has additional library references, please use other mode(e.g. --combined-json) to catch library infos")
   153  			}
   154  		}
   155  		bins = append(bins, string(bin))
   156  
   157  		kind := c.String(typeFlag.Name)
   158  		if kind == "" {
   159  			kind = c.String(pkgFlag.Name)
   160  		}
   161  		types = append(types, kind)
   162  	} else {
   163  		// Generate the list of types to exclude from binding
   164  		exclude := make(map[string]bool)
   165  		for _, kind := range strings.Split(c.String(excFlag.Name), ",") {
   166  			exclude[strings.ToLower(kind)] = true
   167  		}
   168  		var contracts map[string]*compiler.Contract
   169  
   170  		if c.IsSet(jsonFlag.Name) {
   171  			var (
   172  				input      = c.String(jsonFlag.Name)
   173  				jsonOutput []byte
   174  				err        error
   175  			)
   176  			if input == "-" {
   177  				jsonOutput, err = io.ReadAll(os.Stdin)
   178  			} else {
   179  				jsonOutput, err = os.ReadFile(input)
   180  			}
   181  			if err != nil {
   182  				utils.Fatalf("Failed to read combined-json: %v", err)
   183  			}
   184  			contracts, err = compiler.ParseCombinedJSON(jsonOutput, "", "", "", "")
   185  			if err != nil {
   186  				utils.Fatalf("Failed to read contract information from json output: %v", err)
   187  			}
   188  		}
   189  		// Gather all non-excluded contract for binding
   190  		for name, contract := range contracts {
   191  			if exclude[strings.ToLower(name)] {
   192  				continue
   193  			}
   194  			abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
   195  			if err != nil {
   196  				utils.Fatalf("Failed to parse ABIs from compiler output: %v", err)
   197  			}
   198  			abis = append(abis, string(abi))
   199  			bins = append(bins, contract.Code)
   200  			sigs = append(sigs, contract.Hashes)
   201  			nameParts := strings.Split(name, ":")
   202  			types = append(types, nameParts[len(nameParts)-1])
   203  
   204  			// Derive the library placeholder which is a 34 character prefix of the
   205  			// hex encoding of the keccak256 hash of the fully qualified library name.
   206  			// Note that the fully qualified library name is the path of its source
   207  			// file and the library name separated by ":".
   208  			libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] // the first 2 chars are 0x
   209  			libs[libPattern] = nameParts[len(nameParts)-1]
   210  		}
   211  	}
   212  	// Extract all aliases from the flags
   213  	if c.IsSet(aliasFlag.Name) {
   214  		// We support multi-versions for aliasing
   215  		// e.g.
   216  		//      foo=bar,foo2=bar2
   217  		//      foo:bar,foo2:bar2
   218  		re := regexp.MustCompile(`(?:(\w+)[:=](\w+))`)
   219  		submatches := re.FindAllStringSubmatch(c.String(aliasFlag.Name), -1)
   220  		for _, match := range submatches {
   221  			aliases[match[1]] = match[2]
   222  		}
   223  	}
   224  	// Generate the contract binding
   225  	code, err := bind.Bind(types, abis, bins, sigs, c.String(pkgFlag.Name), lang, libs, aliases)
   226  	if err != nil {
   227  		utils.Fatalf("Failed to generate ABI binding: %v", err)
   228  	}
   229  	// Either flush it out to a file or display on the standard output
   230  	if !c.IsSet(outFlag.Name) {
   231  		fmt.Printf("%s\n", code)
   232  		return nil
   233  	}
   234  	if err := os.WriteFile(c.String(outFlag.Name), []byte(code), 0600); err != nil {
   235  		utils.Fatalf("Failed to write ABI binding: %v", err)
   236  	}
   237  	return nil
   238  }
   239  
   240  func main() {
   241  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
   242  
   243  	if err := app.Run(os.Args); err != nil {
   244  		fmt.Fprintln(os.Stderr, err)
   245  		os.Exit(1)
   246  	}
   247  }