github.com/flashbots/go-ethereum@v1.9.7/build/ci.go (about)

     1  // Copyright 2016 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  // +build none
    18  
    19  /*
    20  The ci command is called from Continuous Integration scripts.
    21  
    22  Usage: go run build/ci.go <command> <command flags/arguments>
    23  
    24  Available commands are:
    25  
    26     install    [ -arch architecture ] [ -cc compiler ] [ packages... ]                          -- builds packages and executables
    27     test       [ -coverage ] [ packages... ]                                                    -- runs the tests
    28     lint                                                                                        -- runs certain pre-selected linters
    29     archive    [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artifacts
    30     importkeys                                                                                  -- imports signing keys from env
    31     debsrc     [ -signer key-id ] [ -upload dest ]                                              -- creates a debian source package
    32     nsis                                                                                        -- creates a Windows NSIS installer
    33     aar        [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an Android archive
    34     xcode      [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an iOS XCode framework
    35     xgo        [ -alltools ] [ options ]                                                        -- cross builds according to options
    36     purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
    37  
    38  For all commands, -n prevents execution of external programs (dry run mode).
    39  
    40  */
    41  package main
    42  
    43  import (
    44  	"bufio"
    45  	"bytes"
    46  	"encoding/base64"
    47  	"flag"
    48  	"fmt"
    49  	"go/parser"
    50  	"go/token"
    51  	"io/ioutil"
    52  	"log"
    53  	"os"
    54  	"os/exec"
    55  	"path/filepath"
    56  	"regexp"
    57  	"runtime"
    58  	"strings"
    59  	"time"
    60  
    61  	"github.com/ethereum/go-ethereum/common/hexutil"
    62  	"github.com/ethereum/go-ethereum/internal/build"
    63  	"github.com/ethereum/go-ethereum/params"
    64  )
    65  
    66  var (
    67  	// Files that end up in the geth*.zip archive.
    68  	gethArchiveFiles = []string{
    69  		"COPYING",
    70  		executablePath("geth"),
    71  	}
    72  
    73  	// Files that end up in the geth-alltools*.zip archive.
    74  	allToolsArchiveFiles = []string{
    75  		"COPYING",
    76  		executablePath("abigen"),
    77  		executablePath("bootnode"),
    78  		executablePath("evm"),
    79  		executablePath("geth"),
    80  		executablePath("puppeth"),
    81  		executablePath("rlpdump"),
    82  		executablePath("wnode"),
    83  		executablePath("clef"),
    84  	}
    85  
    86  	// A debian package is created for all executables listed here.
    87  	debExecutables = []debExecutable{
    88  		{
    89  			BinaryName:  "abigen",
    90  			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
    91  		},
    92  		{
    93  			BinaryName:  "bootnode",
    94  			Description: "Ethereum bootnode.",
    95  		},
    96  		{
    97  			BinaryName:  "evm",
    98  			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
    99  		},
   100  		{
   101  			BinaryName:  "geth",
   102  			Description: "Ethereum CLI client.",
   103  		},
   104  		{
   105  			BinaryName:  "puppeth",
   106  			Description: "Ethereum private network manager.",
   107  		},
   108  		{
   109  			BinaryName:  "rlpdump",
   110  			Description: "Developer utility tool that prints RLP structures.",
   111  		},
   112  		{
   113  			BinaryName:  "wnode",
   114  			Description: "Ethereum Whisper diagnostic tool",
   115  		},
   116  		{
   117  			BinaryName:  "clef",
   118  			Description: "Ethereum account management tool.",
   119  		},
   120  	}
   121  
   122  	// A debian package is created for all executables listed here.
   123  
   124  	debEthereum = debPackage{
   125  		Name:        "ethereum",
   126  		Version:     params.Version,
   127  		Executables: debExecutables,
   128  	}
   129  
   130  	// Debian meta packages to build and push to Ubuntu PPA
   131  	debPackages = []debPackage{
   132  		debEthereum,
   133  	}
   134  
   135  	// Distros for which packages are created.
   136  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   137  	// Note: wily is unsupported because it was officially deprecated on Launchpad.
   138  	// Note: yakkety is unsupported because it was officially deprecated on Launchpad.
   139  	// Note: zesty is unsupported because it was officially deprecated on Launchpad.
   140  	// Note: artful is unsupported because it was officially deprecated on Launchpad.
   141  	// Note: cosmic is unsupported because it was officially deprecated on Launchpad.
   142  	debDistroGoBoots = map[string]string{
   143  		"trusty": "golang-1.11",
   144  		"xenial": "golang-go",
   145  		"bionic": "golang-go",
   146  		"disco":  "golang-go",
   147  		"eoan":   "golang-go",
   148  	}
   149  
   150  	debGoBootPaths = map[string]string{
   151  		"golang-1.11": "/usr/lib/go-1.11",
   152  		"golang-go":   "/usr/lib/go",
   153  	}
   154  )
   155  
   156  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   157  
   158  func executablePath(name string) string {
   159  	if runtime.GOOS == "windows" {
   160  		name += ".exe"
   161  	}
   162  	return filepath.Join(GOBIN, name)
   163  }
   164  
   165  func main() {
   166  	log.SetFlags(log.Lshortfile)
   167  
   168  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   169  		log.Fatal("this script must be run from the root of the repository")
   170  	}
   171  	if len(os.Args) < 2 {
   172  		log.Fatal("need subcommand as first argument")
   173  	}
   174  	switch os.Args[1] {
   175  	case "install":
   176  		doInstall(os.Args[2:])
   177  	case "test":
   178  		doTest(os.Args[2:])
   179  	case "lint":
   180  		doLint(os.Args[2:])
   181  	case "archive":
   182  		doArchive(os.Args[2:])
   183  	case "debsrc":
   184  		doDebianSource(os.Args[2:])
   185  	case "nsis":
   186  		doWindowsInstaller(os.Args[2:])
   187  	case "aar":
   188  		doAndroidArchive(os.Args[2:])
   189  	case "xcode":
   190  		doXCodeFramework(os.Args[2:])
   191  	case "xgo":
   192  		doXgo(os.Args[2:])
   193  	case "purge":
   194  		doPurge(os.Args[2:])
   195  	default:
   196  		log.Fatal("unknown command ", os.Args[1])
   197  	}
   198  }
   199  
   200  // Compiling
   201  
   202  func doInstall(cmdline []string) {
   203  	var (
   204  		arch = flag.String("arch", "", "Architecture to cross build for")
   205  		cc   = flag.String("cc", "", "C compiler to cross build with")
   206  	)
   207  	flag.CommandLine.Parse(cmdline)
   208  	env := build.Env()
   209  
   210  	// Check Go version. People regularly open issues about compilation
   211  	// failure with outdated Go. This should save them the trouble.
   212  	if !strings.Contains(runtime.Version(), "devel") {
   213  		// Figure out the minor version number since we can't textually compare (1.10 < 1.9)
   214  		var minor int
   215  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   216  
   217  		if minor < 9 {
   218  			log.Println("You have Go version", runtime.Version())
   219  			log.Println("go-ethereum requires at least Go version 1.9 and cannot")
   220  			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
   221  			os.Exit(1)
   222  		}
   223  	}
   224  	// Compile packages given as arguments, or everything if there are no arguments.
   225  	packages := []string{"./..."}
   226  	if flag.NArg() > 0 {
   227  		packages = flag.Args()
   228  	}
   229  
   230  	if *arch == "" || *arch == runtime.GOARCH {
   231  		goinstall := goTool("install", buildFlags(env)...)
   232  		goinstall.Args = append(goinstall.Args, "-v")
   233  		goinstall.Args = append(goinstall.Args, packages...)
   234  		build.MustRun(goinstall)
   235  		return
   236  	}
   237  	// If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any previous builds
   238  	if *arch == "arm" {
   239  		os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
   240  		for _, path := range filepath.SplitList(build.GOPATH()) {
   241  			os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
   242  		}
   243  	}
   244  	// Seems we are cross compiling, work around forbidden GOBIN
   245  	goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
   246  	goinstall.Args = append(goinstall.Args, "-v")
   247  	goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
   248  	goinstall.Args = append(goinstall.Args, packages...)
   249  	build.MustRun(goinstall)
   250  
   251  	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
   252  		for _, cmd := range cmds {
   253  			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
   254  			if err != nil {
   255  				log.Fatal(err)
   256  			}
   257  			for name := range pkgs {
   258  				if name == "main" {
   259  					gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
   260  					gobuild.Args = append(gobuild.Args, "-v")
   261  					gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
   262  					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
   263  					build.MustRun(gobuild)
   264  					break
   265  				}
   266  			}
   267  		}
   268  	}
   269  }
   270  
   271  func buildFlags(env build.Environment) (flags []string) {
   272  	var ld []string
   273  	if env.Commit != "" {
   274  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   275  		ld = append(ld, "-X", "main.gitDate="+env.Date)
   276  	}
   277  	if runtime.GOOS == "darwin" {
   278  		ld = append(ld, "-s")
   279  	}
   280  
   281  	if len(ld) > 0 {
   282  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   283  	}
   284  	return flags
   285  }
   286  
   287  func goTool(subcmd string, args ...string) *exec.Cmd {
   288  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   289  }
   290  
   291  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   292  	cmd := build.GoTool(subcmd, args...)
   293  	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
   294  	if arch == "" || arch == runtime.GOARCH {
   295  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   296  	} else {
   297  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   298  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   299  	}
   300  	if cc != "" {
   301  		cmd.Env = append(cmd.Env, "CC="+cc)
   302  	}
   303  	for _, e := range os.Environ() {
   304  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   305  			continue
   306  		}
   307  		cmd.Env = append(cmd.Env, e)
   308  	}
   309  	return cmd
   310  }
   311  
   312  // Running The Tests
   313  //
   314  // "tests" also includes static analysis tools such as vet.
   315  
   316  func doTest(cmdline []string) {
   317  	coverage := flag.Bool("coverage", false, "Whether to record code coverage")
   318  	flag.CommandLine.Parse(cmdline)
   319  	env := build.Env()
   320  
   321  	packages := []string{"./..."}
   322  	if len(flag.CommandLine.Args()) > 0 {
   323  		packages = flag.CommandLine.Args()
   324  	}
   325  
   326  	// Run the actual tests.
   327  	// Test a single package at a time. CI builders are slow
   328  	// and some tests run into timeouts under load.
   329  	gotest := goTool("test", buildFlags(env)...)
   330  	gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m", "--short")
   331  	if *coverage {
   332  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   333  	}
   334  
   335  	gotest.Args = append(gotest.Args, packages...)
   336  	build.MustRun(gotest)
   337  }
   338  
   339  // runs gometalinter on requested packages
   340  func doLint(cmdline []string) {
   341  	flag.CommandLine.Parse(cmdline)
   342  
   343  	packages := []string{"./..."}
   344  	if len(flag.CommandLine.Args()) > 0 {
   345  		packages = flag.CommandLine.Args()
   346  	}
   347  	// Get metalinter and install all supported linters
   348  	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
   349  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
   350  
   351  	// Run fast linters batched together
   352  	configs := []string{
   353  		"--vendor",
   354  		"--tests",
   355  		"--deadline=2m",
   356  		"--disable-all",
   357  		"--enable=goimports",
   358  		"--enable=varcheck",
   359  		"--enable=vet",
   360  		"--enable=gofmt",
   361  		"--enable=misspell",
   362  		"--enable=goconst",
   363  		"--min-occurrences=6", // for goconst
   364  	}
   365  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   366  
   367  	// Run slow linters one by one
   368  	for _, linter := range []string{"unconvert", "gosimple"} {
   369  		configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
   370  		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   371  	}
   372  }
   373  
   374  // Release Packaging
   375  func doArchive(cmdline []string) {
   376  	var (
   377  		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   378  		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   379  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   380  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   381  		ext    string
   382  	)
   383  	flag.CommandLine.Parse(cmdline)
   384  	switch *atype {
   385  	case "zip":
   386  		ext = ".zip"
   387  	case "tar":
   388  		ext = ".tar.gz"
   389  	default:
   390  		log.Fatal("unknown archive type: ", atype)
   391  	}
   392  
   393  	var (
   394  		env = build.Env()
   395  
   396  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   397  		geth     = "geth-" + basegeth + ext
   398  		alltools = "geth-alltools-" + basegeth + ext
   399  	)
   400  	maybeSkipArchive(env)
   401  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   402  		log.Fatal(err)
   403  	}
   404  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   405  		log.Fatal(err)
   406  	}
   407  	for _, archive := range []string{geth, alltools} {
   408  		if err := archiveUpload(archive, *upload, *signer); err != nil {
   409  			log.Fatal(err)
   410  		}
   411  	}
   412  }
   413  
   414  func archiveBasename(arch string, archiveVersion string) string {
   415  	platform := runtime.GOOS + "-" + arch
   416  	if arch == "arm" {
   417  		platform += os.Getenv("GOARM")
   418  	}
   419  	if arch == "android" {
   420  		platform = "android-all"
   421  	}
   422  	if arch == "ios" {
   423  		platform = "ios-all"
   424  	}
   425  	return platform + "-" + archiveVersion
   426  }
   427  
   428  func archiveUpload(archive string, blobstore string, signer string) error {
   429  	// If signing was requested, generate the signature files
   430  	if signer != "" {
   431  		key := getenvBase64(signer)
   432  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   433  			return err
   434  		}
   435  	}
   436  	// If uploading to Azure was requested, push the archive possibly with its signature
   437  	if blobstore != "" {
   438  		auth := build.AzureBlobstoreConfig{
   439  			Account:   strings.Split(blobstore, "/")[0],
   440  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   441  			Container: strings.SplitN(blobstore, "/", 2)[1],
   442  		}
   443  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   444  			return err
   445  		}
   446  		if signer != "" {
   447  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   448  				return err
   449  			}
   450  		}
   451  	}
   452  	return nil
   453  }
   454  
   455  // skips archiving for some build configurations.
   456  func maybeSkipArchive(env build.Environment) {
   457  	if env.IsPullRequest {
   458  		log.Printf("skipping because this is a PR build")
   459  		os.Exit(0)
   460  	}
   461  	if env.IsCronJob {
   462  		log.Printf("skipping because this is a cron job")
   463  		os.Exit(0)
   464  	}
   465  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   466  		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
   467  		os.Exit(0)
   468  	}
   469  }
   470  
   471  // Debian Packaging
   472  func doDebianSource(cmdline []string) {
   473  	var (
   474  		goversion = flag.String("goversion", "", `Go version to build with (will be included in the source package)`)
   475  		gobundle  = flag.String("gobundle", "/tmp/go.tar.gz", `Filesystem path to cache the downloaded Go bundles at`)
   476  		gohash    = flag.String("gohash", "", `SHA256 checksum of the Go sources requested to build with`)
   477  		signer    = flag.String("signer", "", `Signing key name, also used as package author`)
   478  		upload    = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   479  		sshUser   = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   480  		workdir   = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   481  		now       = time.Now()
   482  	)
   483  	flag.CommandLine.Parse(cmdline)
   484  	*workdir = makeWorkdir(*workdir)
   485  	env := build.Env()
   486  	maybeSkipArchive(env)
   487  
   488  	// Import the signing key.
   489  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   490  		gpg := exec.Command("gpg", "--import")
   491  		gpg.Stdin = bytes.NewReader(key)
   492  		build.MustRun(gpg)
   493  	}
   494  	// Download and verify the Go source package
   495  	if err := build.EnsureGoSources(*goversion, hexutil.MustDecode("0x"+*gohash), *gobundle); err != nil {
   496  		log.Fatalf("Failed to ensure Go source package: %v", err)
   497  	}
   498  	// Create Debian packages and upload them
   499  	for _, pkg := range debPackages {
   500  		for distro, goboot := range debDistroGoBoots {
   501  			// Prepare the debian package with the go-ethereum sources
   502  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   503  			pkgdir := stageDebianSource(*workdir, meta)
   504  
   505  			// Ship the Go sources along so we have a proper thing to build with
   506  			if err := build.ExtractTarballArchive(*gobundle, pkgdir); err != nil {
   507  				log.Fatalf("Failed to extract Go sources: %v", err)
   508  			}
   509  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   510  				log.Fatalf("Failed to rename Go source folder: %v", err)
   511  			}
   512  			// Run the packaging and upload to the PPA
   513  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz")
   514  			debuild.Dir = pkgdir
   515  			build.MustRun(debuild)
   516  
   517  			var (
   518  				basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   519  				source   = filepath.Join(*workdir, basename+".tar.xz")
   520  				dsc      = filepath.Join(*workdir, basename+".dsc")
   521  				changes  = filepath.Join(*workdir, basename+"_source.changes")
   522  			)
   523  			if *signer != "" {
   524  				build.MustRunCommand("debsign", changes)
   525  			}
   526  			if *upload != "" {
   527  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
   528  			}
   529  		}
   530  	}
   531  }
   532  
   533  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   534  	p := strings.Split(ppa, "/")
   535  	if len(p) != 2 {
   536  		log.Fatal("-upload PPA name must contain single /")
   537  	}
   538  	if sshUser == "" {
   539  		sshUser = p[0]
   540  	}
   541  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   542  	// Create the SSH identity file if it doesn't exist.
   543  	var idfile string
   544  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   545  		idfile = filepath.Join(workdir, "sshkey")
   546  		if _, err := os.Stat(idfile); os.IsNotExist(err) {
   547  			ioutil.WriteFile(idfile, sshkey, 0600)
   548  		}
   549  	}
   550  	// Upload
   551  	dest := sshUser + "@ppa.launchpad.net"
   552  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   553  		log.Fatal(err)
   554  	}
   555  }
   556  
   557  func getenvBase64(variable string) []byte {
   558  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   559  	if err != nil {
   560  		log.Fatal("invalid base64 " + variable)
   561  	}
   562  	return []byte(dec)
   563  }
   564  
   565  func makeWorkdir(wdflag string) string {
   566  	var err error
   567  	if wdflag != "" {
   568  		err = os.MkdirAll(wdflag, 0744)
   569  	} else {
   570  		wdflag, err = ioutil.TempDir("", "geth-build-")
   571  	}
   572  	if err != nil {
   573  		log.Fatal(err)
   574  	}
   575  	return wdflag
   576  }
   577  
   578  func isUnstableBuild(env build.Environment) bool {
   579  	if env.Tag != "" {
   580  		return false
   581  	}
   582  	return true
   583  }
   584  
   585  type debPackage struct {
   586  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   587  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   588  	Executables []debExecutable // executables to be included in the package
   589  }
   590  
   591  type debMetadata struct {
   592  	Env           build.Environment
   593  	GoBootPackage string
   594  	GoBootPath    string
   595  
   596  	PackageName string
   597  
   598  	// go-ethereum version being built. Note that this
   599  	// is not the debian package version. The package version
   600  	// is constructed by VersionString.
   601  	Version string
   602  
   603  	Author       string // "name <email>", also selects signing key
   604  	Distro, Time string
   605  	Executables  []debExecutable
   606  }
   607  
   608  type debExecutable struct {
   609  	PackageName string
   610  	BinaryName  string
   611  	Description string
   612  }
   613  
   614  // Package returns the name of the package if present, or
   615  // fallbacks to BinaryName
   616  func (d debExecutable) Package() string {
   617  	if d.PackageName != "" {
   618  		return d.PackageName
   619  	}
   620  	return d.BinaryName
   621  }
   622  
   623  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   624  	if author == "" {
   625  		// No signing key, use default author.
   626  		author = "Ethereum Builds <fjl@ethereum.org>"
   627  	}
   628  	return debMetadata{
   629  		GoBootPackage: goboot,
   630  		GoBootPath:    debGoBootPaths[goboot],
   631  		PackageName:   name,
   632  		Env:           env,
   633  		Author:        author,
   634  		Distro:        distro,
   635  		Version:       version,
   636  		Time:          t.Format(time.RFC1123Z),
   637  		Executables:   exes,
   638  	}
   639  }
   640  
   641  // Name returns the name of the metapackage that depends
   642  // on all executable packages.
   643  func (meta debMetadata) Name() string {
   644  	if isUnstableBuild(meta.Env) {
   645  		return meta.PackageName + "-unstable"
   646  	}
   647  	return meta.PackageName
   648  }
   649  
   650  // VersionString returns the debian version of the packages.
   651  func (meta debMetadata) VersionString() string {
   652  	vsn := meta.Version
   653  	if meta.Env.Buildnum != "" {
   654  		vsn += "+build" + meta.Env.Buildnum
   655  	}
   656  	if meta.Distro != "" {
   657  		vsn += "+" + meta.Distro
   658  	}
   659  	return vsn
   660  }
   661  
   662  // ExeList returns the list of all executable packages.
   663  func (meta debMetadata) ExeList() string {
   664  	names := make([]string, len(meta.Executables))
   665  	for i, e := range meta.Executables {
   666  		names[i] = meta.ExeName(e)
   667  	}
   668  	return strings.Join(names, ", ")
   669  }
   670  
   671  // ExeName returns the package name of an executable package.
   672  func (meta debMetadata) ExeName(exe debExecutable) string {
   673  	if isUnstableBuild(meta.Env) {
   674  		return exe.Package() + "-unstable"
   675  	}
   676  	return exe.Package()
   677  }
   678  
   679  // ExeConflicts returns the content of the Conflicts field
   680  // for executable packages.
   681  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   682  	if isUnstableBuild(meta.Env) {
   683  		// Set up the conflicts list so that the *-unstable packages
   684  		// cannot be installed alongside the regular version.
   685  		//
   686  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   687  		// is very explicit about Conflicts: and says that Breaks: should
   688  		// be preferred and the conflicting files should be handled via
   689  		// alternates. We might do this eventually but using a conflict is
   690  		// easier now.
   691  		return "ethereum, " + exe.Package()
   692  	}
   693  	return ""
   694  }
   695  
   696  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   697  	pkg := meta.Name() + "-" + meta.VersionString()
   698  	pkgdir = filepath.Join(tmpdir, pkg)
   699  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   700  		log.Fatal(err)
   701  	}
   702  	// Copy the source code.
   703  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   704  
   705  	// Put the debian build files in place.
   706  	debian := filepath.Join(pkgdir, "debian")
   707  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   708  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   709  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   710  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   711  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   712  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   713  	for _, exe := range meta.Executables {
   714  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   715  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   716  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   717  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   718  	}
   719  	return pkgdir
   720  }
   721  
   722  // Windows installer
   723  func doWindowsInstaller(cmdline []string) {
   724  	// Parse the flags and make skip installer generation on PRs
   725  	var (
   726  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   727  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   728  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   729  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   730  	)
   731  	flag.CommandLine.Parse(cmdline)
   732  	*workdir = makeWorkdir(*workdir)
   733  	env := build.Env()
   734  	maybeSkipArchive(env)
   735  
   736  	// Aggregate binaries that are included in the installer
   737  	var (
   738  		devTools []string
   739  		allTools []string
   740  		gethTool string
   741  	)
   742  	for _, file := range allToolsArchiveFiles {
   743  		if file == "COPYING" { // license, copied later
   744  			continue
   745  		}
   746  		allTools = append(allTools, filepath.Base(file))
   747  		if filepath.Base(file) == "geth.exe" {
   748  			gethTool = file
   749  		} else {
   750  			devTools = append(devTools, file)
   751  		}
   752  	}
   753  
   754  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   755  	// first section contains the geth binary, second section holds the dev tools.
   756  	templateData := map[string]interface{}{
   757  		"License":  "COPYING",
   758  		"Geth":     gethTool,
   759  		"DevTools": devTools,
   760  	}
   761  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   762  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   763  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   764  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   765  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   766  	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
   767  	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
   768  
   769  	// Build the installer. This assumes that all the needed files have been previously
   770  	// built (don't mix building and packaging to keep cross compilation complexity to a
   771  	// minimum).
   772  	version := strings.Split(params.Version, ".")
   773  	if env.Commit != "" {
   774  		version[2] += "-" + env.Commit[:8]
   775  	}
   776  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   777  	build.MustRunCommand("makensis.exe",
   778  		"/DOUTPUTFILE="+installer,
   779  		"/DMAJORVERSION="+version[0],
   780  		"/DMINORVERSION="+version[1],
   781  		"/DBUILDVERSION="+version[2],
   782  		"/DARCH="+*arch,
   783  		filepath.Join(*workdir, "geth.nsi"),
   784  	)
   785  
   786  	// Sign and publish installer.
   787  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   788  		log.Fatal(err)
   789  	}
   790  }
   791  
   792  // Android archives
   793  
   794  func doAndroidArchive(cmdline []string) {
   795  	var (
   796  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   797  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   798  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   799  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   800  	)
   801  	flag.CommandLine.Parse(cmdline)
   802  	env := build.Env()
   803  
   804  	// Sanity check that the SDK and NDK are installed and set
   805  	if os.Getenv("ANDROID_HOME") == "" {
   806  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   807  	}
   808  	// Build the Android archive and Maven resources
   809  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   810  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
   811  
   812  	if *local {
   813  		// If we're building locally, copy bundle to build dir and skip Maven
   814  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   815  		return
   816  	}
   817  	meta := newMavenMetadata(env)
   818  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   819  
   820  	// Skip Maven deploy and Azure upload for PR builds
   821  	maybeSkipArchive(env)
   822  
   823  	// Sign and upload the archive to Azure
   824  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
   825  	os.Rename("geth.aar", archive)
   826  
   827  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   828  		log.Fatal(err)
   829  	}
   830  	// Sign and upload all the artifacts to Maven Central
   831  	os.Rename(archive, meta.Package+".aar")
   832  	if *signer != "" && *deploy != "" {
   833  		// Import the signing key into the local GPG instance
   834  		key := getenvBase64(*signer)
   835  		gpg := exec.Command("gpg", "--import")
   836  		gpg.Stdin = bytes.NewReader(key)
   837  		build.MustRun(gpg)
   838  		keyID, err := build.PGPKeyID(string(key))
   839  		if err != nil {
   840  			log.Fatal(err)
   841  		}
   842  		// Upload the artifacts to Sonatype and/or Maven Central
   843  		repo := *deploy + "/service/local/staging/deploy/maven2"
   844  		if meta.Develop {
   845  			repo = *deploy + "/content/repositories/snapshots"
   846  		}
   847  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
   848  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   849  			"-Dgpg.keyname="+keyID,
   850  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   851  	}
   852  }
   853  
   854  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   855  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   856  	cmd.Args = append(cmd.Args, args...)
   857  	cmd.Env = []string{
   858  		"GOPATH=" + build.GOPATH(),
   859  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
   860  	}
   861  	for _, e := range os.Environ() {
   862  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
   863  			continue
   864  		}
   865  		cmd.Env = append(cmd.Env, e)
   866  	}
   867  	return cmd
   868  }
   869  
   870  type mavenMetadata struct {
   871  	Version      string
   872  	Package      string
   873  	Develop      bool
   874  	Contributors []mavenContributor
   875  }
   876  
   877  type mavenContributor struct {
   878  	Name  string
   879  	Email string
   880  }
   881  
   882  func newMavenMetadata(env build.Environment) mavenMetadata {
   883  	// Collect the list of authors from the repo root
   884  	contribs := []mavenContributor{}
   885  	if authors, err := os.Open("AUTHORS"); err == nil {
   886  		defer authors.Close()
   887  
   888  		scanner := bufio.NewScanner(authors)
   889  		for scanner.Scan() {
   890  			// Skip any whitespace from the authors list
   891  			line := strings.TrimSpace(scanner.Text())
   892  			if line == "" || line[0] == '#' {
   893  				continue
   894  			}
   895  			// Split the author and insert as a contributor
   896  			re := regexp.MustCompile("([^<]+) <(.+)>")
   897  			parts := re.FindStringSubmatch(line)
   898  			if len(parts) == 3 {
   899  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
   900  			}
   901  		}
   902  	}
   903  	// Render the version and package strings
   904  	version := params.Version
   905  	if isUnstableBuild(env) {
   906  		version += "-SNAPSHOT"
   907  	}
   908  	return mavenMetadata{
   909  		Version:      version,
   910  		Package:      "geth-" + version,
   911  		Develop:      isUnstableBuild(env),
   912  		Contributors: contribs,
   913  	}
   914  }
   915  
   916  // XCode frameworks
   917  
   918  func doXCodeFramework(cmdline []string) {
   919  	var (
   920  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   921  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
   922  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
   923  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   924  	)
   925  	flag.CommandLine.Parse(cmdline)
   926  	env := build.Env()
   927  
   928  	// Build the iOS XCode framework
   929  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   930  	build.MustRun(gomobileTool("init"))
   931  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
   932  
   933  	if *local {
   934  		// If we're building locally, use the build folder and stop afterwards
   935  		bind.Dir, _ = filepath.Abs(GOBIN)
   936  		build.MustRun(bind)
   937  		return
   938  	}
   939  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
   940  	if err := os.Mkdir(archive, os.ModePerm); err != nil {
   941  		log.Fatal(err)
   942  	}
   943  	bind.Dir, _ = filepath.Abs(archive)
   944  	build.MustRun(bind)
   945  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
   946  
   947  	// Skip CocoaPods deploy and Azure upload for PR builds
   948  	maybeSkipArchive(env)
   949  
   950  	// Sign and upload the framework to Azure
   951  	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
   952  		log.Fatal(err)
   953  	}
   954  	// Prepare and upload a PodSpec to CocoaPods
   955  	if *deploy != "" {
   956  		meta := newPodMetadata(env, archive)
   957  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
   958  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
   959  	}
   960  }
   961  
   962  type podMetadata struct {
   963  	Version      string
   964  	Commit       string
   965  	Archive      string
   966  	Contributors []podContributor
   967  }
   968  
   969  type podContributor struct {
   970  	Name  string
   971  	Email string
   972  }
   973  
   974  func newPodMetadata(env build.Environment, archive string) podMetadata {
   975  	// Collect the list of authors from the repo root
   976  	contribs := []podContributor{}
   977  	if authors, err := os.Open("AUTHORS"); err == nil {
   978  		defer authors.Close()
   979  
   980  		scanner := bufio.NewScanner(authors)
   981  		for scanner.Scan() {
   982  			// Skip any whitespace from the authors list
   983  			line := strings.TrimSpace(scanner.Text())
   984  			if line == "" || line[0] == '#' {
   985  				continue
   986  			}
   987  			// Split the author and insert as a contributor
   988  			re := regexp.MustCompile("([^<]+) <(.+)>")
   989  			parts := re.FindStringSubmatch(line)
   990  			if len(parts) == 3 {
   991  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
   992  			}
   993  		}
   994  	}
   995  	version := params.Version
   996  	if isUnstableBuild(env) {
   997  		version += "-unstable." + env.Buildnum
   998  	}
   999  	return podMetadata{
  1000  		Archive:      archive,
  1001  		Version:      version,
  1002  		Commit:       env.Commit,
  1003  		Contributors: contribs,
  1004  	}
  1005  }
  1006  
  1007  // Cross compilation
  1008  
  1009  func doXgo(cmdline []string) {
  1010  	var (
  1011  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1012  	)
  1013  	flag.CommandLine.Parse(cmdline)
  1014  	env := build.Env()
  1015  
  1016  	// Make sure xgo is available for cross compilation
  1017  	gogetxgo := goTool("get", "github.com/karalabe/xgo")
  1018  	build.MustRun(gogetxgo)
  1019  
  1020  	// If all tools building is requested, build everything the builder wants
  1021  	args := append(buildFlags(env), flag.Args()...)
  1022  
  1023  	if *alltools {
  1024  		args = append(args, []string{"--dest", GOBIN}...)
  1025  		for _, res := range allToolsArchiveFiles {
  1026  			if strings.HasPrefix(res, GOBIN) {
  1027  				// Binary tool found, cross build it explicitly
  1028  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1029  				xgo := xgoTool(args)
  1030  				build.MustRun(xgo)
  1031  				args = args[:len(args)-1]
  1032  			}
  1033  		}
  1034  		return
  1035  	}
  1036  	// Otherwise xxecute the explicit cross compilation
  1037  	path := args[len(args)-1]
  1038  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1039  
  1040  	xgo := xgoTool(args)
  1041  	build.MustRun(xgo)
  1042  }
  1043  
  1044  func xgoTool(args []string) *exec.Cmd {
  1045  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1046  	cmd.Env = []string{
  1047  		"GOPATH=" + build.GOPATH(),
  1048  		"GOBIN=" + GOBIN,
  1049  	}
  1050  	for _, e := range os.Environ() {
  1051  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  1052  			continue
  1053  		}
  1054  		cmd.Env = append(cmd.Env, e)
  1055  	}
  1056  	return cmd
  1057  }
  1058  
  1059  // Binary distribution cleanups
  1060  
  1061  func doPurge(cmdline []string) {
  1062  	var (
  1063  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1064  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1065  	)
  1066  	flag.CommandLine.Parse(cmdline)
  1067  
  1068  	if env := build.Env(); !env.IsCronJob {
  1069  		log.Printf("skipping because not a cron job")
  1070  		os.Exit(0)
  1071  	}
  1072  	// Create the azure authentication and list the current archives
  1073  	auth := build.AzureBlobstoreConfig{
  1074  		Account:   strings.Split(*store, "/")[0],
  1075  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1076  		Container: strings.SplitN(*store, "/", 2)[1],
  1077  	}
  1078  	blobs, err := build.AzureBlobstoreList(auth)
  1079  	if err != nil {
  1080  		log.Fatal(err)
  1081  	}
  1082  	// Iterate over the blobs, collect and sort all unstable builds
  1083  	for i := 0; i < len(blobs); i++ {
  1084  		if !strings.Contains(blobs[i].Name, "unstable") {
  1085  			blobs = append(blobs[:i], blobs[i+1:]...)
  1086  			i--
  1087  		}
  1088  	}
  1089  	for i := 0; i < len(blobs); i++ {
  1090  		for j := i + 1; j < len(blobs); j++ {
  1091  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1092  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1093  			}
  1094  		}
  1095  	}
  1096  	// Filter out all archives more recent that the given threshold
  1097  	for i, blob := range blobs {
  1098  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1099  			blobs = blobs[:i]
  1100  			break
  1101  		}
  1102  	}
  1103  	// Delete all marked as such and return
  1104  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1105  		log.Fatal(err)
  1106  	}
  1107  }