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