github.com/ethereum/go-ethereum@v1.10.9/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 ] [ -signify 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  	"io/ioutil"
    50  	"log"
    51  	"os"
    52  	"os/exec"
    53  	"path"
    54  	"path/filepath"
    55  	"regexp"
    56  	"runtime"
    57  	"strconv"
    58  	"strings"
    59  	"time"
    60  
    61  	"github.com/cespare/cp"
    62  	"github.com/ethereum/go-ethereum/crypto/signify"
    63  	"github.com/ethereum/go-ethereum/internal/build"
    64  	"github.com/ethereum/go-ethereum/params"
    65  )
    66  
    67  var (
    68  	// Files that end up in the geth*.zip archive.
    69  	gethArchiveFiles = []string{
    70  		"COPYING",
    71  		executablePath("geth"),
    72  	}
    73  
    74  	// Files that end up in the geth-alltools*.zip archive.
    75  	allToolsArchiveFiles = []string{
    76  		"COPYING",
    77  		executablePath("abigen"),
    78  		executablePath("bootnode"),
    79  		executablePath("evm"),
    80  		executablePath("geth"),
    81  		executablePath("puppeth"),
    82  		executablePath("rlpdump"),
    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:  "clef",
   114  			Description: "Ethereum account management tool.",
   115  		},
   116  	}
   117  
   118  	// A debian package is created for all executables listed here.
   119  	debEthereum = debPackage{
   120  		Name:        "ethereum",
   121  		Version:     params.Version,
   122  		Executables: debExecutables,
   123  	}
   124  
   125  	// Debian meta packages to build and push to Ubuntu PPA
   126  	debPackages = []debPackage{
   127  		debEthereum,
   128  	}
   129  
   130  	// Distros for which packages are created.
   131  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   132  	// Note: the following Ubuntu releases have been officially deprecated on Launchpad:
   133  	//   wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy
   134  	debDistroGoBoots = map[string]string{
   135  		"trusty":  "golang-1.11",
   136  		"xenial":  "golang-go",
   137  		"bionic":  "golang-go",
   138  		"focal":   "golang-go",
   139  		"hirsute": "golang-go",
   140  	}
   141  
   142  	debGoBootPaths = map[string]string{
   143  		"golang-1.11": "/usr/lib/go-1.11",
   144  		"golang-go":   "/usr/lib/go",
   145  	}
   146  
   147  	// This is the version of go that will be downloaded by
   148  	//
   149  	//     go run ci.go install -dlgo
   150  	dlgoVersion = "1.17"
   151  )
   152  
   153  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   154  
   155  func executablePath(name string) string {
   156  	if runtime.GOOS == "windows" {
   157  		name += ".exe"
   158  	}
   159  	return filepath.Join(GOBIN, name)
   160  }
   161  
   162  func main() {
   163  	log.SetFlags(log.Lshortfile)
   164  
   165  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   166  		log.Fatal("this script must be run from the root of the repository")
   167  	}
   168  	if len(os.Args) < 2 {
   169  		log.Fatal("need subcommand as first argument")
   170  	}
   171  	switch os.Args[1] {
   172  	case "install":
   173  		doInstall(os.Args[2:])
   174  	case "test":
   175  		doTest(os.Args[2:])
   176  	case "lint":
   177  		doLint(os.Args[2:])
   178  	case "archive":
   179  		doArchive(os.Args[2:])
   180  	case "docker":
   181  		doDocker(os.Args[2:])
   182  	case "debsrc":
   183  		doDebianSource(os.Args[2:])
   184  	case "nsis":
   185  		doWindowsInstaller(os.Args[2:])
   186  	case "aar":
   187  		doAndroidArchive(os.Args[2:])
   188  	case "xcode":
   189  		doXCodeFramework(os.Args[2:])
   190  	case "xgo":
   191  		doXgo(os.Args[2:])
   192  	case "purge":
   193  		doPurge(os.Args[2:])
   194  	default:
   195  		log.Fatal("unknown command ", os.Args[1])
   196  	}
   197  }
   198  
   199  // Compiling
   200  
   201  func doInstall(cmdline []string) {
   202  	var (
   203  		dlgo = flag.Bool("dlgo", false, "Download Go and build with it")
   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  
   209  	// Configure the toolchain.
   210  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   211  	if *dlgo {
   212  		csdb := build.MustLoadChecksums("build/checksums.txt")
   213  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   214  	}
   215  
   216  	// Configure the build.
   217  	env := build.Env()
   218  	gobuild := tc.Go("build", buildFlags(env)...)
   219  
   220  	// arm64 CI builders are memory-constrained and can't handle concurrent builds,
   221  	// better disable it. This check isn't the best, it should probably
   222  	// check for something in env instead.
   223  	if env.CI && runtime.GOARCH == "arm64" {
   224  		gobuild.Args = append(gobuild.Args, "-p", "1")
   225  	}
   226  
   227  	// We use -trimpath to avoid leaking local paths into the built executables.
   228  	gobuild.Args = append(gobuild.Args, "-trimpath")
   229  
   230  	// Show packages during build.
   231  	gobuild.Args = append(gobuild.Args, "-v")
   232  
   233  	// Now we choose what we're even building.
   234  	// Default: collect all 'main' packages in cmd/ and build those.
   235  	packages := flag.Args()
   236  	if len(packages) == 0 {
   237  		packages = build.FindMainPackages("./cmd")
   238  	}
   239  
   240  	// Do the build!
   241  	for _, pkg := range packages {
   242  		args := make([]string, len(gobuild.Args))
   243  		copy(args, gobuild.Args)
   244  		args = append(args, "-o", executablePath(path.Base(pkg)))
   245  		args = append(args, pkg)
   246  		build.MustRun(&exec.Cmd{Path: gobuild.Path, Args: args, Env: gobuild.Env})
   247  	}
   248  }
   249  
   250  // buildFlags returns the go tool flags for building.
   251  func buildFlags(env build.Environment) (flags []string) {
   252  	var ld []string
   253  	if env.Commit != "" {
   254  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   255  		ld = append(ld, "-X", "main.gitDate="+env.Date)
   256  	}
   257  	// Strip DWARF on darwin. This used to be required for certain things,
   258  	// and there is no downside to this, so we just keep doing it.
   259  	if runtime.GOOS == "darwin" {
   260  		ld = append(ld, "-s")
   261  	}
   262  	if len(ld) > 0 {
   263  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   264  	}
   265  	return flags
   266  }
   267  
   268  // Running The Tests
   269  //
   270  // "tests" also includes static analysis tools such as vet.
   271  
   272  func doTest(cmdline []string) {
   273  	var (
   274  		dlgo     = flag.Bool("dlgo", false, "Download Go and build with it")
   275  		arch     = flag.String("arch", "", "Run tests for given architecture")
   276  		cc       = flag.String("cc", "", "Sets C compiler binary")
   277  		coverage = flag.Bool("coverage", false, "Whether to record code coverage")
   278  		verbose  = flag.Bool("v", false, "Whether to log verbosely")
   279  	)
   280  	flag.CommandLine.Parse(cmdline)
   281  
   282  	// Configure the toolchain.
   283  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   284  	if *dlgo {
   285  		csdb := build.MustLoadChecksums("build/checksums.txt")
   286  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   287  	}
   288  	gotest := tc.Go("test")
   289  
   290  	// Test a single package at a time. CI builders are slow
   291  	// and some tests run into timeouts under load.
   292  	gotest.Args = append(gotest.Args, "-p", "1")
   293  	if *coverage {
   294  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   295  	}
   296  	if *verbose {
   297  		gotest.Args = append(gotest.Args, "-v")
   298  	}
   299  
   300  	packages := []string{"./..."}
   301  	if len(flag.CommandLine.Args()) > 0 {
   302  		packages = flag.CommandLine.Args()
   303  	}
   304  	gotest.Args = append(gotest.Args, packages...)
   305  	build.MustRun(gotest)
   306  }
   307  
   308  // doLint runs golangci-lint on requested packages.
   309  func doLint(cmdline []string) {
   310  	var (
   311  		cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
   312  	)
   313  	flag.CommandLine.Parse(cmdline)
   314  	packages := []string{"./..."}
   315  	if len(flag.CommandLine.Args()) > 0 {
   316  		packages = flag.CommandLine.Args()
   317  	}
   318  
   319  	linter := downloadLinter(*cachedir)
   320  	lflags := []string{"run", "--config", ".golangci.yml"}
   321  	build.MustRunCommand(linter, append(lflags, packages...)...)
   322  	fmt.Println("You have achieved perfection.")
   323  }
   324  
   325  // downloadLinter downloads and unpacks golangci-lint.
   326  func downloadLinter(cachedir string) string {
   327  	const version = "1.42.0"
   328  
   329  	csdb := build.MustLoadChecksums("build/checksums.txt")
   330  	base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
   331  	url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
   332  	archivePath := filepath.Join(cachedir, base+".tar.gz")
   333  	if err := csdb.DownloadFile(url, archivePath); err != nil {
   334  		log.Fatal(err)
   335  	}
   336  	if err := build.ExtractArchive(archivePath, cachedir); err != nil {
   337  		log.Fatal(err)
   338  	}
   339  	return filepath.Join(cachedir, base, "golangci-lint")
   340  }
   341  
   342  // Release Packaging
   343  func doArchive(cmdline []string) {
   344  	var (
   345  		arch    = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   346  		atype   = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   347  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   348  		signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`)
   349  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   350  		ext     string
   351  	)
   352  	flag.CommandLine.Parse(cmdline)
   353  	switch *atype {
   354  	case "zip":
   355  		ext = ".zip"
   356  	case "tar":
   357  		ext = ".tar.gz"
   358  	default:
   359  		log.Fatal("unknown archive type: ", atype)
   360  	}
   361  
   362  	var (
   363  		env      = build.Env()
   364  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   365  		geth     = "geth-" + basegeth + ext
   366  		alltools = "geth-alltools-" + basegeth + ext
   367  	)
   368  	maybeSkipArchive(env)
   369  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   370  		log.Fatal(err)
   371  	}
   372  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   373  		log.Fatal(err)
   374  	}
   375  	for _, archive := range []string{geth, alltools} {
   376  		if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
   377  			log.Fatal(err)
   378  		}
   379  	}
   380  }
   381  
   382  func archiveBasename(arch string, archiveVersion string) string {
   383  	platform := runtime.GOOS + "-" + arch
   384  	if arch == "arm" {
   385  		platform += os.Getenv("GOARM")
   386  	}
   387  	if arch == "android" {
   388  		platform = "android-all"
   389  	}
   390  	if arch == "ios" {
   391  		platform = "ios-all"
   392  	}
   393  	return platform + "-" + archiveVersion
   394  }
   395  
   396  func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error {
   397  	// If signing was requested, generate the signature files
   398  	if signer != "" {
   399  		key := getenvBase64(signer)
   400  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   401  			return err
   402  		}
   403  	}
   404  	if signifyVar != "" {
   405  		key := os.Getenv(signifyVar)
   406  		untrustedComment := "verify with geth-release.pub"
   407  		trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
   408  		if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
   409  			return err
   410  		}
   411  	}
   412  	// If uploading to Azure was requested, push the archive possibly with its signature
   413  	if blobstore != "" {
   414  		auth := build.AzureBlobstoreConfig{
   415  			Account:   strings.Split(blobstore, "/")[0],
   416  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   417  			Container: strings.SplitN(blobstore, "/", 2)[1],
   418  		}
   419  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   420  			return err
   421  		}
   422  		if signer != "" {
   423  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   424  				return err
   425  			}
   426  		}
   427  		if signifyVar != "" {
   428  			if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
   429  				return err
   430  			}
   431  		}
   432  	}
   433  	return nil
   434  }
   435  
   436  // skips archiving for some build configurations.
   437  func maybeSkipArchive(env build.Environment) {
   438  	if env.IsPullRequest {
   439  		log.Printf("skipping archive creation because this is a PR build")
   440  		os.Exit(0)
   441  	}
   442  	if env.IsCronJob {
   443  		log.Printf("skipping archive creation because this is a cron job")
   444  		os.Exit(0)
   445  	}
   446  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   447  		log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
   448  		os.Exit(0)
   449  	}
   450  }
   451  
   452  // Builds the docker images and optionally uploads them to Docker Hub.
   453  func doDocker(cmdline []string) {
   454  	var (
   455  		image    = flag.Bool("image", false, `Whether to build and push an arch specific docker image`)
   456  		manifest = flag.String("manifest", "", `Push a multi-arch docker image for the specified architectures (usually "amd64,arm64")`)
   457  		upload   = flag.String("upload", "", `Where to upload the docker image (usually "ethereum/client-go")`)
   458  	)
   459  	flag.CommandLine.Parse(cmdline)
   460  
   461  	// Skip building and pushing docker images for PR builds
   462  	env := build.Env()
   463  	maybeSkipArchive(env)
   464  
   465  	// Retrieve the upload credentials and authenticate
   466  	user := getenvBase64("DOCKER_HUB_USERNAME")
   467  	pass := getenvBase64("DOCKER_HUB_PASSWORD")
   468  
   469  	if len(user) > 0 && len(pass) > 0 {
   470  		auther := exec.Command("docker", "login", "-u", string(user), "--password-stdin")
   471  		auther.Stdin = bytes.NewReader(pass)
   472  		build.MustRun(auther)
   473  	}
   474  	// Retrieve the version infos to build and push to the following paths:
   475  	//  - ethereum/client-go:latest                            - Pushes to the master branch, Geth only
   476  	//  - ethereum/client-go:stable                            - Version tag publish on GitHub, Geth only
   477  	//  - ethereum/client-go:alltools-latest                   - Pushes to the master branch, Geth & tools
   478  	//  - ethereum/client-go:alltools-stable                   - Version tag publish on GitHub, Geth & tools
   479  	//  - ethereum/client-go:release-<major>.<minor>           - Version tag publish on GitHub, Geth only
   480  	//  - ethereum/client-go:alltools-release-<major>.<minor>  - Version tag publish on GitHub, Geth & tools
   481  	//  - ethereum/client-go:v<major>.<minor>.<patch>          - Version tag publish on GitHub, Geth only
   482  	//  - ethereum/client-go:alltools-v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth & tools
   483  	var tags []string
   484  
   485  	switch {
   486  	case env.Branch == "master":
   487  		tags = []string{"latest"}
   488  	case strings.HasPrefix(env.Tag, "v1."):
   489  		tags = []string{"stable", fmt.Sprintf("release-1.%d", params.VersionMinor), "v" + params.Version}
   490  	}
   491  	// If architecture specific image builds are requested, build and push them
   492  	if *image {
   493  		build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:TAG", *upload), ".")
   494  		build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:alltools-TAG", *upload), "-f", "Dockerfile.alltools", ".")
   495  
   496  		// Tag and upload the images to Docker Hub
   497  		for _, tag := range tags {
   498  			gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, runtime.GOARCH)
   499  			toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, runtime.GOARCH)
   500  
   501  			// If the image already exists (non version tag), check the build
   502  			// number to prevent overwriting a newer commit if concurrent builds
   503  			// are running. This is still a tiny bit racey if two published are
   504  			// done at the same time, but that's extremely unlikely even on the
   505  			// master branch.
   506  			for _, img := range []string{gethImage, toolImage} {
   507  				if exec.Command("docker", "pull", img).Run() != nil {
   508  					continue // Generally the only failure is a missing image, which is good
   509  				}
   510  				buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   511  				if err != nil {
   512  					log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   513  				}
   514  				buildnum = bytes.TrimSpace(buildnum)
   515  
   516  				if len(buildnum) > 0 && len(env.Buildnum) > 0 {
   517  					oldnum, err := strconv.Atoi(string(buildnum))
   518  					if err != nil {
   519  						log.Fatalf("Failed to parse old image build number: %v", err)
   520  					}
   521  					newnum, err := strconv.Atoi(env.Buildnum)
   522  					if err != nil {
   523  						log.Fatalf("Failed to parse current build number: %v", err)
   524  					}
   525  					if oldnum > newnum {
   526  						log.Fatalf("Current build number %d not newer than existing %d", newnum, oldnum)
   527  					} else {
   528  						log.Printf("Updating %s from build %d to %d", img, oldnum, newnum)
   529  					}
   530  				}
   531  			}
   532  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:TAG", *upload), gethImage)
   533  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:alltools-TAG", *upload), toolImage)
   534  			build.MustRunCommand("docker", "push", gethImage)
   535  			build.MustRunCommand("docker", "push", toolImage)
   536  		}
   537  	}
   538  	// If multi-arch image manifest push is requested, assemble it
   539  	if len(*manifest) != 0 {
   540  		// Since different architectures are pushed by different builders, wait
   541  		// until all required images are updated.
   542  		var mismatch bool
   543  		for i := 0; i < 2; i++ { // 2 attempts, second is race check
   544  			mismatch = false // hope there's no mismatch now
   545  
   546  			for _, tag := range tags {
   547  				for _, arch := range strings.Split(*manifest, ",") {
   548  					gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, arch)
   549  					toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, arch)
   550  
   551  					for _, img := range []string{gethImage, toolImage} {
   552  						if out, err := exec.Command("docker", "pull", img).CombinedOutput(); err != nil {
   553  							log.Printf("Required image %s unavailable: %v\nOutput: %s", img, err, out)
   554  							mismatch = true
   555  							break
   556  						}
   557  						buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   558  						if err != nil {
   559  							log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   560  						}
   561  						buildnum = bytes.TrimSpace(buildnum)
   562  
   563  						if string(buildnum) != env.Buildnum {
   564  							log.Printf("Build number mismatch on %s: want %s, have %s", img, env.Buildnum, buildnum)
   565  							mismatch = true
   566  							break
   567  						}
   568  					}
   569  					if mismatch {
   570  						break
   571  					}
   572  				}
   573  				if mismatch {
   574  					break
   575  				}
   576  			}
   577  			if mismatch {
   578  				// Build numbers mismatching, retry in a short time to
   579  				// avoid concurrent failes in both publisher images. If
   580  				// however the retry failed too, it means the concurrent
   581  				// builder is still crunching, let that do the publish.
   582  				if i == 0 {
   583  					time.Sleep(30 * time.Second)
   584  				}
   585  				continue
   586  			}
   587  			break
   588  		}
   589  		if mismatch {
   590  			log.Println("Relinquishing publish to other builder")
   591  			return
   592  		}
   593  		// Assemble and push the Geth manifest image
   594  		for _, tag := range tags {
   595  			gethImage := fmt.Sprintf("%s:%s", *upload, tag)
   596  
   597  			var gethSubImages []string
   598  			for _, arch := range strings.Split(*manifest, ",") {
   599  				gethSubImages = append(gethSubImages, gethImage+"-"+arch)
   600  			}
   601  			build.MustRunCommand("docker", append([]string{"manifest", "create", gethImage}, gethSubImages...)...)
   602  			build.MustRunCommand("docker", "manifest", "push", gethImage)
   603  		}
   604  		// Assemble and push the alltools manifest image
   605  		for _, tag := range tags {
   606  			toolImage := fmt.Sprintf("%s:alltools-%s", *upload, tag)
   607  
   608  			var toolSubImages []string
   609  			for _, arch := range strings.Split(*manifest, ",") {
   610  				toolSubImages = append(toolSubImages, toolImage+"-"+arch)
   611  			}
   612  			build.MustRunCommand("docker", append([]string{"manifest", "create", toolImage}, toolSubImages...)...)
   613  			build.MustRunCommand("docker", "manifest", "push", toolImage)
   614  		}
   615  	}
   616  }
   617  
   618  // Debian Packaging
   619  func doDebianSource(cmdline []string) {
   620  	var (
   621  		cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
   622  		signer   = flag.String("signer", "", `Signing key name, also used as package author`)
   623  		upload   = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   624  		sshUser  = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   625  		workdir  = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   626  		now      = time.Now()
   627  	)
   628  	flag.CommandLine.Parse(cmdline)
   629  	*workdir = makeWorkdir(*workdir)
   630  	env := build.Env()
   631  	tc := new(build.GoToolchain)
   632  	maybeSkipArchive(env)
   633  
   634  	// Import the signing key.
   635  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   636  		gpg := exec.Command("gpg", "--import")
   637  		gpg.Stdin = bytes.NewReader(key)
   638  		build.MustRun(gpg)
   639  	}
   640  
   641  	// Download and verify the Go source package.
   642  	gobundle := downloadGoSources(*cachedir)
   643  
   644  	// Download all the dependencies needed to build the sources and run the ci script
   645  	srcdepfetch := tc.Go("mod", "download")
   646  	srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   647  	build.MustRun(srcdepfetch)
   648  
   649  	cidepfetch := tc.Go("run", "./build/ci.go")
   650  	cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   651  	cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
   652  
   653  	// Create Debian packages and upload them.
   654  	for _, pkg := range debPackages {
   655  		for distro, goboot := range debDistroGoBoots {
   656  			// Prepare the debian package with the go-ethereum sources.
   657  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   658  			pkgdir := stageDebianSource(*workdir, meta)
   659  
   660  			// Add Go source code
   661  			if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
   662  				log.Fatalf("Failed to extract Go sources: %v", err)
   663  			}
   664  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   665  				log.Fatalf("Failed to rename Go source folder: %v", err)
   666  			}
   667  			// Add all dependency modules in compressed form
   668  			os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
   669  			if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
   670  				log.Fatalf("Failed to copy Go module dependencies: %v", err)
   671  			}
   672  			// Run the packaging and upload to the PPA
   673  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
   674  			debuild.Dir = pkgdir
   675  			build.MustRun(debuild)
   676  
   677  			var (
   678  				basename  = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   679  				source    = filepath.Join(*workdir, basename+".tar.xz")
   680  				dsc       = filepath.Join(*workdir, basename+".dsc")
   681  				changes   = filepath.Join(*workdir, basename+"_source.changes")
   682  				buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
   683  			)
   684  			if *signer != "" {
   685  				build.MustRunCommand("debsign", changes)
   686  			}
   687  			if *upload != "" {
   688  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
   689  			}
   690  		}
   691  	}
   692  }
   693  
   694  // downloadGoSources downloads the Go source tarball.
   695  func downloadGoSources(cachedir string) string {
   696  	csdb := build.MustLoadChecksums("build/checksums.txt")
   697  	file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
   698  	url := "https://dl.google.com/go/" + file
   699  	dst := filepath.Join(cachedir, file)
   700  	if err := csdb.DownloadFile(url, dst); err != nil {
   701  		log.Fatal(err)
   702  	}
   703  	return dst
   704  }
   705  
   706  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   707  	p := strings.Split(ppa, "/")
   708  	if len(p) != 2 {
   709  		log.Fatal("-upload PPA name must contain single /")
   710  	}
   711  	if sshUser == "" {
   712  		sshUser = p[0]
   713  	}
   714  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   715  	// Create the SSH identity file if it doesn't exist.
   716  	var idfile string
   717  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   718  		idfile = filepath.Join(workdir, "sshkey")
   719  		if _, err := os.Stat(idfile); os.IsNotExist(err) {
   720  			ioutil.WriteFile(idfile, sshkey, 0600)
   721  		}
   722  	}
   723  	// Upload
   724  	dest := sshUser + "@ppa.launchpad.net"
   725  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   726  		log.Fatal(err)
   727  	}
   728  }
   729  
   730  func getenvBase64(variable string) []byte {
   731  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   732  	if err != nil {
   733  		log.Fatal("invalid base64 " + variable)
   734  	}
   735  	return []byte(dec)
   736  }
   737  
   738  func makeWorkdir(wdflag string) string {
   739  	var err error
   740  	if wdflag != "" {
   741  		err = os.MkdirAll(wdflag, 0744)
   742  	} else {
   743  		wdflag, err = ioutil.TempDir("", "geth-build-")
   744  	}
   745  	if err != nil {
   746  		log.Fatal(err)
   747  	}
   748  	return wdflag
   749  }
   750  
   751  func isUnstableBuild(env build.Environment) bool {
   752  	if env.Tag != "" {
   753  		return false
   754  	}
   755  	return true
   756  }
   757  
   758  type debPackage struct {
   759  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   760  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   761  	Executables []debExecutable // executables to be included in the package
   762  }
   763  
   764  type debMetadata struct {
   765  	Env           build.Environment
   766  	GoBootPackage string
   767  	GoBootPath    string
   768  
   769  	PackageName string
   770  
   771  	// go-ethereum version being built. Note that this
   772  	// is not the debian package version. The package version
   773  	// is constructed by VersionString.
   774  	Version string
   775  
   776  	Author       string // "name <email>", also selects signing key
   777  	Distro, Time string
   778  	Executables  []debExecutable
   779  }
   780  
   781  type debExecutable struct {
   782  	PackageName string
   783  	BinaryName  string
   784  	Description string
   785  }
   786  
   787  // Package returns the name of the package if present, or
   788  // fallbacks to BinaryName
   789  func (d debExecutable) Package() string {
   790  	if d.PackageName != "" {
   791  		return d.PackageName
   792  	}
   793  	return d.BinaryName
   794  }
   795  
   796  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   797  	if author == "" {
   798  		// No signing key, use default author.
   799  		author = "Ethereum Builds <fjl@ethereum.org>"
   800  	}
   801  	return debMetadata{
   802  		GoBootPackage: goboot,
   803  		GoBootPath:    debGoBootPaths[goboot],
   804  		PackageName:   name,
   805  		Env:           env,
   806  		Author:        author,
   807  		Distro:        distro,
   808  		Version:       version,
   809  		Time:          t.Format(time.RFC1123Z),
   810  		Executables:   exes,
   811  	}
   812  }
   813  
   814  // Name returns the name of the metapackage that depends
   815  // on all executable packages.
   816  func (meta debMetadata) Name() string {
   817  	if isUnstableBuild(meta.Env) {
   818  		return meta.PackageName + "-unstable"
   819  	}
   820  	return meta.PackageName
   821  }
   822  
   823  // VersionString returns the debian version of the packages.
   824  func (meta debMetadata) VersionString() string {
   825  	vsn := meta.Version
   826  	if meta.Env.Buildnum != "" {
   827  		vsn += "+build" + meta.Env.Buildnum
   828  	}
   829  	if meta.Distro != "" {
   830  		vsn += "+" + meta.Distro
   831  	}
   832  	return vsn
   833  }
   834  
   835  // ExeList returns the list of all executable packages.
   836  func (meta debMetadata) ExeList() string {
   837  	names := make([]string, len(meta.Executables))
   838  	for i, e := range meta.Executables {
   839  		names[i] = meta.ExeName(e)
   840  	}
   841  	return strings.Join(names, ", ")
   842  }
   843  
   844  // ExeName returns the package name of an executable package.
   845  func (meta debMetadata) ExeName(exe debExecutable) string {
   846  	if isUnstableBuild(meta.Env) {
   847  		return exe.Package() + "-unstable"
   848  	}
   849  	return exe.Package()
   850  }
   851  
   852  // ExeConflicts returns the content of the Conflicts field
   853  // for executable packages.
   854  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   855  	if isUnstableBuild(meta.Env) {
   856  		// Set up the conflicts list so that the *-unstable packages
   857  		// cannot be installed alongside the regular version.
   858  		//
   859  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   860  		// is very explicit about Conflicts: and says that Breaks: should
   861  		// be preferred and the conflicting files should be handled via
   862  		// alternates. We might do this eventually but using a conflict is
   863  		// easier now.
   864  		return "ethereum, " + exe.Package()
   865  	}
   866  	return ""
   867  }
   868  
   869  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   870  	pkg := meta.Name() + "-" + meta.VersionString()
   871  	pkgdir = filepath.Join(tmpdir, pkg)
   872  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   873  		log.Fatal(err)
   874  	}
   875  	// Copy the source code.
   876  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   877  
   878  	// Put the debian build files in place.
   879  	debian := filepath.Join(pkgdir, "debian")
   880  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   881  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   882  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   883  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   884  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   885  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   886  	for _, exe := range meta.Executables {
   887  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   888  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   889  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   890  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   891  	}
   892  	return pkgdir
   893  }
   894  
   895  // Windows installer
   896  func doWindowsInstaller(cmdline []string) {
   897  	// Parse the flags and make skip installer generation on PRs
   898  	var (
   899  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   900  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   901  		signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
   902  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   903  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   904  	)
   905  	flag.CommandLine.Parse(cmdline)
   906  	*workdir = makeWorkdir(*workdir)
   907  	env := build.Env()
   908  	maybeSkipArchive(env)
   909  
   910  	// Aggregate binaries that are included in the installer
   911  	var (
   912  		devTools []string
   913  		allTools []string
   914  		gethTool string
   915  	)
   916  	for _, file := range allToolsArchiveFiles {
   917  		if file == "COPYING" { // license, copied later
   918  			continue
   919  		}
   920  		allTools = append(allTools, filepath.Base(file))
   921  		if filepath.Base(file) == "geth.exe" {
   922  			gethTool = file
   923  		} else {
   924  			devTools = append(devTools, file)
   925  		}
   926  	}
   927  
   928  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   929  	// first section contains the geth binary, second section holds the dev tools.
   930  	templateData := map[string]interface{}{
   931  		"License":  "COPYING",
   932  		"Geth":     gethTool,
   933  		"DevTools": devTools,
   934  	}
   935  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   936  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   937  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   938  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   939  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   940  	if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
   941  		log.Fatal("Failed to copy SimpleFC.dll: %v", err)
   942  	}
   943  	if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
   944  		log.Fatal("Failed to copy copyright note: %v", err)
   945  	}
   946  	// Build the installer. This assumes that all the needed files have been previously
   947  	// built (don't mix building and packaging to keep cross compilation complexity to a
   948  	// minimum).
   949  	version := strings.Split(params.Version, ".")
   950  	if env.Commit != "" {
   951  		version[2] += "-" + env.Commit[:8]
   952  	}
   953  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   954  	build.MustRunCommand("makensis.exe",
   955  		"/DOUTPUTFILE="+installer,
   956  		"/DMAJORVERSION="+version[0],
   957  		"/DMINORVERSION="+version[1],
   958  		"/DBUILDVERSION="+version[2],
   959  		"/DARCH="+*arch,
   960  		filepath.Join(*workdir, "geth.nsi"),
   961  	)
   962  	// Sign and publish installer.
   963  	if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
   964  		log.Fatal(err)
   965  	}
   966  }
   967  
   968  // Android archives
   969  
   970  func doAndroidArchive(cmdline []string) {
   971  	var (
   972  		local   = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   973  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   974  		signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`)
   975  		deploy  = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   976  		upload  = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   977  	)
   978  	flag.CommandLine.Parse(cmdline)
   979  	env := build.Env()
   980  	tc := new(build.GoToolchain)
   981  
   982  	// Sanity check that the SDK and NDK are installed and set
   983  	if os.Getenv("ANDROID_HOME") == "" {
   984  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   985  	}
   986  
   987  	// Build gomobile.
   988  	install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")
   989  	install.Env = append(install.Env)
   990  	build.MustRun(install)
   991  
   992  	// Ensure all dependencies are available. This is required to make
   993  	// gomobile bind work because it expects go.sum to contain all checksums.
   994  	build.MustRun(tc.Go("mod", "download"))
   995  
   996  	// Build the Android archive and Maven resources
   997  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
   998  
   999  	if *local {
  1000  		// If we're building locally, copy bundle to build dir and skip Maven
  1001  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  1002  		os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
  1003  		return
  1004  	}
  1005  	meta := newMavenMetadata(env)
  1006  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  1007  
  1008  	// Skip Maven deploy and Azure upload for PR builds
  1009  	maybeSkipArchive(env)
  1010  
  1011  	// Sign and upload the archive to Azure
  1012  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  1013  	os.Rename("geth.aar", archive)
  1014  
  1015  	if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  1016  		log.Fatal(err)
  1017  	}
  1018  	// Sign and upload all the artifacts to Maven Central
  1019  	os.Rename(archive, meta.Package+".aar")
  1020  	if *signer != "" && *deploy != "" {
  1021  		// Import the signing key into the local GPG instance
  1022  		key := getenvBase64(*signer)
  1023  		gpg := exec.Command("gpg", "--import")
  1024  		gpg.Stdin = bytes.NewReader(key)
  1025  		build.MustRun(gpg)
  1026  		keyID, err := build.PGPKeyID(string(key))
  1027  		if err != nil {
  1028  			log.Fatal(err)
  1029  		}
  1030  		// Upload the artifacts to Sonatype and/or Maven Central
  1031  		repo := *deploy + "/service/local/staging/deploy/maven2"
  1032  		if meta.Develop {
  1033  			repo = *deploy + "/content/repositories/snapshots"
  1034  		}
  1035  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  1036  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  1037  			"-Dgpg.keyname="+keyID,
  1038  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  1039  	}
  1040  }
  1041  
  1042  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  1043  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  1044  	cmd.Args = append(cmd.Args, args...)
  1045  	cmd.Env = []string{
  1046  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  1047  	}
  1048  	for _, e := range os.Environ() {
  1049  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
  1050  			continue
  1051  		}
  1052  		cmd.Env = append(cmd.Env, e)
  1053  	}
  1054  	cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  1055  	return cmd
  1056  }
  1057  
  1058  type mavenMetadata struct {
  1059  	Version      string
  1060  	Package      string
  1061  	Develop      bool
  1062  	Contributors []mavenContributor
  1063  }
  1064  
  1065  type mavenContributor struct {
  1066  	Name  string
  1067  	Email string
  1068  }
  1069  
  1070  func newMavenMetadata(env build.Environment) mavenMetadata {
  1071  	// Collect the list of authors from the repo root
  1072  	contribs := []mavenContributor{}
  1073  	if authors, err := os.Open("AUTHORS"); err == nil {
  1074  		defer authors.Close()
  1075  
  1076  		scanner := bufio.NewScanner(authors)
  1077  		for scanner.Scan() {
  1078  			// Skip any whitespace from the authors list
  1079  			line := strings.TrimSpace(scanner.Text())
  1080  			if line == "" || line[0] == '#' {
  1081  				continue
  1082  			}
  1083  			// Split the author and insert as a contributor
  1084  			re := regexp.MustCompile("([^<]+) <(.+)>")
  1085  			parts := re.FindStringSubmatch(line)
  1086  			if len(parts) == 3 {
  1087  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  1088  			}
  1089  		}
  1090  	}
  1091  	// Render the version and package strings
  1092  	version := params.Version
  1093  	if isUnstableBuild(env) {
  1094  		version += "-SNAPSHOT"
  1095  	}
  1096  	return mavenMetadata{
  1097  		Version:      version,
  1098  		Package:      "geth-" + version,
  1099  		Develop:      isUnstableBuild(env),
  1100  		Contributors: contribs,
  1101  	}
  1102  }
  1103  
  1104  // XCode frameworks
  1105  
  1106  func doXCodeFramework(cmdline []string) {
  1107  	var (
  1108  		local   = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  1109  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  1110  		signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`)
  1111  		deploy  = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  1112  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  1113  	)
  1114  	flag.CommandLine.Parse(cmdline)
  1115  	env := build.Env()
  1116  	tc := new(build.GoToolchain)
  1117  
  1118  	// Build gomobile.
  1119  	build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest"))
  1120  
  1121  	// Ensure all dependencies are available. This is required to make
  1122  	// gomobile bind work because it expects go.sum to contain all checksums.
  1123  	build.MustRun(tc.Go("mod", "download"))
  1124  
  1125  	// Build the iOS XCode framework
  1126  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  1127  
  1128  	if *local {
  1129  		// If we're building locally, use the build folder and stop afterwards
  1130  		bind.Dir = GOBIN
  1131  		build.MustRun(bind)
  1132  		return
  1133  	}
  1134  
  1135  	// Create the archive.
  1136  	maybeSkipArchive(env)
  1137  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  1138  	if err := os.MkdirAll(archive, 0755); err != nil {
  1139  		log.Fatal(err)
  1140  	}
  1141  	bind.Dir, _ = filepath.Abs(archive)
  1142  	build.MustRun(bind)
  1143  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  1144  
  1145  	// Sign and upload the framework to Azure
  1146  	if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
  1147  		log.Fatal(err)
  1148  	}
  1149  	// Prepare and upload a PodSpec to CocoaPods
  1150  	if *deploy != "" {
  1151  		meta := newPodMetadata(env, archive)
  1152  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  1153  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
  1154  	}
  1155  }
  1156  
  1157  type podMetadata struct {
  1158  	Version      string
  1159  	Commit       string
  1160  	Archive      string
  1161  	Contributors []podContributor
  1162  }
  1163  
  1164  type podContributor struct {
  1165  	Name  string
  1166  	Email string
  1167  }
  1168  
  1169  func newPodMetadata(env build.Environment, archive string) podMetadata {
  1170  	// Collect the list of authors from the repo root
  1171  	contribs := []podContributor{}
  1172  	if authors, err := os.Open("AUTHORS"); err == nil {
  1173  		defer authors.Close()
  1174  
  1175  		scanner := bufio.NewScanner(authors)
  1176  		for scanner.Scan() {
  1177  			// Skip any whitespace from the authors list
  1178  			line := strings.TrimSpace(scanner.Text())
  1179  			if line == "" || line[0] == '#' {
  1180  				continue
  1181  			}
  1182  			// Split the author and insert as a contributor
  1183  			re := regexp.MustCompile("([^<]+) <(.+)>")
  1184  			parts := re.FindStringSubmatch(line)
  1185  			if len(parts) == 3 {
  1186  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  1187  			}
  1188  		}
  1189  	}
  1190  	version := params.Version
  1191  	if isUnstableBuild(env) {
  1192  		version += "-unstable." + env.Buildnum
  1193  	}
  1194  	return podMetadata{
  1195  		Archive:      archive,
  1196  		Version:      version,
  1197  		Commit:       env.Commit,
  1198  		Contributors: contribs,
  1199  	}
  1200  }
  1201  
  1202  // Cross compilation
  1203  
  1204  func doXgo(cmdline []string) {
  1205  	var (
  1206  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1207  	)
  1208  	flag.CommandLine.Parse(cmdline)
  1209  	env := build.Env()
  1210  	var tc build.GoToolchain
  1211  
  1212  	// Make sure xgo is available for cross compilation
  1213  	build.MustRun(tc.Install(GOBIN, "github.com/karalabe/xgo@latest"))
  1214  
  1215  	// If all tools building is requested, build everything the builder wants
  1216  	args := append(buildFlags(env), flag.Args()...)
  1217  
  1218  	if *alltools {
  1219  		args = append(args, []string{"--dest", GOBIN}...)
  1220  		for _, res := range allToolsArchiveFiles {
  1221  			if strings.HasPrefix(res, GOBIN) {
  1222  				// Binary tool found, cross build it explicitly
  1223  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1224  				build.MustRun(xgoTool(args))
  1225  				args = args[:len(args)-1]
  1226  			}
  1227  		}
  1228  		return
  1229  	}
  1230  
  1231  	// Otherwise execute the explicit cross compilation
  1232  	path := args[len(args)-1]
  1233  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1234  	build.MustRun(xgoTool(args))
  1235  }
  1236  
  1237  func xgoTool(args []string) *exec.Cmd {
  1238  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1239  	cmd.Env = os.Environ()
  1240  	cmd.Env = append(cmd.Env, []string{"GOBIN=" + GOBIN}...)
  1241  	return cmd
  1242  }
  1243  
  1244  // Binary distribution cleanups
  1245  
  1246  func doPurge(cmdline []string) {
  1247  	var (
  1248  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1249  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1250  	)
  1251  	flag.CommandLine.Parse(cmdline)
  1252  
  1253  	if env := build.Env(); !env.IsCronJob {
  1254  		log.Printf("skipping because not a cron job")
  1255  		os.Exit(0)
  1256  	}
  1257  	// Create the azure authentication and list the current archives
  1258  	auth := build.AzureBlobstoreConfig{
  1259  		Account:   strings.Split(*store, "/")[0],
  1260  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1261  		Container: strings.SplitN(*store, "/", 2)[1],
  1262  	}
  1263  	blobs, err := build.AzureBlobstoreList(auth)
  1264  	if err != nil {
  1265  		log.Fatal(err)
  1266  	}
  1267  	fmt.Printf("Found %d blobs\n", len(blobs))
  1268  
  1269  	// Iterate over the blobs, collect and sort all unstable builds
  1270  	for i := 0; i < len(blobs); i++ {
  1271  		if !strings.Contains(blobs[i].Name, "unstable") {
  1272  			blobs = append(blobs[:i], blobs[i+1:]...)
  1273  			i--
  1274  		}
  1275  	}
  1276  	for i := 0; i < len(blobs); i++ {
  1277  		for j := i + 1; j < len(blobs); j++ {
  1278  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1279  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1280  			}
  1281  		}
  1282  	}
  1283  	// Filter out all archives more recent that the given threshold
  1284  	for i, blob := range blobs {
  1285  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1286  			blobs = blobs[:i]
  1287  			break
  1288  		}
  1289  	}
  1290  	fmt.Printf("Deleting %d blobs\n", len(blobs))
  1291  	// Delete all marked as such and return
  1292  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1293  		log.Fatal(err)
  1294  	}
  1295  }