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