solidity.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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"
  24. "io/ioutil"
  25. "os"
  26. "os/exec"
  27. "regexp"
  28. "strings"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. )
  32. var (
  33. versionRegexp = regexp.MustCompile("[0-9]+\\.[0-9]+\\.[0-9]+")
  34. solcParams = []string{
  35. "--combined-json", "bin,abi,userdoc,devdoc",
  36. "--add-std", // include standard lib contracts
  37. "--optimize", // code optimizer switched on
  38. }
  39. )
  40. type Contract struct {
  41. Code string `json:"code"`
  42. Info ContractInfo `json:"info"`
  43. }
  44. type ContractInfo struct {
  45. Source string `json:"source"`
  46. Language string `json:"language"`
  47. LanguageVersion string `json:"languageVersion"`
  48. CompilerVersion string `json:"compilerVersion"`
  49. CompilerOptions string `json:"compilerOptions"`
  50. AbiDefinition interface{} `json:"abiDefinition"`
  51. UserDoc interface{} `json:"userDoc"`
  52. DeveloperDoc interface{} `json:"developerDoc"`
  53. }
  54. // Solidity contains information about the solidity compiler.
  55. type Solidity struct {
  56. Path, Version, FullVersion string
  57. }
  58. // --combined-output format
  59. type solcOutput struct {
  60. Contracts map[string]struct{ Bin, Abi, Devdoc, Userdoc string }
  61. Version string
  62. }
  63. // SolidityVersion runs solc and parses its version output.
  64. func SolidityVersion(solc string) (*Solidity, error) {
  65. if solc == "" {
  66. solc = "solc"
  67. }
  68. var out bytes.Buffer
  69. cmd := exec.Command(solc, "--version")
  70. cmd.Stdout = &out
  71. if err := cmd.Run(); err != nil {
  72. return nil, err
  73. }
  74. s := &Solidity{
  75. Path: cmd.Path,
  76. FullVersion: out.String(),
  77. Version: versionRegexp.FindString(out.String()),
  78. }
  79. return s, nil
  80. }
  81. // CompileSolidityString builds and returns all the contracts contained within a source string.
  82. func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
  83. if len(source) == 0 {
  84. return nil, errors.New("solc: empty source string")
  85. }
  86. if solc == "" {
  87. solc = "solc"
  88. }
  89. // Write source to a temporary file. Compiling stdin used to be supported
  90. // but seems to produce an exception with solc 0.3.5.
  91. infile, err := ioutil.TempFile("", "geth-compile-solidity")
  92. if err != nil {
  93. return nil, err
  94. }
  95. defer os.Remove(infile.Name())
  96. if _, err := io.WriteString(infile, source); err != nil {
  97. return nil, err
  98. }
  99. if err := infile.Close(); err != nil {
  100. return nil, err
  101. }
  102. return CompileSolidity(solc, infile.Name())
  103. }
  104. // CompileSolidity compiles all given Solidity source files.
  105. func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
  106. if len(sourcefiles) == 0 {
  107. return nil, errors.New("solc: no source ")
  108. }
  109. source, err := slurpFiles(sourcefiles)
  110. if err != nil {
  111. return nil, err
  112. }
  113. if solc == "" {
  114. solc = "solc"
  115. }
  116. var stderr, stdout bytes.Buffer
  117. args := append(solcParams, "--")
  118. cmd := exec.Command(solc, append(args, sourcefiles...)...)
  119. cmd.Stderr = &stderr
  120. cmd.Stdout = &stdout
  121. if err := cmd.Run(); err != nil {
  122. return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
  123. }
  124. var output solcOutput
  125. if err := json.Unmarshal(stdout.Bytes(), &output); err != nil {
  126. return nil, err
  127. }
  128. shortVersion := versionRegexp.FindString(output.Version)
  129. // Compilation succeeded, assemble and return the contracts.
  130. contracts := make(map[string]*Contract)
  131. for name, info := range output.Contracts {
  132. // Parse the individual compilation results.
  133. var abi interface{}
  134. if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
  135. return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
  136. }
  137. var userdoc interface{}
  138. if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
  139. return nil, fmt.Errorf("solc: error reading user doc: %v", err)
  140. }
  141. var devdoc interface{}
  142. if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
  143. return nil, fmt.Errorf("solc: error reading dev doc: %v", err)
  144. }
  145. contracts[name] = &Contract{
  146. Code: "0x" + info.Bin,
  147. Info: ContractInfo{
  148. Source: source,
  149. Language: "Solidity",
  150. LanguageVersion: shortVersion,
  151. CompilerVersion: shortVersion,
  152. CompilerOptions: strings.Join(solcParams, " "),
  153. AbiDefinition: abi,
  154. UserDoc: userdoc,
  155. DeveloperDoc: devdoc,
  156. },
  157. }
  158. }
  159. return contracts, nil
  160. }
  161. func slurpFiles(files []string) (string, error) {
  162. var concat bytes.Buffer
  163. for _, file := range files {
  164. content, err := ioutil.ReadFile(file)
  165. if err != nil {
  166. return "", err
  167. }
  168. concat.Write(content)
  169. }
  170. return concat.String(), nil
  171. }
  172. // SaveInfo serializes info to the given file and returns its Keccak256 hash.
  173. func SaveInfo(info *ContractInfo, filename string) (common.Hash, error) {
  174. infojson, err := json.Marshal(info)
  175. if err != nil {
  176. return common.Hash{}, err
  177. }
  178. contenthash := common.BytesToHash(crypto.Keccak256(infojson))
  179. return contenthash, ioutil.WriteFile(filename, infojson, 0600)
  180. }