github.com/calmw/ethereum@v0.1.1/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  //go:build none
    18  // +build none
    19  
    20  /*
    21  The ci command is called from Continuous Integration scripts.
    22  
    23  Usage: go run build/ci.go <command> <command flags/arguments>
    24  
    25  Available commands are:
    26  
    27  	install    [ -arch architecture ] [ -cc compiler ] [ packages... ]                          -- builds packages and executables
    28  	test       [ -coverage ] [ packages... ]                                                    -- runs the tests
    29  	lint                                                                                        -- runs certain pre-selected linters
    30  	archive    [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -signify key-envvar ] [ -upload dest ] -- archives build artifacts
    31  	importkeys                                                                                  -- imports signing keys from env
    32  	debsrc     [ -signer key-id ] [ -upload dest ]                                              -- creates a debian source package
    33  	nsis                                                                                        -- creates a Windows NSIS installer
    34  	purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
    35  
    36  For all commands, -n prevents execution of external programs (dry run mode).
    37  */
    38  package main
    39  
    40  import (
    41  	"bytes"
    42  	"encoding/base64"
    43  	"flag"
    44  	"fmt"
    45  	"log"
    46  	"os"
    47  	"os/exec"
    48  	"path"
    49  	"path/filepath"
    50  	"runtime"
    51  	"strconv"
    52  	"strings"
    53  	"time"
    54  
    55  	"github.com/calmw/ethereum/common"
    56  	"github.com/calmw/ethereum/crypto/signify"
    57  	"github.com/calmw/ethereum/internal/build"
    58  	"github.com/calmw/ethereum/params"
    59  	"github.com/cespare/cp"
    60  )
    61  
    62  var (
    63  	// Files that end up in the geth*.zip archive.
    64  	gethArchiveFiles = []string{
    65  		"COPYING",
    66  		executablePath("geth"),
    67  	}
    68  
    69  	// Files that end up in the geth-alltools*.zip archive.
    70  	allToolsArchiveFiles = []string{
    71  		"COPYING",
    72  		executablePath("abigen"),
    73  		executablePath("bootnode"),
    74  		executablePath("evm"),
    75  		executablePath("geth"),
    76  		executablePath("rlpdump"),
    77  		executablePath("clef"),
    78  	}
    79  
    80  	// A debian package is created for all executables listed here.
    81  	debExecutables = []debExecutable{
    82  		{
    83  			BinaryName:  "abigen",
    84  			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
    85  		},
    86  		{
    87  			BinaryName:  "bootnode",
    88  			Description: "Ethereum bootnode.",
    89  		},
    90  		{
    91  			BinaryName:  "evm",
    92  			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
    93  		},
    94  		{
    95  			BinaryName:  "geth",
    96  			Description: "Ethereum CLI client.",
    97  		},
    98  		{
    99  			BinaryName:  "rlpdump",
   100  			Description: "Developer utility tool that prints RLP structures.",
   101  		},
   102  		{
   103  			BinaryName:  "clef",
   104  			Description: "Ethereum account management tool.",
   105  		},
   106  	}
   107  
   108  	// A debian package is created for all executables listed here.
   109  	debEthereum = debPackage{
   110  		Name:        "ethereum",
   111  		Version:     params.Version,
   112  		Executables: debExecutables,
   113  	}
   114  
   115  	// Debian meta packages to build and push to Ubuntu PPA
   116  	debPackages = []debPackage{
   117  		debEthereum,
   118  	}
   119  
   120  	// Distros for which packages are created.
   121  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   122  	// Note: the following Ubuntu releases have been officially deprecated on Launchpad:
   123  	//   wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy, hirsuite, impish
   124  	debDistroGoBoots = map[string]string{
   125  		"trusty":  "golang-1.11", // EOL: 04/2024
   126  		"xenial":  "golang-go",   // EOL: 04/2026
   127  		"bionic":  "golang-go",   // EOL: 04/2028
   128  		"focal":   "golang-go",   // EOL: 04/2030
   129  		"jammy":   "golang-go",   // EOL: 04/2032
   130  		"kinetic": "golang-go",   // EOL: 07/2023
   131  		"lunar":   "golang-go",   // EOL: 01/2024
   132  	}
   133  
   134  	debGoBootPaths = map[string]string{
   135  		"golang-1.11": "/usr/lib/go-1.11",
   136  		"golang-go":   "/usr/lib/go",
   137  	}
   138  
   139  	// This is the version of Go that will be downloaded by
   140  	//
   141  	//     go run ci.go install -dlgo
   142  	dlgoVersion = "1.20.3"
   143  
   144  	// This is the version of Go that will be used to bootstrap the PPA builder.
   145  	//
   146  	// This version is fine to be old and full of security holes, we just use it
   147  	// to build the latest Go. Don't change it. If it ever becomes insufficient,
   148  	// we need to switch over to a recursive builder to jumpt across supported
   149  	// versions.
   150  	gobootVersion = "1.19.6"
   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 !common.FileExist(filepath.Join("build", "ci.go")) {
   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 "purge":
   187  		doPurge(os.Args[2:])
   188  	default:
   189  		log.Fatal("unknown command ", os.Args[1])
   190  	}
   191  }
   192  
   193  // Compiling
   194  
   195  func doInstall(cmdline []string) {
   196  	var (
   197  		dlgo       = flag.Bool("dlgo", false, "Download Go and build with it")
   198  		arch       = flag.String("arch", "", "Architecture to cross build for")
   199  		cc         = flag.String("cc", "", "C compiler to cross build with")
   200  		staticlink = flag.Bool("static", false, "Create statically-linked executable")
   201  	)
   202  	flag.CommandLine.Parse(cmdline)
   203  
   204  	// Configure the toolchain.
   205  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   206  	if *dlgo {
   207  		csdb := build.MustLoadChecksums("build/checksums.txt")
   208  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   209  	}
   210  	// Disable CLI markdown doc generation in release builds and enable linking
   211  	// the CKZG library since we can make it portable here.
   212  	buildTags := []string{"urfave_cli_no_docs", "ckzg"}
   213  
   214  	// Configure the build.
   215  	env := build.Env()
   216  	gobuild := tc.Go("build", buildFlags(env, *staticlink, buildTags)...)
   217  
   218  	// arm64 CI builders are memory-constrained and can't handle concurrent builds,
   219  	// better disable it. This check isn't the best, it should probably
   220  	// check for something in env instead.
   221  	if env.CI && runtime.GOARCH == "arm64" {
   222  		gobuild.Args = append(gobuild.Args, "-p", "1")
   223  	}
   224  	// We use -trimpath to avoid leaking local paths into the built executables.
   225  	gobuild.Args = append(gobuild.Args, "-trimpath")
   226  
   227  	// Show packages during build.
   228  	gobuild.Args = append(gobuild.Args, "-v")
   229  
   230  	// Now we choose what we're even building.
   231  	// Default: collect all 'main' packages in cmd/ and build those.
   232  	packages := flag.Args()
   233  	if len(packages) == 0 {
   234  		packages = build.FindMainPackages("./cmd")
   235  	}
   236  
   237  	// Do the build!
   238  	for _, pkg := range packages {
   239  		args := make([]string, len(gobuild.Args))
   240  		copy(args, gobuild.Args)
   241  		args = append(args, "-o", executablePath(path.Base(pkg)))
   242  		args = append(args, pkg)
   243  		build.MustRun(&exec.Cmd{Path: gobuild.Path, Args: args, Env: gobuild.Env})
   244  	}
   245  }
   246  
   247  // buildFlags returns the go tool flags for building.
   248  func buildFlags(env build.Environment, staticLinking bool, buildTags []string) (flags []string) {
   249  	var ld []string
   250  	if env.Commit != "" {
   251  		ld = append(ld, "-X", "github.com/calmw/ethereum/internal/version.gitCommit="+env.Commit)
   252  		ld = append(ld, "-X", "github.com/calmw/ethereum/internal/version.gitDate="+env.Date)
   253  	}
   254  	// Strip DWARF on darwin. This used to be required for certain things,
   255  	// and there is no downside to this, so we just keep doing it.
   256  	if runtime.GOOS == "darwin" {
   257  		ld = append(ld, "-s")
   258  	}
   259  	if runtime.GOOS == "linux" {
   260  		// Enforce the stacksize to 8M, which is the case on most platforms apart from
   261  		// alpine Linux.
   262  		extld := []string{"-Wl,-z,stack-size=0x800000"}
   263  		if staticLinking {
   264  			extld = append(extld, "-static")
   265  			// Under static linking, use of certain glibc features must be
   266  			// disabled to avoid shared library dependencies.
   267  			buildTags = append(buildTags, "osusergo", "netgo")
   268  		}
   269  		ld = append(ld, "-extldflags", "'"+strings.Join(extld, " ")+"'")
   270  	}
   271  	if len(ld) > 0 {
   272  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   273  	}
   274  	if len(buildTags) > 0 {
   275  		flags = append(flags, "-tags", strings.Join(buildTags, ","))
   276  	}
   277  	return flags
   278  }
   279  
   280  // Running The Tests
   281  //
   282  // "tests" also includes static analysis tools such as vet.
   283  
   284  func doTest(cmdline []string) {
   285  	var (
   286  		dlgo     = flag.Bool("dlgo", false, "Download Go and build with it")
   287  		arch     = flag.String("arch", "", "Run tests for given architecture")
   288  		cc       = flag.String("cc", "", "Sets C compiler binary")
   289  		coverage = flag.Bool("coverage", false, "Whether to record code coverage")
   290  		verbose  = flag.Bool("v", false, "Whether to log verbosely")
   291  		race     = flag.Bool("race", false, "Execute the race detector")
   292  	)
   293  	flag.CommandLine.Parse(cmdline)
   294  
   295  	// Configure the toolchain.
   296  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   297  	if *dlgo {
   298  		csdb := build.MustLoadChecksums("build/checksums.txt")
   299  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   300  	}
   301  	gotest := tc.Go("test", "-tags=ckzg")
   302  
   303  	// Test a single package at a time. CI builders are slow
   304  	// and some tests run into timeouts under load.
   305  	gotest.Args = append(gotest.Args, "-p", "1")
   306  	if *coverage {
   307  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   308  	}
   309  	if *verbose {
   310  		gotest.Args = append(gotest.Args, "-v")
   311  	}
   312  	if *race {
   313  		gotest.Args = append(gotest.Args, "-race")
   314  	}
   315  
   316  	packages := []string{"./..."}
   317  	if len(flag.CommandLine.Args()) > 0 {
   318  		packages = flag.CommandLine.Args()
   319  	}
   320  	gotest.Args = append(gotest.Args, packages...)
   321  	build.MustRun(gotest)
   322  }
   323  
   324  // doLint runs golangci-lint on requested packages.
   325  func doLint(cmdline []string) {
   326  	var (
   327  		cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
   328  	)
   329  	flag.CommandLine.Parse(cmdline)
   330  	packages := []string{"./..."}
   331  	if len(flag.CommandLine.Args()) > 0 {
   332  		packages = flag.CommandLine.Args()
   333  	}
   334  
   335  	linter := downloadLinter(*cachedir)
   336  	lflags := []string{"run", "--config", ".golangci.yml"}
   337  	build.MustRunCommand(linter, append(lflags, packages...)...)
   338  	fmt.Println("You have achieved perfection.")
   339  }
   340  
   341  // downloadLinter downloads and unpacks golangci-lint.
   342  func downloadLinter(cachedir string) string {
   343  	const version = "1.51.1"
   344  
   345  	csdb := build.MustLoadChecksums("build/checksums.txt")
   346  	arch := runtime.GOARCH
   347  	ext := ".tar.gz"
   348  
   349  	if runtime.GOOS == "windows" {
   350  		ext = ".zip"
   351  	}
   352  	if arch == "arm" {
   353  		arch += "v" + os.Getenv("GOARM")
   354  	}
   355  	base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, arch)
   356  	url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s%s", version, base, ext)
   357  	archivePath := filepath.Join(cachedir, base+ext)
   358  	if err := csdb.DownloadFile(url, archivePath); err != nil {
   359  		log.Fatal(err)
   360  	}
   361  	if err := build.ExtractArchive(archivePath, cachedir); err != nil {
   362  		log.Fatal(err)
   363  	}
   364  	return filepath.Join(cachedir, base, "golangci-lint")
   365  }
   366  
   367  // Release Packaging
   368  func doArchive(cmdline []string) {
   369  	var (
   370  		arch    = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   371  		atype   = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   372  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   373  		signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`)
   374  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   375  		ext     string
   376  	)
   377  	flag.CommandLine.Parse(cmdline)
   378  	switch *atype {
   379  	case "zip":
   380  		ext = ".zip"
   381  	case "tar":
   382  		ext = ".tar.gz"
   383  	default:
   384  		log.Fatal("unknown archive type: ", atype)
   385  	}
   386  
   387  	var (
   388  		env      = build.Env()
   389  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   390  		geth     = "geth-" + basegeth + ext
   391  		alltools = "geth-alltools-" + basegeth + ext
   392  	)
   393  	maybeSkipArchive(env)
   394  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   395  		log.Fatal(err)
   396  	}
   397  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   398  		log.Fatal(err)
   399  	}
   400  	for _, archive := range []string{geth, alltools} {
   401  		if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
   402  			log.Fatal(err)
   403  		}
   404  	}
   405  }
   406  
   407  func archiveBasename(arch string, archiveVersion string) string {
   408  	platform := runtime.GOOS + "-" + arch
   409  	if arch == "arm" {
   410  		platform += os.Getenv("GOARM")
   411  	}
   412  	if arch == "android" {
   413  		platform = "android-all"
   414  	}
   415  	if arch == "ios" {
   416  		platform = "ios-all"
   417  	}
   418  	return platform + "-" + archiveVersion
   419  }
   420  
   421  func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error {
   422  	// If signing was requested, generate the signature files
   423  	if signer != "" {
   424  		key := getenvBase64(signer)
   425  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   426  			return err
   427  		}
   428  	}
   429  	if signifyVar != "" {
   430  		key := os.Getenv(signifyVar)
   431  		untrustedComment := "verify with geth-release.pub"
   432  		trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
   433  		if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
   434  			return err
   435  		}
   436  	}
   437  	// If uploading to Azure was requested, push the archive possibly with its signature
   438  	if blobstore != "" {
   439  		auth := build.AzureBlobstoreConfig{
   440  			Account:   strings.Split(blobstore, "/")[0],
   441  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   442  			Container: strings.SplitN(blobstore, "/", 2)[1],
   443  		}
   444  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   445  			return err
   446  		}
   447  		if signer != "" {
   448  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   449  				return err
   450  			}
   451  		}
   452  		if signifyVar != "" {
   453  			if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
   454  				return err
   455  			}
   456  		}
   457  	}
   458  	return nil
   459  }
   460  
   461  // skips archiving for some build configurations.
   462  func maybeSkipArchive(env build.Environment) {
   463  	if env.IsPullRequest {
   464  		log.Printf("skipping archive creation because this is a PR build")
   465  		os.Exit(0)
   466  	}
   467  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   468  		log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
   469  		os.Exit(0)
   470  	}
   471  }
   472  
   473  // Builds the docker images and optionally uploads them to Docker Hub.
   474  func doDocker(cmdline []string) {
   475  	var (
   476  		image    = flag.Bool("image", false, `Whether to build and push an arch specific docker image`)
   477  		manifest = flag.String("manifest", "", `Push a multi-arch docker image for the specified architectures (usually "amd64,arm64")`)
   478  		upload   = flag.String("upload", "", `Where to upload the docker image (usually "ethereum/client-go")`)
   479  	)
   480  	flag.CommandLine.Parse(cmdline)
   481  
   482  	// Skip building and pushing docker images for PR builds
   483  	env := build.Env()
   484  	maybeSkipArchive(env)
   485  
   486  	// Retrieve the upload credentials and authenticate
   487  	user := getenvBase64("DOCKER_HUB_USERNAME")
   488  	pass := getenvBase64("DOCKER_HUB_PASSWORD")
   489  
   490  	if len(user) > 0 && len(pass) > 0 {
   491  		auther := exec.Command("docker", "login", "-u", string(user), "--password-stdin")
   492  		auther.Stdin = bytes.NewReader(pass)
   493  		build.MustRun(auther)
   494  	}
   495  	// Retrieve the version infos to build and push to the following paths:
   496  	//  - ethereum/client-go:latest                            - Pushes to the master branch, Geth only
   497  	//  - ethereum/client-go:stable                            - Version tag publish on GitHub, Geth only
   498  	//  - ethereum/client-go:alltools-latest                   - Pushes to the master branch, Geth & tools
   499  	//  - ethereum/client-go:alltools-stable                   - Version tag publish on GitHub, Geth & tools
   500  	//  - ethereum/client-go:release-<major>.<minor>           - Version tag publish on GitHub, Geth only
   501  	//  - ethereum/client-go:alltools-release-<major>.<minor>  - Version tag publish on GitHub, Geth & tools
   502  	//  - ethereum/client-go:v<major>.<minor>.<patch>          - Version tag publish on GitHub, Geth only
   503  	//  - ethereum/client-go:alltools-v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth & tools
   504  	var tags []string
   505  
   506  	switch {
   507  	case env.Branch == "master":
   508  		tags = []string{"latest"}
   509  	case strings.HasPrefix(env.Tag, "v1."):
   510  		tags = []string{"stable", fmt.Sprintf("release-1.%d", params.VersionMinor), "v" + params.Version}
   511  	}
   512  	// If architecture specific image builds are requested, build and push them
   513  	if *image {
   514  		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), ".")
   515  		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", ".")
   516  
   517  		// Tag and upload the images to Docker Hub
   518  		for _, tag := range tags {
   519  			gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, runtime.GOARCH)
   520  			toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, runtime.GOARCH)
   521  
   522  			// If the image already exists (non version tag), check the build
   523  			// number to prevent overwriting a newer commit if concurrent builds
   524  			// are running. This is still a tiny bit racey if two published are
   525  			// done at the same time, but that's extremely unlikely even on the
   526  			// master branch.
   527  			for _, img := range []string{gethImage, toolImage} {
   528  				if exec.Command("docker", "pull", img).Run() != nil {
   529  					continue // Generally the only failure is a missing image, which is good
   530  				}
   531  				buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   532  				if err != nil {
   533  					log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   534  				}
   535  				buildnum = bytes.TrimSpace(buildnum)
   536  
   537  				if len(buildnum) > 0 && len(env.Buildnum) > 0 {
   538  					oldnum, err := strconv.Atoi(string(buildnum))
   539  					if err != nil {
   540  						log.Fatalf("Failed to parse old image build number: %v", err)
   541  					}
   542  					newnum, err := strconv.Atoi(env.Buildnum)
   543  					if err != nil {
   544  						log.Fatalf("Failed to parse current build number: %v", err)
   545  					}
   546  					if oldnum > newnum {
   547  						log.Fatalf("Current build number %d not newer than existing %d", newnum, oldnum)
   548  					} else {
   549  						log.Printf("Updating %s from build %d to %d", img, oldnum, newnum)
   550  					}
   551  				}
   552  			}
   553  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:TAG", *upload), gethImage)
   554  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:alltools-TAG", *upload), toolImage)
   555  			build.MustRunCommand("docker", "push", gethImage)
   556  			build.MustRunCommand("docker", "push", toolImage)
   557  		}
   558  	}
   559  	// If multi-arch image manifest push is requested, assemble it
   560  	if len(*manifest) != 0 {
   561  		// Since different architectures are pushed by different builders, wait
   562  		// until all required images are updated.
   563  		var mismatch bool
   564  		for i := 0; i < 2; i++ { // 2 attempts, second is race check
   565  			mismatch = false // hope there's no mismatch now
   566  
   567  			for _, tag := range tags {
   568  				for _, arch := range strings.Split(*manifest, ",") {
   569  					gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, arch)
   570  					toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, arch)
   571  
   572  					for _, img := range []string{gethImage, toolImage} {
   573  						if out, err := exec.Command("docker", "pull", img).CombinedOutput(); err != nil {
   574  							log.Printf("Required image %s unavailable: %v\nOutput: %s", img, err, out)
   575  							mismatch = true
   576  							break
   577  						}
   578  						buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   579  						if err != nil {
   580  							log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   581  						}
   582  						buildnum = bytes.TrimSpace(buildnum)
   583  
   584  						if string(buildnum) != env.Buildnum {
   585  							log.Printf("Build number mismatch on %s: want %s, have %s", img, env.Buildnum, buildnum)
   586  							mismatch = true
   587  							break
   588  						}
   589  					}
   590  					if mismatch {
   591  						break
   592  					}
   593  				}
   594  				if mismatch {
   595  					break
   596  				}
   597  			}
   598  			if mismatch {
   599  				// Build numbers mismatching, retry in a short time to
   600  				// avoid concurrent fails in both publisher images. If
   601  				// however the retry failed too, it means the concurrent
   602  				// builder is still crunching, let that do the publish.
   603  				if i == 0 {
   604  					time.Sleep(30 * time.Second)
   605  				}
   606  				continue
   607  			}
   608  			break
   609  		}
   610  		if mismatch {
   611  			log.Println("Relinquishing publish to other builder")
   612  			return
   613  		}
   614  		// Assemble and push the Geth manifest image
   615  		for _, tag := range tags {
   616  			gethImage := fmt.Sprintf("%s:%s", *upload, tag)
   617  
   618  			var gethSubImages []string
   619  			for _, arch := range strings.Split(*manifest, ",") {
   620  				gethSubImages = append(gethSubImages, gethImage+"-"+arch)
   621  			}
   622  			build.MustRunCommand("docker", append([]string{"manifest", "create", gethImage}, gethSubImages...)...)
   623  			build.MustRunCommand("docker", "manifest", "push", gethImage)
   624  		}
   625  		// Assemble and push the alltools manifest image
   626  		for _, tag := range tags {
   627  			toolImage := fmt.Sprintf("%s:alltools-%s", *upload, tag)
   628  
   629  			var toolSubImages []string
   630  			for _, arch := range strings.Split(*manifest, ",") {
   631  				toolSubImages = append(toolSubImages, toolImage+"-"+arch)
   632  			}
   633  			build.MustRunCommand("docker", append([]string{"manifest", "create", toolImage}, toolSubImages...)...)
   634  			build.MustRunCommand("docker", "manifest", "push", toolImage)
   635  		}
   636  	}
   637  }
   638  
   639  // Debian Packaging
   640  func doDebianSource(cmdline []string) {
   641  	var (
   642  		cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
   643  		signer   = flag.String("signer", "", `Signing key name, also used as package author`)
   644  		upload   = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   645  		sshUser  = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   646  		workdir  = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   647  		now      = time.Now()
   648  	)
   649  	flag.CommandLine.Parse(cmdline)
   650  	*workdir = makeWorkdir(*workdir)
   651  	env := build.Env()
   652  	tc := new(build.GoToolchain)
   653  	maybeSkipArchive(env)
   654  
   655  	// Import the signing key.
   656  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   657  		gpg := exec.Command("gpg", "--import")
   658  		gpg.Stdin = bytes.NewReader(key)
   659  		build.MustRun(gpg)
   660  	}
   661  	// Download and verify the Go source packages.
   662  	var (
   663  		gobootbundle = downloadGoBootstrapSources(*cachedir)
   664  		gobundle     = downloadGoSources(*cachedir)
   665  	)
   666  	// Download all the dependencies needed to build the sources and run the ci script
   667  	srcdepfetch := tc.Go("mod", "download")
   668  	srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   669  	build.MustRun(srcdepfetch)
   670  
   671  	cidepfetch := tc.Go("run", "./build/ci.go")
   672  	cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   673  	cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
   674  
   675  	// Create Debian packages and upload them.
   676  	for _, pkg := range debPackages {
   677  		for distro, goboot := range debDistroGoBoots {
   678  			// Prepare the debian package with the go-ethereum sources.
   679  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   680  			pkgdir := stageDebianSource(*workdir, meta)
   681  
   682  			// Add bootstrapper Go source code
   683  			if err := build.ExtractArchive(gobootbundle, pkgdir); err != nil {
   684  				log.Fatalf("Failed to extract bootstrapper Go sources: %v", err)
   685  			}
   686  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".goboot")); err != nil {
   687  				log.Fatalf("Failed to rename bootstrapper Go source folder: %v", err)
   688  			}
   689  			// Add builder Go source code
   690  			if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
   691  				log.Fatalf("Failed to extract builder Go sources: %v", err)
   692  			}
   693  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   694  				log.Fatalf("Failed to rename builder Go source folder: %v", err)
   695  			}
   696  			// Add all dependency modules in compressed form
   697  			os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
   698  			if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
   699  				log.Fatalf("Failed to copy Go module dependencies: %v", err)
   700  			}
   701  			// Run the packaging and upload to the PPA
   702  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
   703  			debuild.Dir = pkgdir
   704  			build.MustRun(debuild)
   705  
   706  			var (
   707  				basename  = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   708  				source    = filepath.Join(*workdir, basename+".tar.xz")
   709  				dsc       = filepath.Join(*workdir, basename+".dsc")
   710  				changes   = filepath.Join(*workdir, basename+"_source.changes")
   711  				buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
   712  			)
   713  			if *signer != "" {
   714  				build.MustRunCommand("debsign", changes)
   715  			}
   716  			if *upload != "" {
   717  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
   718  			}
   719  		}
   720  	}
   721  }
   722  
   723  // downloadGoBootstrapSources downloads the Go source tarball that will be used
   724  // to bootstrap the builder Go.
   725  func downloadGoBootstrapSources(cachedir string) string {
   726  	csdb := build.MustLoadChecksums("build/checksums.txt")
   727  	file := fmt.Sprintf("go%s.src.tar.gz", gobootVersion)
   728  	url := "https://dl.google.com/go/" + file
   729  	dst := filepath.Join(cachedir, file)
   730  	if err := csdb.DownloadFile(url, dst); err != nil {
   731  		log.Fatal(err)
   732  	}
   733  	return dst
   734  }
   735  
   736  // downloadGoSources downloads the Go source tarball.
   737  func downloadGoSources(cachedir string) string {
   738  	csdb := build.MustLoadChecksums("build/checksums.txt")
   739  	file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
   740  	url := "https://dl.google.com/go/" + file
   741  	dst := filepath.Join(cachedir, file)
   742  	if err := csdb.DownloadFile(url, dst); err != nil {
   743  		log.Fatal(err)
   744  	}
   745  	return dst
   746  }
   747  
   748  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   749  	p := strings.Split(ppa, "/")
   750  	if len(p) != 2 {
   751  		log.Fatal("-upload PPA name must contain single /")
   752  	}
   753  	if sshUser == "" {
   754  		sshUser = p[0]
   755  	}
   756  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   757  	// Create the SSH identity file if it doesn't exist.
   758  	var idfile string
   759  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   760  		idfile = filepath.Join(workdir, "sshkey")
   761  		if !common.FileExist(idfile) {
   762  			os.WriteFile(idfile, sshkey, 0600)
   763  		}
   764  	}
   765  	// Upload
   766  	dest := sshUser + "@ppa.launchpad.net"
   767  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   768  		log.Fatal(err)
   769  	}
   770  }
   771  
   772  func getenvBase64(variable string) []byte {
   773  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   774  	if err != nil {
   775  		log.Fatal("invalid base64 " + variable)
   776  	}
   777  	return []byte(dec)
   778  }
   779  
   780  func makeWorkdir(wdflag string) string {
   781  	var err error
   782  	if wdflag != "" {
   783  		err = os.MkdirAll(wdflag, 0744)
   784  	} else {
   785  		wdflag, err = os.MkdirTemp("", "geth-build-")
   786  	}
   787  	if err != nil {
   788  		log.Fatal(err)
   789  	}
   790  	return wdflag
   791  }
   792  
   793  func isUnstableBuild(env build.Environment) bool {
   794  	if env.Tag != "" {
   795  		return false
   796  	}
   797  	return true
   798  }
   799  
   800  type debPackage struct {
   801  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   802  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   803  	Executables []debExecutable // executables to be included in the package
   804  }
   805  
   806  type debMetadata struct {
   807  	Env           build.Environment
   808  	GoBootPackage string
   809  	GoBootPath    string
   810  
   811  	PackageName string
   812  
   813  	// go-ethereum version being built. Note that this
   814  	// is not the debian package version. The package version
   815  	// is constructed by VersionString.
   816  	Version string
   817  
   818  	Author       string // "name <email>", also selects signing key
   819  	Distro, Time string
   820  	Executables  []debExecutable
   821  }
   822  
   823  type debExecutable struct {
   824  	PackageName string
   825  	BinaryName  string
   826  	Description string
   827  }
   828  
   829  // Package returns the name of the package if present, or
   830  // fallbacks to BinaryName
   831  func (d debExecutable) Package() string {
   832  	if d.PackageName != "" {
   833  		return d.PackageName
   834  	}
   835  	return d.BinaryName
   836  }
   837  
   838  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   839  	if author == "" {
   840  		// No signing key, use default author.
   841  		author = "Ethereum Builds <fjl@ethereum.org>"
   842  	}
   843  	return debMetadata{
   844  		GoBootPackage: goboot,
   845  		GoBootPath:    debGoBootPaths[goboot],
   846  		PackageName:   name,
   847  		Env:           env,
   848  		Author:        author,
   849  		Distro:        distro,
   850  		Version:       version,
   851  		Time:          t.Format(time.RFC1123Z),
   852  		Executables:   exes,
   853  	}
   854  }
   855  
   856  // Name returns the name of the metapackage that depends
   857  // on all executable packages.
   858  func (meta debMetadata) Name() string {
   859  	if isUnstableBuild(meta.Env) {
   860  		return meta.PackageName + "-unstable"
   861  	}
   862  	return meta.PackageName
   863  }
   864  
   865  // VersionString returns the debian version of the packages.
   866  func (meta debMetadata) VersionString() string {
   867  	vsn := meta.Version
   868  	if meta.Env.Buildnum != "" {
   869  		vsn += "+build" + meta.Env.Buildnum
   870  	}
   871  	if meta.Distro != "" {
   872  		vsn += "+" + meta.Distro
   873  	}
   874  	return vsn
   875  }
   876  
   877  // ExeList returns the list of all executable packages.
   878  func (meta debMetadata) ExeList() string {
   879  	names := make([]string, len(meta.Executables))
   880  	for i, e := range meta.Executables {
   881  		names[i] = meta.ExeName(e)
   882  	}
   883  	return strings.Join(names, ", ")
   884  }
   885  
   886  // ExeName returns the package name of an executable package.
   887  func (meta debMetadata) ExeName(exe debExecutable) string {
   888  	if isUnstableBuild(meta.Env) {
   889  		return exe.Package() + "-unstable"
   890  	}
   891  	return exe.Package()
   892  }
   893  
   894  // ExeConflicts returns the content of the Conflicts field
   895  // for executable packages.
   896  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   897  	if isUnstableBuild(meta.Env) {
   898  		// Set up the conflicts list so that the *-unstable packages
   899  		// cannot be installed alongside the regular version.
   900  		//
   901  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   902  		// is very explicit about Conflicts: and says that Breaks: should
   903  		// be preferred and the conflicting files should be handled via
   904  		// alternates. We might do this eventually but using a conflict is
   905  		// easier now.
   906  		return "ethereum, " + exe.Package()
   907  	}
   908  	return ""
   909  }
   910  
   911  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   912  	pkg := meta.Name() + "-" + meta.VersionString()
   913  	pkgdir = filepath.Join(tmpdir, pkg)
   914  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   915  		log.Fatal(err)
   916  	}
   917  	// Copy the source code.
   918  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   919  
   920  	// Put the debian build files in place.
   921  	debian := filepath.Join(pkgdir, "debian")
   922  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   923  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   924  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   925  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   926  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   927  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   928  	for _, exe := range meta.Executables {
   929  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   930  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   931  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   932  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   933  	}
   934  	return pkgdir
   935  }
   936  
   937  // Windows installer
   938  func doWindowsInstaller(cmdline []string) {
   939  	// Parse the flags and make skip installer generation on PRs
   940  	var (
   941  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   942  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   943  		signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
   944  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   945  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   946  	)
   947  	flag.CommandLine.Parse(cmdline)
   948  	*workdir = makeWorkdir(*workdir)
   949  	env := build.Env()
   950  	maybeSkipArchive(env)
   951  
   952  	// Aggregate binaries that are included in the installer
   953  	var (
   954  		devTools []string
   955  		allTools []string
   956  		gethTool string
   957  	)
   958  	for _, file := range allToolsArchiveFiles {
   959  		if file == "COPYING" { // license, copied later
   960  			continue
   961  		}
   962  		allTools = append(allTools, filepath.Base(file))
   963  		if filepath.Base(file) == "geth.exe" {
   964  			gethTool = file
   965  		} else {
   966  			devTools = append(devTools, file)
   967  		}
   968  	}
   969  
   970  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   971  	// first section contains the geth binary, second section holds the dev tools.
   972  	templateData := map[string]interface{}{
   973  		"License":  "COPYING",
   974  		"Geth":     gethTool,
   975  		"DevTools": devTools,
   976  	}
   977  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   978  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   979  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   980  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   981  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   982  	if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
   983  		log.Fatalf("Failed to copy SimpleFC.dll: %v", err)
   984  	}
   985  	if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
   986  		log.Fatalf("Failed to copy copyright note: %v", err)
   987  	}
   988  	// Build the installer. This assumes that all the needed files have been previously
   989  	// built (don't mix building and packaging to keep cross compilation complexity to a
   990  	// minimum).
   991  	version := strings.Split(params.Version, ".")
   992  	if env.Commit != "" {
   993  		version[2] += "-" + env.Commit[:8]
   994  	}
   995  	installer, err := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   996  	if err != nil {
   997  		log.Fatalf("Failed to convert installer file path: %v", err)
   998  	}
   999  	build.MustRunCommand("makensis.exe",
  1000  		"/DOUTPUTFILE="+installer,
  1001  		"/DMAJORVERSION="+version[0],
  1002  		"/DMINORVERSION="+version[1],
  1003  		"/DBUILDVERSION="+version[2],
  1004  		"/DARCH="+*arch,
  1005  		filepath.Join(*workdir, "geth.nsi"),
  1006  	)
  1007  	// Sign and publish installer.
  1008  	if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
  1009  		log.Fatal(err)
  1010  	}
  1011  }
  1012  
  1013  // Binary distribution cleanups
  1014  
  1015  func doPurge(cmdline []string) {
  1016  	var (
  1017  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1018  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1019  	)
  1020  	flag.CommandLine.Parse(cmdline)
  1021  
  1022  	if env := build.Env(); !env.IsCronJob {
  1023  		log.Printf("skipping because not a cron job")
  1024  		os.Exit(0)
  1025  	}
  1026  	// Create the azure authentication and list the current archives
  1027  	auth := build.AzureBlobstoreConfig{
  1028  		Account:   strings.Split(*store, "/")[0],
  1029  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1030  		Container: strings.SplitN(*store, "/", 2)[1],
  1031  	}
  1032  	blobs, err := build.AzureBlobstoreList(auth)
  1033  	if err != nil {
  1034  		log.Fatal(err)
  1035  	}
  1036  	fmt.Printf("Found %d blobs\n", len(blobs))
  1037  
  1038  	// Iterate over the blobs, collect and sort all unstable builds
  1039  	for i := 0; i < len(blobs); i++ {
  1040  		if !strings.Contains(*blobs[i].Name, "unstable") {
  1041  			blobs = append(blobs[:i], blobs[i+1:]...)
  1042  			i--
  1043  		}
  1044  	}
  1045  	for i := 0; i < len(blobs); i++ {
  1046  		for j := i + 1; j < len(blobs); j++ {
  1047  			if blobs[i].Properties.LastModified.After(*blobs[j].Properties.LastModified) {
  1048  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1049  			}
  1050  		}
  1051  	}
  1052  	// Filter out all archives more recent that the given threshold
  1053  	for i, blob := range blobs {
  1054  		if time.Since(*blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1055  			blobs = blobs[:i]
  1056  			break
  1057  		}
  1058  	}
  1059  	fmt.Printf("Deleting %d blobs\n", len(blobs))
  1060  	// Delete all marked as such and return
  1061  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1062  		log.Fatal(err)
  1063  	}
  1064  }