main.go 7.0 KB

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