github.com/FinTechToken/go-ethereum@v1.8.4-0.20190621030324-0b02bfba9171/common/compiler/solidity.go (about)

     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  
    17  // Package compiler wraps the Solidity compiler executable (solc).
    18  package compiler
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"io/ioutil"
    26  	"os/exec"
    27  	"regexp"
    28  	"strconv"
    29  	"strings"
    30  )
    31  
    32  var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`)
    33  
    34  // Contract contains information about a compiled contract, alongside its code and runtime code.
    35  type Contract struct {
    36  	Code        string       `json:"code"`
    37  	RuntimeCode string       `json:"runtime-code"`
    38  	Info        ContractInfo `json:"info"`
    39  }
    40  
    41  // ContractInfo contains information about a compiled contract, including access
    42  // to the ABI definition, source mapping, user and developer docs, and metadata.
    43  //
    44  // Depending on the source, language version, compiler version, and compiler
    45  // options will provide information about how the contract was compiled.
    46  type ContractInfo struct {
    47  	Source          string      `json:"source"`
    48  	Language        string      `json:"language"`
    49  	LanguageVersion string      `json:"languageVersion"`
    50  	CompilerVersion string      `json:"compilerVersion"`
    51  	CompilerOptions string      `json:"compilerOptions"`
    52  	SrcMap          string      `json:"srcMap"`
    53  	SrcMapRuntime   string      `json:"srcMapRuntime"`
    54  	AbiDefinition   interface{} `json:"abiDefinition"`
    55  	UserDoc         interface{} `json:"userDoc"`
    56  	DeveloperDoc    interface{} `json:"developerDoc"`
    57  	Metadata        string      `json:"metadata"`
    58  }
    59  
    60  // Solidity contains information about the solidity compiler.
    61  type Solidity struct {
    62  	Path, Version, FullVersion string
    63  	Major, Minor, Patch        int
    64  }
    65  
    66  // --combined-output format
    67  type solcOutput struct {
    68  	Contracts map[string]struct {
    69  		BinRuntime                                  string `json:"bin-runtime"`
    70  		SrcMapRuntime                               string `json:"srcmap-runtime"`
    71  		Bin, SrcMap, Abi, Devdoc, Userdoc, Metadata string
    72  	}
    73  	Version string
    74  }
    75  
    76  func (s *Solidity) makeArgs() []string {
    77  	p := []string{
    78  		"--combined-json", "bin,bin-runtime,srcmap,srcmap-runtime,abi,userdoc,devdoc",
    79  		"--optimize", // code optimizer switched on
    80  		//"--evm-version", "homestead",
    81  	}
    82  	if s.Major > 0 || s.Minor > 4 || s.Patch > 6 {
    83  		p[1] += ",metadata"
    84  	}
    85  	return p
    86  }
    87  
    88  // SolidityVersion runs solc and parses its version output.
    89  func SolidityVersion(solc string) (*Solidity, error) {
    90  	if solc == "" {
    91  		solc = "solc"
    92  	}
    93  	var out bytes.Buffer
    94  	cmd := exec.Command(solc, "--version")
    95  	cmd.Stdout = &out
    96  	err := cmd.Run()
    97  	if err != nil {
    98  		return nil, err
    99  	}
   100  	matches := versionRegexp.FindStringSubmatch(out.String())
   101  	if len(matches) != 4 {
   102  		return nil, fmt.Errorf("can't parse solc version %q", out.String())
   103  	}
   104  	s := &Solidity{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
   105  	if s.Major, err = strconv.Atoi(matches[1]); err != nil {
   106  		return nil, err
   107  	}
   108  	if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
   109  		return nil, err
   110  	}
   111  	if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
   112  		return nil, err
   113  	}
   114  	return s, nil
   115  }
   116  
   117  func New(solcPath string) (sol *Solidity, err error) {
   118  	// set default solc
   119  	if len(solcPath) == 0 {
   120  		solcPath = "solc"
   121  	}
   122  	solcPath, err = exec.LookPath(solcPath)
   123  	if err != nil {
   124  		return
   125  	}
   126  
   127  	cmd := exec.Command(solcPath, "--version")
   128  	var out bytes.Buffer
   129  	cmd.Stdout = &out
   130  	err = cmd.Run()
   131  	if err != nil {
   132  		return
   133  	}
   134  	fullVersion := out.String()
   135  	version := versionRegexp.FindString(fullVersion)
   136  
   137  	sol = &Solidity{
   138  		Path: solcPath,
   139  		Version: version,
   140  		FullVersion: fullVersion}
   141  	return
   142  }
   143  
   144  // CompileSolidityString builds and returns all the contracts contained within a source string.
   145  func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
   146  	if len(source) == 0 {
   147  		return nil, errors.New("solc: empty source string")
   148  	}
   149  	s, err := SolidityVersion(solc)
   150  	if err != nil {
   151  		return nil, err
   152  	}
   153  	args := append(s.makeArgs(), "--")
   154  	cmd := exec.Command(s.Path, append(args, "-")...)
   155  	cmd.Stdin = strings.NewReader(source)
   156  	return s.run(cmd, source)
   157  }
   158  
   159  // CompileSolidity compiles all given Solidity source files.
   160  func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
   161  	if len(sourcefiles) == 0 {
   162  		return nil, errors.New("solc: no source files")
   163  	}
   164  	source, err := slurpFiles(sourcefiles)
   165  	if err != nil {
   166  		return nil, err
   167  	}
   168  	s, err := SolidityVersion(solc)
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  	args := append(s.makeArgs(), "--")
   173  	cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
   174  	return s.run(cmd, source)
   175  }
   176  
   177  func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
   178  	var stderr, stdout bytes.Buffer
   179  	cmd.Stderr = &stderr
   180  	cmd.Stdout = &stdout
   181  	if err := cmd.Run(); err != nil {
   182  		return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
   183  	}
   184  
   185  	return ParseCombinedJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
   186  }
   187  
   188  // ParseCombinedJSON takes the direct output of a solc --combined-output run and
   189  // parses it into a map of string contract name to Contract structs. The
   190  // provided source, language and compiler version, and compiler options are all
   191  // passed through into the Contract structs.
   192  //
   193  // The solc output is expected to contain ABI, source mapping, user docs, and dev docs.
   194  //
   195  // Returns an error if the JSON is malformed or missing data, or if the JSON
   196  // embedded within the JSON is malformed.
   197  func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
   198  	var output solcOutput
   199  	if err := json.Unmarshal(combinedJSON, &output); err != nil {
   200  		return nil, err
   201  	}
   202  
   203  	// Compilation succeeded, assemble and return the contracts.
   204  	contracts := make(map[string]*Contract)
   205  	for name, info := range output.Contracts {
   206  		// Parse the individual compilation results.
   207  		var abi interface{}
   208  		if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
   209  			return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
   210  		}
   211  		var userdoc interface{}
   212  		if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
   213  			return nil, fmt.Errorf("solc: error reading user doc: %v", err)
   214  		}
   215  		var devdoc interface{}
   216  		if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
   217  			return nil, fmt.Errorf("solc: error reading dev doc: %v", err)
   218  		}
   219  		contracts[name] = &Contract{
   220  			Code:        "0x" + info.Bin,
   221  			RuntimeCode: "0x" + info.BinRuntime,
   222  			Info: ContractInfo{
   223  				Source:          source,
   224  				Language:        "Solidity",
   225  				LanguageVersion: languageVersion,
   226  				CompilerVersion: compilerVersion,
   227  				CompilerOptions: compilerOptions,
   228  				SrcMap:          info.SrcMap,
   229  				SrcMapRuntime:   info.SrcMapRuntime,
   230  				AbiDefinition:   abi,
   231  				UserDoc:         userdoc,
   232  				DeveloperDoc:    devdoc,
   233  				Metadata:        info.Metadata,
   234  			},
   235  		}
   236  	}
   237  	return contracts, nil
   238  }
   239  
   240  func slurpFiles(files []string) (string, error) {
   241  	var concat bytes.Buffer
   242  	for _, file := range files {
   243  		content, err := ioutil.ReadFile(file)
   244  		if err != nil {
   245  			return "", err
   246  		}
   247  		concat.Write(content)
   248  	}
   249  	return concat.String(), nil
   250  }
   251  
   252  //Compile builds and returns all the contracts contnained within a source string.
   253  func (sol *Solidity) Compile(source string) (map[string]*Contract, error) {
   254  	return CompileSolidityString("solc", source)
   255  }