common/compiler, cmd/abigen: fixed linter errors, ran gofmt

This commit is contained in:
Kushagra Sharma 2019-03-06 12:55:01 +01:00
parent 4fc7a53e85
commit a992762ebd
4 changed files with 289 additions and 285 deletions

View file

@ -17,124 +17,124 @@
package main package main
import ( import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"strings" "strings"
"github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common/compiler" "github.com/ethereum/go-ethereum/common/compiler"
) )
var ( var (
abiFlag = flag.String("abi", "", "Path to the Ethereum contract ABI json to bind, - for STDIN") abiFlag = flag.String("abi", "", "Path to the Ethereum contract ABI json to bind, - for STDIN")
binFlag = flag.String("bin", "", "Path to the Ethereum contract bytecode (generate deploy method)") binFlag = flag.String("bin", "", "Path to the Ethereum contract bytecode (generate deploy method)")
typFlag = flag.String("type", "", "Struct name for the binding (default = package name)") typFlag = flag.String("type", "", "Struct name for the binding (default = package name)")
solFlag = flag.String("sol", "", "Path to the Ethereum contract Solidity source to build and bind") solFlag = flag.String("sol", "", "Path to the Ethereum contract Solidity source to build and bind")
solcFlag = flag.String("solc", "solc", "Solidity compiler to use if source builds are requested") solcFlag = flag.String("solc", "solc", "Solidity compiler to use if source builds are requested")
excFlag = flag.String("exc", "", "Comma separated types to exclude from binding") excFlag = flag.String("exc", "", "Comma separated types to exclude from binding")
vyFlag = flag.String("vy", "", "Path to the Ethereum contract Vyper source to build and bind") vyFlag = flag.String("vy", "", "Path to the Ethereum contract Vyper source to build and bind")
vyperFlag = flag.String("vyper", "vyper", "Vyper compiler to use if source builds are requested") vyperFlag = flag.String("vyper", "vyper", "Vyper compiler to use if source builds are requested")
pkgFlag = flag.String("pkg", "", "Package name to generate the binding into") pkgFlag = flag.String("pkg", "", "Package name to generate the binding into")
outFlag = flag.String("out", "", "Output file for the generated binding (default = stdout)") outFlag = flag.String("out", "", "Output file for the generated binding (default = stdout)")
langFlag = flag.String("lang", "go", "Destination language for the bindings (go, java, objc)") langFlag = flag.String("lang", "go", "Destination language for the bindings (go, java, objc)")
) )
func main() { func main() {
// Parse and ensure all needed inputs are specified // Parse and ensure all needed inputs are specified
flag.Parse() flag.Parse()
if *abiFlag == "" && *solFlag == "" && *vyFlag == "" { if *abiFlag == "" && *solFlag == "" && *vyFlag == "" {
fmt.Printf("No contract ABI (--abi), Solidity source (--sol), or Vyper source (--vy) specified\n") fmt.Printf("No contract ABI (--abi), Solidity source (--sol), or Vyper source (--vy) specified\n")
os.Exit(-1) os.Exit(-1)
} else if (*abiFlag != "" || *binFlag != "" || *typFlag != "") && (*solFlag != "" || *vyFlag != "") { } else if (*abiFlag != "" || *binFlag != "" || *typFlag != "") && (*solFlag != "" || *vyFlag != "") {
fmt.Printf("Contract ABI (--abi), bytecode (--bin) and type (--type) flags are mutually exclusive with the Solidity (--sol) and Vyper (--vy) flags\n") fmt.Printf("Contract ABI (--abi), bytecode (--bin) and type (--type) flags are mutually exclusive with the Solidity (--sol) and Vyper (--vy) flags\n")
os.Exit(-1) os.Exit(-1)
} else if *solFlag != "" && *vyFlag != "" { } else if *solFlag != "" && *vyFlag != "" {
fmt.Printf("Solidity (--sol) and Vyper (--vy) flags are mutually exclusive\n") fmt.Printf("Solidity (--sol) and Vyper (--vy) flags are mutually exclusive\n")
os.Exit(-1) os.Exit(-1)
} }
if *pkgFlag == "" { if *pkgFlag == "" {
fmt.Printf("No destination package specified (--pkg)\n") fmt.Printf("No destination package specified (--pkg)\n")
os.Exit(-1) os.Exit(-1)
} }
var lang bind.Lang var lang bind.Lang
switch *langFlag { switch *langFlag {
case "go": case "go":
lang = bind.LangGo lang = bind.LangGo
case "java": case "java":
lang = bind.LangJava lang = bind.LangJava
case "objc": case "objc":
lang = bind.LangObjC lang = bind.LangObjC
default: default:
fmt.Printf("Unsupported destination language \"%s\" (--lang)\n", *langFlag) fmt.Printf("Unsupported destination language \"%s\" (--lang)\n", *langFlag)
os.Exit(-1) os.Exit(-1)
} }
// If the entire solidity code was specified, build and bind based on that // If the entire solidity code was specified, build and bind based on that
var ( var (
abis []string abis []string
bins []string bins []string
types []string types []string
) )
if *solFlag != "" || *vyFlag != "" || (*abiFlag == "-" && *pkgFlag == "") { if *solFlag != "" || *vyFlag != "" || (*abiFlag == "-" && *pkgFlag == "") {
// Generate the list of types to exclude from binding // Generate the list of types to exclude from binding
exclude := make(map[string]bool) exclude := make(map[string]bool)
for _, kind := range strings.Split(*excFlag, ",") { for _, kind := range strings.Split(*excFlag, ",") {
exclude[strings.ToLower(kind)] = true exclude[strings.ToLower(kind)] = true
} }
var contracts map[string]*compiler.Contract var contracts map[string]*compiler.Contract
var err error var err error
if *solFlag != "" { if *solFlag != "" {
contracts, err = compiler.CompileSolidity(*solcFlag, *solFlag) contracts, err = compiler.CompileSolidity(*solcFlag, *solFlag)
if err != nil { if err != nil {
fmt.Printf("Failed to build Solidity contract: %v\n", err) fmt.Printf("Failed to build Solidity contract: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }
} else if *vyFlag != "" { } else if *vyFlag != "" {
contracts, err = compiler.CompileVyper(*vyperFlag, *vyFlag) contracts, err = compiler.CompileVyper(*vyperFlag, *vyFlag)
if err != nil { if err != nil {
fmt.Printf("Failed to build Vyper contract: %v\n", err) fmt.Printf("Failed to build Vyper contract: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }
} else { } else {
contracts, err = contractsFromStdin() contracts, err = contractsFromStdin()
if err != nil { if err != nil {
fmt.Printf("Failed to read input ABIs from STDIN: %v\n", err) fmt.Printf("Failed to read input ABIs from STDIN: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }
} }
// Gather all non-excluded contract for binding // Gather all non-excluded contract for binding
for name, contract := range contracts { for name, contract := range contracts {
if exclude[strings.ToLower(name)] { if exclude[strings.ToLower(name)] {
continue continue
} }
abi, _ := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse abi, _ := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
abis = append(abis, string(abi)) abis = append(abis, string(abi))
bins = append(bins, contract.Code) bins = append(bins, contract.Code)
nameParts := strings.Split(name, ":") nameParts := strings.Split(name, ":")
types = append(types, nameParts[len(nameParts)-1]) types = append(types, nameParts[len(nameParts)-1])
} }
} else { } else {
// Otherwise load up the ABI, optional bytecode and type name from the parameters // Otherwise load up the ABI, optional bytecode and type name from the parameters
var abi []byte var abi []byte
var err error var err error
if *abiFlag == "-" { if *abiFlag == "-" {
abi, err = ioutil.ReadAll(os.Stdin) abi, err = ioutil.ReadAll(os.Stdin)
} else { } else {
abi, err = ioutil.ReadFile(*abiFlag) abi, err = ioutil.ReadFile(*abiFlag)
} }
if err != nil { if err != nil {
fmt.Printf("Failed to read input ABI: %v\n", err) fmt.Printf("Failed to read input ABI: %v\n", err)
os.Exit(-1) os.Exit(-1)
} }
abis = append(abis, string(abi)) abis = append(abis, string(abi))
var bin []byte var bin []byte
if *binFlag != "" { if *binFlag != "" {
@ -145,33 +145,34 @@ func main() {
} }
bins = append(bins, string(bin)) bins = append(bins, string(bin))
kind := *typFlag kind := *typFlag
if kind == "" { if kind == "" {
kind = *pkgFlag kind = *pkgFlag
} }
types = append(types, kind) types = append(types, kind)
} }
// Generate the contract binding // Generate the contract binding
code, err := bind.Bind(types, abis, bins, *pkgFlag, lang) fmt.Printf("%+v", abis)
if err != nil { code, err := bind.Bind(types, abis, bins, *pkgFlag, lang)
fmt.Printf("Failed to generate ABI binding: %v\n", err) if err != nil {
os.Exit(-1) fmt.Printf("Failed to generate ABI binding: %v\n", err)
} os.Exit(-1)
// Either flush it out to a file or display on the standard output }
if *outFlag == "" { // Either flush it out to a file or display on the standard output
fmt.Printf("%s\n", code) if *outFlag == "" {
return fmt.Printf("%s\n", code)
} return
if err := ioutil.WriteFile(*outFlag, []byte(code), 0600); err != nil { }
fmt.Printf("Failed to write ABI binding: %v\n", err) if err := ioutil.WriteFile(*outFlag, []byte(code), 0600); err != nil {
os.Exit(-1) fmt.Printf("Failed to write ABI binding: %v\n", err)
} os.Exit(-1)
}
} }
func contractsFromStdin() (map[string]*compiler.Contract, error) { func contractsFromStdin() (map[string]*compiler.Contract, error) {
bytes, err := ioutil.ReadAll(os.Stdin) bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return compiler.ParseCombinedJSON(bytes, "", "", "", "") return compiler.ParseCombinedJSON(bytes, "", "", "", "")
} }

View file

@ -18,18 +18,18 @@
package compiler package compiler
import ( import (
"bytes" "bytes"
"io/ioutil" "io/ioutil"
"regexp" "regexp"
) )
var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`) var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`)
// Contract contains information about a compiled contract, alongside its code and runtime code. // Contract contains information about a compiled contract, alongside its code and runtime code.
type Contract struct { type Contract struct {
Code string `json:"code"` Code string `json:"code"`
RuntimeCode string `json:"runtime-code"` RuntimeCode string `json:"runtime-code"`
Info ContractInfo `json:"info"` Info ContractInfo `json:"info"`
} }
// ContractInfo contains information about a compiled contract, including access // ContractInfo contains information about a compiled contract, including access
@ -38,27 +38,27 @@ type Contract struct {
// Depending on the source, language version, compiler version, and compiler // Depending on the source, language version, compiler version, and compiler
// options will provide information about how the contract was compiled. // options will provide information about how the contract was compiled.
type ContractInfo struct { type ContractInfo struct {
Source string `json:"source"` Source string `json:"source"`
Language string `json:"language"` Language string `json:"language"`
LanguageVersion string `json:"languageVersion"` LanguageVersion string `json:"languageVersion"`
CompilerVersion string `json:"compilerVersion"` CompilerVersion string `json:"compilerVersion"`
CompilerOptions string `json:"compilerOptions"` CompilerOptions string `json:"compilerOptions"`
SrcMap interface{} `json:"srcMap"` SrcMap interface{} `json:"srcMap"`
SrcMapRuntime string `json:"srcMapRuntime"` SrcMapRuntime string `json:"srcMapRuntime"`
AbiDefinition interface{} `json:"abiDefinition"` AbiDefinition interface{} `json:"abiDefinition"`
UserDoc interface{} `json:"userDoc"` UserDoc interface{} `json:"userDoc"`
DeveloperDoc interface{} `json:"developerDoc"` DeveloperDoc interface{} `json:"developerDoc"`
Metadata string `json:"metadata"` Metadata string `json:"metadata"`
} }
func slurpFiles(files []string) (string, error) { func slurpFiles(files []string) (string, error) {
var concat bytes.Buffer var concat bytes.Buffer
for _, file := range files { for _, file := range files {
content, err := ioutil.ReadFile(file) content, err := ioutil.ReadFile(file)
if err != nil { if err != nil {
return "", err return "", err
} }
concat.Write(content) concat.Write(content)
} }
return concat.String(), nil return concat.String(), nil
} }

View file

@ -18,84 +18,84 @@
package compiler package compiler
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
) )
// Vyper contains information about the vyper compiler. // Vyper contains information about the vyper compiler.
type Vyper struct { type Vyper struct {
Path, Version, FullVersion string Path, Version, FullVersion string
Major, Minor, Patch int Major, Minor, Patch int
} }
func (s *Vyper) makeArgs() []string { func (s *Vyper) makeArgs() []string {
p := []string{ p := []string{
"-f", "combined_json", "-f", "combined_json",
} }
return p return p
} }
// VyperVersion runs vyper and parses its version output. // VyperVersion runs vyper and parses its version output.
func VyperVersion(vyper string) (*Vyper, error) { func VyperVersion(vyper string) (*Vyper, error) {
if vyper == "" { if vyper == "" {
vyper = "vyper" vyper = "vyper"
} }
var out bytes.Buffer var out bytes.Buffer
cmd := exec.Command(vyper, "--version") cmd := exec.Command(vyper, "--version")
cmd.Stdout = &out cmd.Stdout = &out
err := cmd.Run() err := cmd.Run()
if err != nil { if err != nil {
return nil, err return nil, err
} }
matches := versionRegexp.FindStringSubmatch(out.String()) matches := versionRegexp.FindStringSubmatch(out.String())
if len(matches) != 4 { if len(matches) != 4 {
return nil, fmt.Errorf("can't parse vyper version %q", out.String()) return nil, fmt.Errorf("can't parse vyper version %q", out.String())
} }
s := &Vyper{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]} s := &Vyper{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
if s.Major, err = strconv.Atoi(matches[1]); err != nil { if s.Major, err = strconv.Atoi(matches[1]); err != nil {
return nil, err return nil, err
} }
if s.Minor, err = strconv.Atoi(matches[2]); err != nil { if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
return nil, err return nil, err
} }
if s.Patch, err = strconv.Atoi(matches[3]); err != nil { if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
return nil, err return nil, err
} }
return s, nil return s, nil
} }
// CompileVyper compiles all given Vyper source files. // CompileVyper compiles all given Vyper source files.
func CompileVyper(vyper string, sourcefiles ...string) (map[string]*Contract, error) { func CompileVyper(vyper string, sourcefiles ...string) (map[string]*Contract, error) {
if len(sourcefiles) == 0 { if len(sourcefiles) == 0 {
return nil, errors.New("vyper: no source files") return nil, errors.New("vyper: no source files")
} }
source, err := slurpFiles(sourcefiles) source, err := slurpFiles(sourcefiles)
if err != nil { if err != nil {
return nil, err return nil, err
} }
s, err := VyperVersion(vyper) s, err := VyperVersion(vyper)
if err != nil { if err != nil {
return nil, err return nil, err
} }
args := s.makeArgs() args := s.makeArgs()
cmd := exec.Command(s.Path, append(args, sourcefiles...)...) cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
return s.run(cmd, source) return s.run(cmd, source)
} }
func (s *Vyper) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) { func (s *Vyper) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
var stderr, stdout bytes.Buffer var stderr, stdout bytes.Buffer
cmd.Stderr = &stderr cmd.Stderr = &stderr
cmd.Stdout = &stdout cmd.Stdout = &stdout
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("vyper: %v\n%s", err, stderr.Bytes()) return nil, fmt.Errorf("vyper: %v\n%s", err, stderr.Bytes())
} }
return ParseVyperJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " ")) return ParseVyperJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
} }
// ParseVyperJSON takes the direct output of a vyper --f combined_json run and // ParseVyperJSON takes the direct output of a vyper --f combined_json run and
@ -108,37 +108,37 @@ func (s *Vyper) run(cmd *exec.Cmd, source string) (map[string]*Contract, error)
// Returns an error if the JSON is malformed or missing data, or if the JSON // Returns an error if the JSON is malformed or missing data, or if the JSON
// embedded within the JSON is malformed. // embedded within the JSON is malformed.
func ParseVyperJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) { func ParseVyperJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
var output map[string]interface{} var output map[string]interface{}
if err := json.Unmarshal(combinedJSON, &output); err != nil { if err := json.Unmarshal(combinedJSON, &output); err != nil {
return nil, err return nil, err
} }
// Compilation succeeded, assemble and return the contracts. // Compilation succeeded, assemble and return the contracts.
contracts := make(map[string]*Contract) contracts := make(map[string]*Contract)
for name, info := range output { for name, info := range output {
// Parse the individual compilation results. // Parse the individual compilation results.
if name == "version" { if name == "version" {
continue continue
} }
c := info.(map[string]interface{}) c := info.(map[string]interface{})
contracts[name] = &Contract{ contracts[name] = &Contract{
Code: c["bytecode"].(string), Code: c["bytecode"].(string),
RuntimeCode: c["bytecode_runtime"].(string), RuntimeCode: c["bytecode_runtime"].(string),
Info: ContractInfo{ Info: ContractInfo{
Source: source, Source: source,
Language: "Vyper", Language: "Vyper",
LanguageVersion: languageVersion, LanguageVersion: languageVersion,
CompilerVersion: compilerVersion, CompilerVersion: compilerVersion,
CompilerOptions: compilerOptions, CompilerOptions: compilerOptions,
SrcMap: c["source_map"], SrcMap: c["source_map"],
SrcMapRuntime: "", SrcMapRuntime: "",
AbiDefinition: c["abi"], AbiDefinition: c["abi"],
UserDoc: "", UserDoc: "",
DeveloperDoc: "", DeveloperDoc: "",
Metadata: "", Metadata: "",
}, },
} }
} }
return contracts, nil return contracts, nil
} }

View file

@ -17,52 +17,55 @@
package compiler package compiler
import ( import (
"os/exec" "os/exec"
"testing" "testing"
) )
func skipWithoutVyper(t *testing.T) { func skipWithoutVyper(t *testing.T) {
if _, err := exec.LookPath("vyper"); err != nil { if _, err := exec.LookPath("vyper"); err != nil {
t.Skip(err) t.Skip(err)
} }
} }
func TestVyperCompiler(t *testing.T) { func TestVyperCompiler(t *testing.T) {
skipWithoutVyper(t) skipWithoutVyper(t)
testSource := []string{"test.v.py"} testSource := []string{"test.v.py"}
source, err := slurpFiles(testSource) source, err := slurpFiles(testSource)
contracts, err := CompileVyper("", testSource...) if err != nil {
if err != nil { t.Error("couldn't read test files")
t.Fatalf("error compiling test.v.py. result %v: %v", contracts, err) }
} contracts, err := CompileVyper("", testSource...)
if len(contracts) != 1 { if err != nil {
t.Errorf("one contract expected, got %d", len(contracts)) t.Fatalf("error compiling test.v.py. result %v: %v", contracts, err)
} }
c, ok := contracts["test.v.py"] if len(contracts) != 1 {
if !ok { t.Errorf("one contract expected, got %d", len(contracts))
c, ok = contracts["<stdin>:test"] }
if !ok { c, ok := contracts["test.v.py"]
t.Fatal("info for contract 'test.v.py' not present in result") if !ok {
} c, ok = contracts["<stdin>:test"]
} if !ok {
if c.Code == "" { t.Fatal("info for contract 'test.v.py' not present in result")
t.Error("empty code") }
} }
if c.Info.Source != source { if c.Code == "" {
t.Error("wrong source") t.Error("empty code")
} }
if c.Info.CompilerVersion == "" { if c.Info.Source != source {
t.Error("empty version") t.Error("wrong source")
} }
if c.Info.CompilerVersion == "" {
t.Error("empty version")
}
} }
func TestVyperCompileError(t *testing.T) { func TestVyperCompileError(t *testing.T) {
skipWithoutVyper(t) skipWithoutVyper(t)
contracts, err := CompileVyper("", "test_bad.v.py") contracts, err := CompileVyper("", "test_bad.v.py")
if err == nil { if err == nil {
t.Errorf("error expected compiling test_bad.v.py. got none. result %v", contracts) t.Errorf("error expected compiling test_bad.v.py. got none. result %v", contracts)
} }
t.Logf("error: %v", err) t.Logf("error: %v", err)
} }