github.com/jimmyx0x/go-ethereum@v1.10.28/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  	// Flags needed by abigen
    38  	abiFlag = &cli.StringFlag{
    39  		Name:  "abi",
    40  		Usage: "Path to the Ethereum contract ABI json to bind, - for STDIN",
    41  	}
    42  	binFlag = &cli.StringFlag{
    43  		Name:  "bin",
    44  		Usage: "Path to the Ethereum contract bytecode (generate deploy method)",
    45  	}
    46  	typeFlag = &cli.StringFlag{
    47  		Name:  "type",
    48  		Usage: "Struct name for the binding (default = package name)",
    49  	}
    50  	jsonFlag = &cli.StringFlag{
    51  		Name:  "combined-json",
    52  		Usage: "Path to the combined-json file generated by compiler, - for STDIN",
    53  	}
    54  	excFlag = &cli.StringFlag{
    55  		Name:  "exc",
    56  		Usage: "Comma separated types to exclude from binding",
    57  	}
    58  	pkgFlag = &cli.StringFlag{
    59  		Name:  "pkg",
    60  		Usage: "Package name to generate the binding into",
    61  	}
    62  	outFlag = &cli.StringFlag{
    63  		Name:  "out",
    64  		Usage: "Output file for the generated binding (default = stdout)",
    65  	}
    66  	langFlag = &cli.StringFlag{
    67  		Name:  "lang",
    68  		Usage: "Destination language for the bindings (go, java, objc)",
    69  		Value: "go",
    70  	}
    71  	aliasFlag = &cli.StringFlag{
    72  		Name:  "alias",
    73  		Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2",
    74  	}
    75  )
    76  
    77  var app = flags.NewApp("Ethereum ABI wrapper code generator")
    78  
    79  func init() {
    80  	app.Name = "abigen"
    81  	app.Flags = []cli.Flag{
    82  		abiFlag,
    83  		binFlag,
    84  		typeFlag,
    85  		jsonFlag,
    86  		excFlag,
    87  		pkgFlag,
    88  		outFlag,
    89  		langFlag,
    90  		aliasFlag,
    91  	}
    92  	app.Action = abigen
    93  }
    94  
    95  func abigen(c *cli.Context) error {
    96  	utils.CheckExclusive(c, abiFlag, jsonFlag) // Only one source can be selected.
    97  
    98  	if c.String(pkgFlag.Name) == "" {
    99  		utils.Fatalf("No destination package specified (--pkg)")
   100  	}
   101  	var lang bind.Lang
   102  	switch c.String(langFlag.Name) {
   103  	case "go":
   104  		lang = bind.LangGo
   105  	case "java":
   106  		lang = bind.LangJava
   107  	case "objc":
   108  		lang = bind.LangObjC
   109  		utils.Fatalf("Objc binding generation is uncompleted")
   110  	default:
   111  		utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.String(langFlag.Name))
   112  	}
   113  	// If the entire solidity code was specified, build and bind based on that
   114  	var (
   115  		abis    []string
   116  		bins    []string
   117  		types   []string
   118  		sigs    []map[string]string
   119  		libs    = make(map[string]string)
   120  		aliases = make(map[string]string)
   121  	)
   122  	if c.String(abiFlag.Name) != "" {
   123  		// Load up the ABI, optional bytecode and type name from the parameters
   124  		var (
   125  			abi []byte
   126  			err error
   127  		)
   128  		input := c.String(abiFlag.Name)
   129  		if input == "-" {
   130  			abi, err = io.ReadAll(os.Stdin)
   131  		} else {
   132  			abi, err = os.ReadFile(input)
   133  		}
   134  		if err != nil {
   135  			utils.Fatalf("Failed to read input ABI: %v", err)
   136  		}
   137  		abis = append(abis, string(abi))
   138  
   139  		var bin []byte
   140  		if binFile := c.String(binFlag.Name); binFile != "" {
   141  			if bin, err = os.ReadFile(binFile); err != nil {
   142  				utils.Fatalf("Failed to read input bytecode: %v", err)
   143  			}
   144  			if strings.Contains(string(bin), "//") {
   145  				utils.Fatalf("Contract has additional library references, please use other mode(e.g. --combined-json) to catch library infos")
   146  			}
   147  		}
   148  		bins = append(bins, string(bin))
   149  
   150  		kind := c.String(typeFlag.Name)
   151  		if kind == "" {
   152  			kind = c.String(pkgFlag.Name)
   153  		}
   154  		types = append(types, kind)
   155  	} else {
   156  		// Generate the list of types to exclude from binding
   157  		var exclude *nameFilter
   158  		if c.IsSet(excFlag.Name) {
   159  			var err error
   160  			if exclude, err = newNameFilter(strings.Split(c.String(excFlag.Name), ",")...); err != nil {
   161  				utils.Fatalf("Failed to parse excludes: %v", err)
   162  			}
   163  		}
   164  		var contracts map[string]*compiler.Contract
   165  
   166  		if c.IsSet(jsonFlag.Name) {
   167  			var (
   168  				input      = c.String(jsonFlag.Name)
   169  				jsonOutput []byte
   170  				err        error
   171  			)
   172  			if input == "-" {
   173  				jsonOutput, err = io.ReadAll(os.Stdin)
   174  			} else {
   175  				jsonOutput, err = os.ReadFile(input)
   176  			}
   177  			if err != nil {
   178  				utils.Fatalf("Failed to read combined-json: %v", err)
   179  			}
   180  			contracts, err = compiler.ParseCombinedJSON(jsonOutput, "", "", "", "")
   181  			if err != nil {
   182  				utils.Fatalf("Failed to read contract information from json output: %v", err)
   183  			}
   184  		}
   185  		// Gather all non-excluded contract for binding
   186  		for name, contract := range contracts {
   187  			// fully qualified name is of the form <solFilePath>:<type>
   188  			nameParts := strings.Split(name, ":")
   189  			typeName := nameParts[len(nameParts)-1]
   190  			if exclude != nil && exclude.Matches(name) {
   191  				fmt.Fprintf(os.Stderr, "excluding: %v\n", 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  			types = append(types, typeName)
   202  
   203  			// Derive the library placeholder which is a 34 character prefix of the
   204  			// hex encoding of the keccak256 hash of the fully qualified library name.
   205  			// Note that the fully qualified library name is the path of its source
   206  			// file and the library name separated by ":".
   207  			libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] // the first 2 chars are 0x
   208  			libs[libPattern] = typeName
   209  		}
   210  	}
   211  	// Extract all aliases from the flags
   212  	if c.IsSet(aliasFlag.Name) {
   213  		// We support multi-versions for aliasing
   214  		// e.g.
   215  		//      foo=bar,foo2=bar2
   216  		//      foo:bar,foo2:bar2
   217  		re := regexp.MustCompile(`(?:(\w+)[:=](\w+))`)
   218  		submatches := re.FindAllStringSubmatch(c.String(aliasFlag.Name), -1)
   219  		for _, match := range submatches {
   220  			aliases[match[1]] = match[2]
   221  		}
   222  	}
   223  	// Generate the contract binding
   224  	code, err := bind.Bind(types, abis, bins, sigs, c.String(pkgFlag.Name), lang, libs, aliases)
   225  	if err != nil {
   226  		utils.Fatalf("Failed to generate ABI binding: %v", err)
   227  	}
   228  	// Either flush it out to a file or display on the standard output
   229  	if !c.IsSet(outFlag.Name) {
   230  		fmt.Printf("%s\n", code)
   231  		return nil
   232  	}
   233  	if err := os.WriteFile(c.String(outFlag.Name), []byte(code), 0600); err != nil {
   234  		utils.Fatalf("Failed to write ABI binding: %v", err)
   235  	}
   236  	return nil
   237  }
   238  
   239  func main() {
   240  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
   241  
   242  	if err := app.Run(os.Args); err != nil {
   243  		fmt.Fprintln(os.Stderr, err)
   244  		os.Exit(1)
   245  	}
   246  }