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