solidity.go 5.4 KB

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