github.com/devkononov/go-func@v0.0.0-20190722084534-f14392d369a7/common/compiler/solidity.go (about)

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