solidity.go 6.6 KB

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