github.com/rayrapetyan/go-ethereum@v1.8.21/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  	}
    81  	if s.Major > 0 || s.Minor > 4 || s.Patch > 6 {
    82  		p[1] += ",metadata"
    83  	}
    84  	return p
    85  }
    86  
    87  // SolidityVersion runs solc and parses its version output.
    88  func SolidityVersion(solc string) (*Solidity, error) {
    89  	if solc == "" {
    90  		solc = "solc"
    91  	}
    92  	var out bytes.Buffer
    93  	cmd := exec.Command(solc, "--version")
    94  	cmd.Stdout = &out
    95  	err := cmd.Run()
    96  	if err != nil {
    97  		return nil, err
    98  	}
    99  	matches := versionRegexp.FindStringSubmatch(out.String())
   100  	if len(matches) != 4 {
   101  		return nil, fmt.Errorf("can't parse solc version %q", out.String())
   102  	}
   103  	s := &Solidity{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
   104  	if s.Major, err = strconv.Atoi(matches[1]); err != nil {
   105  		return nil, err
   106  	}
   107  	if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
   108  		return nil, err
   109  	}
   110  	if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
   111  		return nil, err
   112  	}
   113  	return s, nil
   114  }
   115  
   116  // CompileSolidityString builds and returns all the contracts contained within a source string.
   117  func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
   118  	if len(source) == 0 {
   119  		return nil, errors.New("solc: empty source string")
   120  	}
   121  	s, err := SolidityVersion(solc)
   122  	if err != nil {
   123  		return nil, err
   124  	}
   125  	args := append(s.makeArgs(), "--")
   126  	cmd := exec.Command(s.Path, append(args, "-")...)
   127  	cmd.Stdin = strings.NewReader(source)
   128  	return s.run(cmd, source)
   129  }
   130  
   131  // CompileSolidity compiles all given Solidity source files.
   132  func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
   133  	if len(sourcefiles) == 0 {
   134  		return nil, errors.New("solc: no source files")
   135  	}
   136  	source, err := slurpFiles(sourcefiles)
   137  	if err != nil {
   138  		return nil, err
   139  	}
   140  	s, err := SolidityVersion(solc)
   141  	if err != nil {
   142  		return nil, err
   143  	}
   144  	args := append(s.makeArgs(), "--")
   145  	cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
   146  	return s.run(cmd, source)
   147  }
   148  
   149  func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
   150  	var stderr, stdout bytes.Buffer
   151  	cmd.Stderr = &stderr
   152  	cmd.Stdout = &stdout
   153  	if err := cmd.Run(); err != nil {
   154  		return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
   155  	}
   156  
   157  	return ParseCombinedJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
   158  }
   159  
   160  // ParseCombinedJSON takes the direct output of a solc --combined-output run and
   161  // parses it into a map of string contract name to Contract structs. The
   162  // provided source, language and compiler version, and compiler options are all
   163  // passed through into the Contract structs.
   164  //
   165  // The solc output is expected to contain ABI, source mapping, user docs, and dev docs.
   166  //
   167  // Returns an error if the JSON is malformed or missing data, or if the JSON
   168  // embedded within the JSON is malformed.
   169  func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
   170  	var output solcOutput
   171  	if err := json.Unmarshal(combinedJSON, &output); err != nil {
   172  		return nil, err
   173  	}
   174  
   175  	// Compilation succeeded, assemble and return the contracts.
   176  	contracts := make(map[string]*Contract)
   177  	for name, info := range output.Contracts {
   178  		// Parse the individual compilation results.
   179  		var abi interface{}
   180  		if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
   181  			return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
   182  		}
   183  		var userdoc interface{}
   184  		if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
   185  			return nil, fmt.Errorf("solc: error reading user doc: %v", err)
   186  		}
   187  		var devdoc interface{}
   188  		if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
   189  			return nil, fmt.Errorf("solc: error reading dev doc: %v", err)
   190  		}
   191  		contracts[name] = &Contract{
   192  			Code:        "0x" + info.Bin,
   193  			RuntimeCode: "0x" + info.BinRuntime,
   194  			Info: ContractInfo{
   195  				Source:          source,
   196  				Language:        "Solidity",
   197  				LanguageVersion: languageVersion,
   198  				CompilerVersion: compilerVersion,
   199  				CompilerOptions: compilerOptions,
   200  				SrcMap:          info.SrcMap,
   201  				SrcMapRuntime:   info.SrcMapRuntime,
   202  				AbiDefinition:   abi,
   203  				UserDoc:         userdoc,
   204  				DeveloperDoc:    devdoc,
   205  				Metadata:        info.Metadata,
   206  			},
   207  		}
   208  	}
   209  	return contracts, nil
   210  }
   211  
   212  func slurpFiles(files []string) (string, error) {
   213  	var concat bytes.Buffer
   214  	for _, file := range files {
   215  		content, err := ioutil.ReadFile(file)
   216  		if err != nil {
   217  			return "", err
   218  		}
   219  		concat.Write(content)
   220  	}
   221  	return concat.String(), nil
   222  }