github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/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/cespare/cp"
    62  	"github.com/ethereum-optimism/optimism/l2geth/internal/build"
    63  	"github.com/ethereum-optimism/optimism/l2geth/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  		"focal":  "golang-go",
   149  	}
   150  
   151  	debGoBootPaths = map[string]string{
   152  		"golang-1.11": "/usr/lib/go-1.11",
   153  		"golang-go":   "/usr/lib/go",
   154  	}
   155  )
   156  
   157  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   158  
   159  func executablePath(name string) string {
   160  	if runtime.GOOS == "windows" {
   161  		name += ".exe"
   162  	}
   163  	return filepath.Join(GOBIN, name)
   164  }
   165  
   166  func main() {
   167  	log.SetFlags(log.Lshortfile)
   168  
   169  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   170  		log.Fatal("this script must be run from the root of the repository")
   171  	}
   172  	if len(os.Args) < 2 {
   173  		log.Fatal("need subcommand as first argument")
   174  	}
   175  	switch os.Args[1] {
   176  	case "install":
   177  		doInstall(os.Args[2:])
   178  	case "test":
   179  		doTest(os.Args[2:])
   180  	case "lint":
   181  		doLint(os.Args[2:])
   182  	case "archive":
   183  		doArchive(os.Args[2:])
   184  	case "debsrc":
   185  		doDebianSource(os.Args[2:])
   186  	case "nsis":
   187  		doWindowsInstaller(os.Args[2:])
   188  	case "aar":
   189  		doAndroidArchive(os.Args[2:])
   190  	case "xcode":
   191  		doXCodeFramework(os.Args[2:])
   192  	case "xgo":
   193  		doXgo(os.Args[2:])
   194  	case "purge":
   195  		doPurge(os.Args[2:])
   196  	default:
   197  		log.Fatal("unknown command ", os.Args[1])
   198  	}
   199  }
   200  
   201  // Compiling
   202  
   203  func doInstall(cmdline []string) {
   204  	var (
   205  		arch = flag.String("arch", "", "Architecture to cross build for")
   206  		cc   = flag.String("cc", "", "C compiler to cross build with")
   207  	)
   208  	flag.CommandLine.Parse(cmdline)
   209  	env := build.Env()
   210  
   211  	// Check Go version. People regularly open issues about compilation
   212  	// failure with outdated Go. This should save them the trouble.
   213  	if !strings.Contains(runtime.Version(), "devel") {
   214  		// Figure out the minor version number since we can't textually compare (1.10 < 1.9)
   215  		var minor int
   216  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   217  
   218  		if minor < 11 {
   219  			log.Println("You have Go version", runtime.Version())
   220  			log.Println("go-ethereum requires at least Go version 1.11 and cannot")
   221  			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
   222  			os.Exit(1)
   223  		}
   224  	}
   225  	// Compile packages given as arguments, or everything if there are no arguments.
   226  	packages := []string{"./..."}
   227  	if flag.NArg() > 0 {
   228  		packages = flag.Args()
   229  	}
   230  
   231  	if *arch == "" || *arch == runtime.GOARCH {
   232  		goinstall := goTool("install", buildFlags(env)...)
   233  		if runtime.GOARCH == "arm64" {
   234  			goinstall.Args = append(goinstall.Args, "-p", "1")
   235  		}
   236  		goinstall.Args = append(goinstall.Args, "-v")
   237  		goinstall.Args = append(goinstall.Args, packages...)
   238  		build.MustRun(goinstall)
   239  		return
   240  	}
   241  
   242  	// Seems we are cross compiling, work around forbidden GOBIN
   243  	goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
   244  	goinstall.Args = append(goinstall.Args, "-v")
   245  	goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
   246  	goinstall.Args = append(goinstall.Args, packages...)
   247  	build.MustRun(goinstall)
   248  
   249  	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
   250  		for _, cmd := range cmds {
   251  			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
   252  			if err != nil {
   253  				log.Fatal(err)
   254  			}
   255  			for name := range pkgs {
   256  				if name == "main" {
   257  					gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
   258  					gobuild.Args = append(gobuild.Args, "-v")
   259  					gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
   260  					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
   261  					build.MustRun(gobuild)
   262  					break
   263  				}
   264  			}
   265  		}
   266  	}
   267  }
   268  
   269  func buildFlags(env build.Environment) (flags []string) {
   270  	var ld []string
   271  	if env.Commit != "" {
   272  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   273  		ld = append(ld, "-X", "main.gitDate="+env.Date)
   274  	}
   275  	if runtime.GOOS == "darwin" {
   276  		ld = append(ld, "-s")
   277  	}
   278  
   279  	if len(ld) > 0 {
   280  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   281  	}
   282  	return flags
   283  }
   284  
   285  func goTool(subcmd string, args ...string) *exec.Cmd {
   286  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   287  }
   288  
   289  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   290  	cmd := build.GoTool(subcmd, args...)
   291  	if arch == "" || arch == runtime.GOARCH {
   292  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   293  	} else {
   294  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   295  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   296  	}
   297  	if cc != "" {
   298  		cmd.Env = append(cmd.Env, "CC="+cc)
   299  	}
   300  	for _, e := range os.Environ() {
   301  		if strings.HasPrefix(e, "GOBIN=") {
   302  			continue
   303  		}
   304  		cmd.Env = append(cmd.Env, e)
   305  	}
   306  	return cmd
   307  }
   308  
   309  // Running The Tests
   310  //
   311  // "tests" also includes static analysis tools such as vet.
   312  
   313  func doTest(cmdline []string) {
   314  	coverage := flag.Bool("coverage", false, "Whether to record code coverage")
   315  	verbose := flag.Bool("v", false, "Whether to log verbosely")
   316  	flag.CommandLine.Parse(cmdline)
   317  	env := build.Env()
   318  
   319  	packages := []string{"./..."}
   320  	if len(flag.CommandLine.Args()) > 0 {
   321  		packages = flag.CommandLine.Args()
   322  	}
   323  
   324  	// Run the actual tests.
   325  	// Test a single package at a time. CI builders are slow
   326  	// and some tests run into timeouts under load.
   327  	gotest := goTool("test", buildFlags(env)...)
   328  	gotest.Args = append(gotest.Args, "-p", "1")
   329  	if *coverage {
   330  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   331  	}
   332  	if *verbose {
   333  		gotest.Args = append(gotest.Args, "-v")
   334  	}
   335  
   336  	gotest.Args = append(gotest.Args, packages...)
   337  	build.MustRun(gotest)
   338  }
   339  
   340  // doLint runs golangci-lint on requested packages.
   341  func doLint(cmdline []string) {
   342  	var (
   343  		cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
   344  	)
   345  	flag.CommandLine.Parse(cmdline)
   346  	packages := []string{"./..."}
   347  	if len(flag.CommandLine.Args()) > 0 {
   348  		packages = flag.CommandLine.Args()
   349  	}
   350  
   351  	linter := downloadLinter(*cachedir)
   352  	lflags := []string{"run", "--config", ".golangci.yml"}
   353  	build.MustRunCommand(linter, append(lflags, packages...)...)
   354  	fmt.Println("You have achieved perfection.")
   355  }
   356  
   357  // downloadLinter downloads and unpacks golangci-lint.
   358  func downloadLinter(cachedir string) string {
   359  	const version = "1.24.0"
   360  
   361  	csdb := build.MustLoadChecksums("build/checksums.txt")
   362  	base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
   363  	url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
   364  	archivePath := filepath.Join(cachedir, base+".tar.gz")
   365  	if err := csdb.DownloadFile(url, archivePath); err != nil {
   366  		log.Fatal(err)
   367  	}
   368  	if err := build.ExtractTarballArchive(archivePath, cachedir); err != nil {
   369  		log.Fatal(err)
   370  	}
   371  	return filepath.Join(cachedir, base, "golangci-lint")
   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  		cachedir  = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
   476  		signer    = flag.String("signer", "", `Signing key name, also used as package author`)
   477  		upload    = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   478  		sshUser   = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   479  		workdir   = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   480  		now       = time.Now()
   481  	)
   482  	flag.CommandLine.Parse(cmdline)
   483  	*workdir = makeWorkdir(*workdir)
   484  	env := build.Env()
   485  	maybeSkipArchive(env)
   486  
   487  	// Import the signing key.
   488  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   489  		gpg := exec.Command("gpg", "--import")
   490  		gpg.Stdin = bytes.NewReader(key)
   491  		build.MustRun(gpg)
   492  	}
   493  
   494  	// Download and verify the Go source package.
   495  	gobundle := downloadGoSources(*goversion, *cachedir)
   496  
   497  	// Download all the dependencies needed to build the sources and run the ci script
   498  	srcdepfetch := goTool("install", "-n", "./...")
   499  	srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
   500  	build.MustRun(srcdepfetch)
   501  
   502  	cidepfetch := goTool("run", "./build/ci.go")
   503  	cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
   504  	cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
   505  
   506  	// Create Debian packages and upload them.
   507  	for _, pkg := range debPackages {
   508  		for distro, goboot := range debDistroGoBoots {
   509  			// Prepare the debian package with the go-ethereum sources.
   510  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   511  			pkgdir := stageDebianSource(*workdir, meta)
   512  
   513  			// Add Go source code
   514  			if err := build.ExtractTarballArchive(gobundle, pkgdir); err != nil {
   515  				log.Fatalf("Failed to extract Go sources: %v", err)
   516  			}
   517  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   518  				log.Fatalf("Failed to rename Go source folder: %v", err)
   519  			}
   520  			// Add all dependency modules in compressed form
   521  			os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
   522  			if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
   523  				log.Fatalf("Failed to copy Go module dependencies: %v", err)
   524  			}
   525  			// Run the packaging and upload to the PPA
   526  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
   527  			debuild.Dir = pkgdir
   528  			build.MustRun(debuild)
   529  
   530  			var (
   531  				basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   532  				source   = filepath.Join(*workdir, basename+".tar.xz")
   533  				dsc      = filepath.Join(*workdir, basename+".dsc")
   534  				changes  = filepath.Join(*workdir, basename+"_source.changes")
   535  			)
   536  			if *signer != "" {
   537  				build.MustRunCommand("debsign", changes)
   538  			}
   539  			if *upload != "" {
   540  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
   541  			}
   542  		}
   543  	}
   544  }
   545  
   546  func downloadGoSources(version string, cachedir string) string {
   547  	csdb := build.MustLoadChecksums("build/checksums.txt")
   548  	file := fmt.Sprintf("go%s.src.tar.gz", version)
   549  	url := "https://dl.google.com/go/" + file
   550  	dst := filepath.Join(cachedir, file)
   551  	if err := csdb.DownloadFile(url, dst); err != nil {
   552  		log.Fatal(err)
   553  	}
   554  	return dst
   555  }
   556  
   557  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   558  	p := strings.Split(ppa, "/")
   559  	if len(p) != 2 {
   560  		log.Fatal("-upload PPA name must contain single /")
   561  	}
   562  	if sshUser == "" {
   563  		sshUser = p[0]
   564  	}
   565  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   566  	// Create the SSH identity file if it doesn't exist.
   567  	var idfile string
   568  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   569  		idfile = filepath.Join(workdir, "sshkey")
   570  		if _, err := os.Stat(idfile); os.IsNotExist(err) {
   571  			ioutil.WriteFile(idfile, sshkey, 0600)
   572  		}
   573  	}
   574  	// Upload
   575  	dest := sshUser + "@ppa.launchpad.net"
   576  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   577  		log.Fatal(err)
   578  	}
   579  }
   580  
   581  func getenvBase64(variable string) []byte {
   582  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   583  	if err != nil {
   584  		log.Fatal("invalid base64 " + variable)
   585  	}
   586  	return []byte(dec)
   587  }
   588  
   589  func makeWorkdir(wdflag string) string {
   590  	var err error
   591  	if wdflag != "" {
   592  		err = os.MkdirAll(wdflag, 0744)
   593  	} else {
   594  		wdflag, err = ioutil.TempDir("", "geth-build-")
   595  	}
   596  	if err != nil {
   597  		log.Fatal(err)
   598  	}
   599  	return wdflag
   600  }
   601  
   602  func isUnstableBuild(env build.Environment) bool {
   603  	if env.Tag != "" {
   604  		return false
   605  	}
   606  	return true
   607  }
   608  
   609  type debPackage struct {
   610  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   611  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   612  	Executables []debExecutable // executables to be included in the package
   613  }
   614  
   615  type debMetadata struct {
   616  	Env           build.Environment
   617  	GoBootPackage string
   618  	GoBootPath    string
   619  
   620  	PackageName string
   621  
   622  	// go-ethereum version being built. Note that this
   623  	// is not the debian package version. The package version
   624  	// is constructed by VersionString.
   625  	Version string
   626  
   627  	Author       string // "name <email>", also selects signing key
   628  	Distro, Time string
   629  	Executables  []debExecutable
   630  }
   631  
   632  type debExecutable struct {
   633  	PackageName string
   634  	BinaryName  string
   635  	Description string
   636  }
   637  
   638  // Package returns the name of the package if present, or
   639  // fallbacks to BinaryName
   640  func (d debExecutable) Package() string {
   641  	if d.PackageName != "" {
   642  		return d.PackageName
   643  	}
   644  	return d.BinaryName
   645  }
   646  
   647  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   648  	if author == "" {
   649  		// No signing key, use default author.
   650  		author = "Ethereum Builds <fjl@ethereum.org>"
   651  	}
   652  	return debMetadata{
   653  		GoBootPackage: goboot,
   654  		GoBootPath:    debGoBootPaths[goboot],
   655  		PackageName:   name,
   656  		Env:           env,
   657  		Author:        author,
   658  		Distro:        distro,
   659  		Version:       version,
   660  		Time:          t.Format(time.RFC1123Z),
   661  		Executables:   exes,
   662  	}
   663  }
   664  
   665  // Name returns the name of the metapackage that depends
   666  // on all executable packages.
   667  func (meta debMetadata) Name() string {
   668  	if isUnstableBuild(meta.Env) {
   669  		return meta.PackageName + "-unstable"
   670  	}
   671  	return meta.PackageName
   672  }
   673  
   674  // VersionString returns the debian version of the packages.
   675  func (meta debMetadata) VersionString() string {
   676  	vsn := meta.Version
   677  	if meta.Env.Buildnum != "" {
   678  		vsn += "+build" + meta.Env.Buildnum
   679  	}
   680  	if meta.Distro != "" {
   681  		vsn += "+" + meta.Distro
   682  	}
   683  	return vsn
   684  }
   685  
   686  // ExeList returns the list of all executable packages.
   687  func (meta debMetadata) ExeList() string {
   688  	names := make([]string, len(meta.Executables))
   689  	for i, e := range meta.Executables {
   690  		names[i] = meta.ExeName(e)
   691  	}
   692  	return strings.Join(names, ", ")
   693  }
   694  
   695  // ExeName returns the package name of an executable package.
   696  func (meta debMetadata) ExeName(exe debExecutable) string {
   697  	if isUnstableBuild(meta.Env) {
   698  		return exe.Package() + "-unstable"
   699  	}
   700  	return exe.Package()
   701  }
   702  
   703  // ExeConflicts returns the content of the Conflicts field
   704  // for executable packages.
   705  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   706  	if isUnstableBuild(meta.Env) {
   707  		// Set up the conflicts list so that the *-unstable packages
   708  		// cannot be installed alongside the regular version.
   709  		//
   710  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   711  		// is very explicit about Conflicts: and says that Breaks: should
   712  		// be preferred and the conflicting files should be handled via
   713  		// alternates. We might do this eventually but using a conflict is
   714  		// easier now.
   715  		return "ethereum, " + exe.Package()
   716  	}
   717  	return ""
   718  }
   719  
   720  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   721  	pkg := meta.Name() + "-" + meta.VersionString()
   722  	pkgdir = filepath.Join(tmpdir, pkg)
   723  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   724  		log.Fatal(err)
   725  	}
   726  	// Copy the source code.
   727  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   728  
   729  	// Put the debian build files in place.
   730  	debian := filepath.Join(pkgdir, "debian")
   731  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   732  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   733  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   734  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   735  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   736  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   737  	for _, exe := range meta.Executables {
   738  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   739  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   740  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   741  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   742  	}
   743  	return pkgdir
   744  }
   745  
   746  // Windows installer
   747  func doWindowsInstaller(cmdline []string) {
   748  	// Parse the flags and make skip installer generation on PRs
   749  	var (
   750  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   751  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   752  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   753  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   754  	)
   755  	flag.CommandLine.Parse(cmdline)
   756  	*workdir = makeWorkdir(*workdir)
   757  	env := build.Env()
   758  	maybeSkipArchive(env)
   759  
   760  	// Aggregate binaries that are included in the installer
   761  	var (
   762  		devTools []string
   763  		allTools []string
   764  		gethTool string
   765  	)
   766  	for _, file := range allToolsArchiveFiles {
   767  		if file == "COPYING" { // license, copied later
   768  			continue
   769  		}
   770  		allTools = append(allTools, filepath.Base(file))
   771  		if filepath.Base(file) == "geth.exe" {
   772  			gethTool = file
   773  		} else {
   774  			devTools = append(devTools, file)
   775  		}
   776  	}
   777  
   778  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   779  	// first section contains the geth binary, second section holds the dev tools.
   780  	templateData := map[string]interface{}{
   781  		"License":  "COPYING",
   782  		"Geth":     gethTool,
   783  		"DevTools": devTools,
   784  	}
   785  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   786  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   787  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   788  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   789  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   790  	if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
   791  		log.Fatal("Failed to copy SimpleFC.dll: %v", err)
   792  	}
   793  	if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
   794  		log.Fatal("Failed to copy copyright note: %v", err)
   795  	}
   796  	// Build the installer. This assumes that all the needed files have been previously
   797  	// built (don't mix building and packaging to keep cross compilation complexity to a
   798  	// minimum).
   799  	version := strings.Split(params.Version, ".")
   800  	if env.Commit != "" {
   801  		version[2] += "-" + env.Commit[:8]
   802  	}
   803  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   804  	build.MustRunCommand("makensis.exe",
   805  		"/DOUTPUTFILE="+installer,
   806  		"/DMAJORVERSION="+version[0],
   807  		"/DMINORVERSION="+version[1],
   808  		"/DBUILDVERSION="+version[2],
   809  		"/DARCH="+*arch,
   810  		filepath.Join(*workdir, "geth.nsi"),
   811  	)
   812  	// Sign and publish installer.
   813  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   814  		log.Fatal(err)
   815  	}
   816  }
   817  
   818  // Android archives
   819  
   820  func doAndroidArchive(cmdline []string) {
   821  	var (
   822  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   823  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   824  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   825  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   826  	)
   827  	flag.CommandLine.Parse(cmdline)
   828  	env := build.Env()
   829  
   830  	// Sanity check that the SDK and NDK are installed and set
   831  	if os.Getenv("ANDROID_HOME") == "" {
   832  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   833  	}
   834  	// Build the Android archive and Maven resources
   835  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   836  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum-optimism/optimism/l2geth/mobile"))
   837  
   838  	if *local {
   839  		// If we're building locally, copy bundle to build dir and skip Maven
   840  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   841  		return
   842  	}
   843  	meta := newMavenMetadata(env)
   844  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   845  
   846  	// Skip Maven deploy and Azure upload for PR builds
   847  	maybeSkipArchive(env)
   848  
   849  	// Sign and upload the archive to Azure
   850  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
   851  	os.Rename("geth.aar", archive)
   852  
   853  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   854  		log.Fatal(err)
   855  	}
   856  	// Sign and upload all the artifacts to Maven Central
   857  	os.Rename(archive, meta.Package+".aar")
   858  	if *signer != "" && *deploy != "" {
   859  		// Import the signing key into the local GPG instance
   860  		key := getenvBase64(*signer)
   861  		gpg := exec.Command("gpg", "--import")
   862  		gpg.Stdin = bytes.NewReader(key)
   863  		build.MustRun(gpg)
   864  		keyID, err := build.PGPKeyID(string(key))
   865  		if err != nil {
   866  			log.Fatal(err)
   867  		}
   868  		// Upload the artifacts to Sonatype and/or Maven Central
   869  		repo := *deploy + "/service/local/staging/deploy/maven2"
   870  		if meta.Develop {
   871  			repo = *deploy + "/content/repositories/snapshots"
   872  		}
   873  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
   874  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   875  			"-Dgpg.keyname="+keyID,
   876  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   877  	}
   878  }
   879  
   880  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   881  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   882  	cmd.Args = append(cmd.Args, args...)
   883  	cmd.Env = []string{
   884  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
   885  	}
   886  	for _, e := range os.Environ() {
   887  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
   888  			continue
   889  		}
   890  		cmd.Env = append(cmd.Env, e)
   891  	}
   892  	return cmd
   893  }
   894  
   895  type mavenMetadata struct {
   896  	Version      string
   897  	Package      string
   898  	Develop      bool
   899  	Contributors []mavenContributor
   900  }
   901  
   902  type mavenContributor struct {
   903  	Name  string
   904  	Email string
   905  }
   906  
   907  func newMavenMetadata(env build.Environment) mavenMetadata {
   908  	// Collect the list of authors from the repo root
   909  	contribs := []mavenContributor{}
   910  	if authors, err := os.Open("AUTHORS"); err == nil {
   911  		defer authors.Close()
   912  
   913  		scanner := bufio.NewScanner(authors)
   914  		for scanner.Scan() {
   915  			// Skip any whitespace from the authors list
   916  			line := strings.TrimSpace(scanner.Text())
   917  			if line == "" || line[0] == '#' {
   918  				continue
   919  			}
   920  			// Split the author and insert as a contributor
   921  			re := regexp.MustCompile("([^<]+) <(.+)>")
   922  			parts := re.FindStringSubmatch(line)
   923  			if len(parts) == 3 {
   924  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
   925  			}
   926  		}
   927  	}
   928  	// Render the version and package strings
   929  	version := params.Version
   930  	if isUnstableBuild(env) {
   931  		version += "-SNAPSHOT"
   932  	}
   933  	return mavenMetadata{
   934  		Version:      version,
   935  		Package:      "geth-" + version,
   936  		Develop:      isUnstableBuild(env),
   937  		Contributors: contribs,
   938  	}
   939  }
   940  
   941  // XCode frameworks
   942  
   943  func doXCodeFramework(cmdline []string) {
   944  	var (
   945  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   946  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
   947  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
   948  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   949  	)
   950  	flag.CommandLine.Parse(cmdline)
   951  	env := build.Env()
   952  
   953  	// Build the iOS XCode framework
   954  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   955  	build.MustRun(gomobileTool("init"))
   956  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum-optimism/optimism/l2geth/mobile")
   957  
   958  	if *local {
   959  		// If we're building locally, use the build folder and stop afterwards
   960  		bind.Dir, _ = filepath.Abs(GOBIN)
   961  		build.MustRun(bind)
   962  		return
   963  	}
   964  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
   965  	if err := os.Mkdir(archive, os.ModePerm); err != nil {
   966  		log.Fatal(err)
   967  	}
   968  	bind.Dir, _ = filepath.Abs(archive)
   969  	build.MustRun(bind)
   970  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
   971  
   972  	// Skip CocoaPods deploy and Azure upload for PR builds
   973  	maybeSkipArchive(env)
   974  
   975  	// Sign and upload the framework to Azure
   976  	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
   977  		log.Fatal(err)
   978  	}
   979  	// Prepare and upload a PodSpec to CocoaPods
   980  	if *deploy != "" {
   981  		meta := newPodMetadata(env, archive)
   982  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
   983  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
   984  	}
   985  }
   986  
   987  type podMetadata struct {
   988  	Version      string
   989  	Commit       string
   990  	Archive      string
   991  	Contributors []podContributor
   992  }
   993  
   994  type podContributor struct {
   995  	Name  string
   996  	Email string
   997  }
   998  
   999  func newPodMetadata(env build.Environment, archive string) podMetadata {
  1000  	// Collect the list of authors from the repo root
  1001  	contribs := []podContributor{}
  1002  	if authors, err := os.Open("AUTHORS"); err == nil {
  1003  		defer authors.Close()
  1004  
  1005  		scanner := bufio.NewScanner(authors)
  1006  		for scanner.Scan() {
  1007  			// Skip any whitespace from the authors list
  1008  			line := strings.TrimSpace(scanner.Text())
  1009  			if line == "" || line[0] == '#' {
  1010  				continue
  1011  			}
  1012  			// Split the author and insert as a contributor
  1013  			re := regexp.MustCompile("([^<]+) <(.+)>")
  1014  			parts := re.FindStringSubmatch(line)
  1015  			if len(parts) == 3 {
  1016  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  1017  			}
  1018  		}
  1019  	}
  1020  	version := params.Version
  1021  	if isUnstableBuild(env) {
  1022  		version += "-unstable." + env.Buildnum
  1023  	}
  1024  	return podMetadata{
  1025  		Archive:      archive,
  1026  		Version:      version,
  1027  		Commit:       env.Commit,
  1028  		Contributors: contribs,
  1029  	}
  1030  }
  1031  
  1032  // Cross compilation
  1033  
  1034  func doXgo(cmdline []string) {
  1035  	var (
  1036  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1037  	)
  1038  	flag.CommandLine.Parse(cmdline)
  1039  	env := build.Env()
  1040  
  1041  	// Make sure xgo is available for cross compilation
  1042  	gogetxgo := goTool("get", "github.com/karalabe/xgo")
  1043  	build.MustRun(gogetxgo)
  1044  
  1045  	// If all tools building is requested, build everything the builder wants
  1046  	args := append(buildFlags(env), flag.Args()...)
  1047  
  1048  	if *alltools {
  1049  		args = append(args, []string{"--dest", GOBIN}...)
  1050  		for _, res := range allToolsArchiveFiles {
  1051  			if strings.HasPrefix(res, GOBIN) {
  1052  				// Binary tool found, cross build it explicitly
  1053  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1054  				xgo := xgoTool(args)
  1055  				build.MustRun(xgo)
  1056  				args = args[:len(args)-1]
  1057  			}
  1058  		}
  1059  		return
  1060  	}
  1061  	// Otherwise xxecute the explicit cross compilation
  1062  	path := args[len(args)-1]
  1063  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1064  
  1065  	xgo := xgoTool(args)
  1066  	build.MustRun(xgo)
  1067  }
  1068  
  1069  func xgoTool(args []string) *exec.Cmd {
  1070  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1071  	cmd.Env = os.Environ()
  1072  	cmd.Env = append(cmd.Env, []string{
  1073  		"GOBIN=" + GOBIN,
  1074  	}...)
  1075  	return cmd
  1076  }
  1077  
  1078  // Binary distribution cleanups
  1079  
  1080  func doPurge(cmdline []string) {
  1081  	var (
  1082  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1083  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1084  	)
  1085  	flag.CommandLine.Parse(cmdline)
  1086  
  1087  	if env := build.Env(); !env.IsCronJob {
  1088  		log.Printf("skipping because not a cron job")
  1089  		os.Exit(0)
  1090  	}
  1091  	// Create the azure authentication and list the current archives
  1092  	auth := build.AzureBlobstoreConfig{
  1093  		Account:   strings.Split(*store, "/")[0],
  1094  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1095  		Container: strings.SplitN(*store, "/", 2)[1],
  1096  	}
  1097  	blobs, err := build.AzureBlobstoreList(auth)
  1098  	if err != nil {
  1099  		log.Fatal(err)
  1100  	}
  1101  	// Iterate over the blobs, collect and sort all unstable builds
  1102  	for i := 0; i < len(blobs); i++ {
  1103  		if !strings.Contains(blobs[i].Name, "unstable") {
  1104  			blobs = append(blobs[:i], blobs[i+1:]...)
  1105  			i--
  1106  		}
  1107  	}
  1108  	for i := 0; i < len(blobs); i++ {
  1109  		for j := i + 1; j < len(blobs); j++ {
  1110  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1111  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1112  			}
  1113  		}
  1114  	}
  1115  	// Filter out all archives more recent that the given threshold
  1116  	for i, blob := range blobs {
  1117  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1118  			blobs = blobs[:i]
  1119  			break
  1120  		}
  1121  	}
  1122  	// Delete all marked as such and return
  1123  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1124  		log.Fatal(err)
  1125  	}
  1126  }