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