solidity.go 7.4 KB

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