solidity.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package compiler wraps the Solidity compiler executable (solc).
  17. package compiler
  18. import (
  19. "bytes"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io/ioutil"
  24. "os/exec"
  25. "regexp"
  26. "strconv"
  27. "strings"
  28. )
  29. var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`)
  30. // Contract contains information about a compiled contract, alongside its code and runtime code.
  31. type Contract struct {
  32. Code string `json:"code"`
  33. RuntimeCode string `json:"runtime-code"`
  34. Info ContractInfo `json:"info"`
  35. }
  36. // ContractInfo contains information about a compiled contract, including access
  37. // to the ABI definition, source mapping, user and developer docs, and metadata.
  38. //
  39. // Depending on the source, language version, compiler version, and compiler
  40. // options will provide information about how the contract was compiled.
  41. type ContractInfo struct {
  42. Source string `json:"source"`
  43. Language string `json:"language"`
  44. LanguageVersion string `json:"languageVersion"`
  45. CompilerVersion string `json:"compilerVersion"`
  46. CompilerOptions string `json:"compilerOptions"`
  47. SrcMap string `json:"srcMap"`
  48. SrcMapRuntime string `json:"srcMapRuntime"`
  49. AbiDefinition interface{} `json:"abiDefinition"`
  50. UserDoc interface{} `json:"userDoc"`
  51. DeveloperDoc interface{} `json:"developerDoc"`
  52. Metadata string `json:"metadata"`
  53. }
  54. // Solidity contains information about the solidity compiler.
  55. type Solidity struct {
  56. Path, Version, FullVersion string
  57. Major, Minor, Patch int
  58. }
  59. // --combined-output format
  60. type solcOutput struct {
  61. Contracts map[string]struct {
  62. BinRuntime string `json:"bin-runtime"`
  63. SrcMapRuntime string `json:"srcmap-runtime"`
  64. Bin, SrcMap, Abi, Devdoc, Userdoc, Metadata string
  65. }
  66. Version string
  67. }
  68. func (s *Solidity) makeArgs() []string {
  69. p := []string{
  70. "--combined-json", "bin,bin-runtime,srcmap,srcmap-runtime,abi,userdoc,devdoc",
  71. "--optimize", // code optimizer switched on
  72. }
  73. if s.Major > 0 || s.Minor > 4 || s.Patch > 6 {
  74. p[1] += ",metadata"
  75. }
  76. return p
  77. }
  78. // SolidityVersion runs solc and parses its version output.
  79. func SolidityVersion(solc string) (*Solidity, error) {
  80. if solc == "" {
  81. solc = "solc"
  82. }
  83. var out bytes.Buffer
  84. cmd := exec.Command(solc, "--version")
  85. cmd.Stdout = &out
  86. err := cmd.Run()
  87. if err != nil {
  88. return nil, err
  89. }
  90. matches := versionRegexp.FindStringSubmatch(out.String())
  91. if len(matches) != 4 {
  92. return nil, fmt.Errorf("can't parse solc version %q", out.String())
  93. }
  94. s := &Solidity{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
  95. if s.Major, err = strconv.Atoi(matches[1]); err != nil {
  96. return nil, err
  97. }
  98. if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
  99. return nil, err
  100. }
  101. if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
  102. return nil, err
  103. }
  104. return s, nil
  105. }
  106. // CompileSolidityString builds and returns all the contracts contained within a source string.
  107. func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
  108. if len(source) == 0 {
  109. return nil, errors.New("solc: empty source string")
  110. }
  111. s, err := SolidityVersion(solc)
  112. if err != nil {
  113. return nil, err
  114. }
  115. args := append(s.makeArgs(), "--")
  116. cmd := exec.Command(s.Path, append(args, "-")...)
  117. cmd.Stdin = strings.NewReader(source)
  118. return s.run(cmd, source)
  119. }
  120. // CompileSolidity compiles all given Solidity source files.
  121. func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
  122. if len(sourcefiles) == 0 {
  123. return nil, errors.New("solc: no source files")
  124. }
  125. source, err := slurpFiles(sourcefiles)
  126. if err != nil {
  127. return nil, err
  128. }
  129. s, err := SolidityVersion(solc)
  130. if err != nil {
  131. return nil, err
  132. }
  133. args := append(s.makeArgs(), "--")
  134. cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
  135. return s.run(cmd, source)
  136. }
  137. func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
  138. var stderr, stdout bytes.Buffer
  139. cmd.Stderr = &stderr
  140. cmd.Stdout = &stdout
  141. if err := cmd.Run(); err != nil {
  142. return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
  143. }
  144. return ParseCombinedJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
  145. }
  146. // ParseCombinedJSON takes the direct output of a solc --combined-output run and
  147. // parses it into a map of string contract name to Contract structs. The
  148. // provided source, language and compiler version, and compiler options are all
  149. // passed through into the Contract structs.
  150. //
  151. // The solc output is expected to contain ABI, source mapping, user docs, and dev docs.
  152. //
  153. // Returns an error if the JSON is malformed or missing data, or if the JSON
  154. // embedded within the JSON is malformed.
  155. func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
  156. var output solcOutput
  157. if err := json.Unmarshal(combinedJSON, &output); err != nil {
  158. return nil, err
  159. }
  160. // Compilation succeeded, assemble and return the contracts.
  161. contracts := make(map[string]*Contract)
  162. for name, info := range output.Contracts {
  163. // Parse the individual compilation results.
  164. var abi interface{}
  165. if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
  166. return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
  167. }
  168. var userdoc interface{}
  169. if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
  170. return nil, fmt.Errorf("solc: error reading user doc: %v", err)
  171. }
  172. var devdoc interface{}
  173. if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
  174. return nil, fmt.Errorf("solc: error reading dev doc: %v", err)
  175. }
  176. contracts[name] = &Contract{
  177. Code: "0x" + info.Bin,
  178. RuntimeCode: "0x" + info.BinRuntime,
  179. Info: ContractInfo{
  180. Source: source,
  181. Language: "Solidity",
  182. LanguageVersion: languageVersion,
  183. CompilerVersion: compilerVersion,
  184. CompilerOptions: compilerOptions,
  185. SrcMap: info.SrcMap,
  186. SrcMapRuntime: info.SrcMapRuntime,
  187. AbiDefinition: abi,
  188. UserDoc: userdoc,
  189. DeveloperDoc: devdoc,
  190. Metadata: info.Metadata,
  191. },
  192. }
  193. }
  194. return contracts, nil
  195. }
  196. func slurpFiles(files []string) (string, error) {
  197. var concat bytes.Buffer
  198. for _, file := range files {
  199. content, err := ioutil.ReadFile(file)
  200. if err != nil {
  201. return "", err
  202. }
  203. concat.Write(content)
  204. }
  205. return concat.String(), nil
  206. }