solidity.go 5.6 KB

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