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