github.com/mrwater98/go-ethereum@v1.9.7/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 and Vyper compiler executables (solc; vyper).
    18  package compiler
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"os/exec"
    26  	"strconv"
    27  	"strings"
    28  )
    29  
    30  // Solidity contains information about the solidity compiler.
    31  type Solidity struct {
    32  	Path, Version, FullVersion string
    33  	Major, Minor, Patch        int
    34  }
    35  
    36  // --combined-output format
    37  type solcOutput struct {
    38  	Contracts map[string]struct {
    39  		BinRuntime                                  string `json:"bin-runtime"`
    40  		SrcMapRuntime                               string `json:"srcmap-runtime"`
    41  		Bin, SrcMap, Abi, Devdoc, Userdoc, Metadata string
    42  		Hashes                                      map[string]string
    43  	}
    44  	Version string
    45  }
    46  
    47  func (s *Solidity) makeArgs() []string {
    48  	p := []string{
    49  		"--combined-json", "bin,bin-runtime,srcmap,srcmap-runtime,abi,userdoc,devdoc",
    50  		"--optimize",                  // code optimizer switched on
    51  		"--allow-paths", "., ./, ../", // default to support relative paths
    52  	}
    53  	if s.Major > 0 || s.Minor > 4 || s.Patch > 6 {
    54  		p[1] += ",metadata,hashes"
    55  	}
    56  	return p
    57  }
    58  
    59  // SolidityVersion runs solc and parses its version output.
    60  func SolidityVersion(solc string) (*Solidity, error) {
    61  	if solc == "" {
    62  		solc = "solc"
    63  	}
    64  	var out bytes.Buffer
    65  	cmd := exec.Command(solc, "--version")
    66  	cmd.Stdout = &out
    67  	err := cmd.Run()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	matches := versionRegexp.FindStringSubmatch(out.String())
    72  	if len(matches) != 4 {
    73  		return nil, fmt.Errorf("can't parse solc version %q", out.String())
    74  	}
    75  	s := &Solidity{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
    76  	if s.Major, err = strconv.Atoi(matches[1]); err != nil {
    77  		return nil, err
    78  	}
    79  	if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
    80  		return nil, err
    81  	}
    82  	if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
    83  		return nil, err
    84  	}
    85  	return s, nil
    86  }
    87  
    88  // CompileSolidityString builds and returns all the contracts contained within a source string.
    89  func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
    90  	if len(source) == 0 {
    91  		return nil, errors.New("solc: empty source string")
    92  	}
    93  	s, err := SolidityVersion(solc)
    94  	if err != nil {
    95  		return nil, err
    96  	}
    97  	args := append(s.makeArgs(), "--")
    98  	cmd := exec.Command(s.Path, append(args, "-")...)
    99  	cmd.Stdin = strings.NewReader(source)
   100  	return s.run(cmd, source)
   101  }
   102  
   103  // CompileSolidity compiles all given Solidity source files.
   104  func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
   105  	if len(sourcefiles) == 0 {
   106  		return nil, errors.New("solc: no source files")
   107  	}
   108  	source, err := slurpFiles(sourcefiles)
   109  	if err != nil {
   110  		return nil, err
   111  	}
   112  	s, err := SolidityVersion(solc)
   113  	if err != nil {
   114  		return nil, err
   115  	}
   116  	args := append(s.makeArgs(), "--")
   117  	cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
   118  	return s.run(cmd, source)
   119  }
   120  
   121  func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
   122  	var stderr, stdout bytes.Buffer
   123  	cmd.Stderr = &stderr
   124  	cmd.Stdout = &stdout
   125  	if err := cmd.Run(); err != nil {
   126  		return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
   127  	}
   128  
   129  	return ParseCombinedJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
   130  }
   131  
   132  // ParseCombinedJSON takes the direct output of a solc --combined-output run and
   133  // parses it into a map of string contract name to Contract structs. The
   134  // provided source, language and compiler version, and compiler options are all
   135  // passed through into the Contract structs.
   136  //
   137  // The solc output is expected to contain ABI, source mapping, user docs, and dev docs.
   138  //
   139  // Returns an error if the JSON is malformed or missing data, or if the JSON
   140  // embedded within the JSON is malformed.
   141  func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
   142  	var output solcOutput
   143  	if err := json.Unmarshal(combinedJSON, &output); err != nil {
   144  		return nil, err
   145  	}
   146  	// Compilation succeeded, assemble and return the contracts.
   147  	contracts := make(map[string]*Contract)
   148  	for name, info := range output.Contracts {
   149  		// Parse the individual compilation results.
   150  		var abi interface{}
   151  		if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
   152  			return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
   153  		}
   154  		var userdoc, devdoc interface{}
   155  		json.Unmarshal([]byte(info.Userdoc), &userdoc)
   156  		json.Unmarshal([]byte(info.Devdoc), &devdoc)
   157  
   158  		contracts[name] = &Contract{
   159  			Code:        "0x" + info.Bin,
   160  			RuntimeCode: "0x" + info.BinRuntime,
   161  			Hashes:      info.Hashes,
   162  			Info: ContractInfo{
   163  				Source:          source,
   164  				Language:        "Solidity",
   165  				LanguageVersion: languageVersion,
   166  				CompilerVersion: compilerVersion,
   167  				CompilerOptions: compilerOptions,
   168  				SrcMap:          info.SrcMap,
   169  				SrcMapRuntime:   info.SrcMapRuntime,
   170  				AbiDefinition:   abi,
   171  				UserDoc:         userdoc,
   172  				DeveloperDoc:    devdoc,
   173  				Metadata:        info.Metadata,
   174  			},
   175  		}
   176  	}
   177  	return contracts, nil
   178  }