github.com/codingfuture/orig-energi3@v0.8.4/mobile/android_test.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2016 The go-ethereum Authors
     3  // This file is part of the Energi Core library.
     4  //
     5  // The Energi Core library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The Energi Core library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package geth
    19  
    20  import (
    21  	"io/ioutil"
    22  	"os"
    23  	"os/exec"
    24  	"path/filepath"
    25  	"runtime"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/internal/build"
    30  )
    31  
    32  // androidTestClass is a Java class to do some lightweight tests against the Android
    33  // bindings. The goal is not to test each individual functionality, rather just to
    34  // catch breaking API and/or implementation changes.
    35  const androidTestClass = `
    36  package go;
    37  
    38  import android.test.InstrumentationTestCase;
    39  import android.test.MoreAsserts;
    40  
    41  import java.math.BigInteger;
    42  import java.util.Arrays;
    43  
    44  import org.ethereum.geth.*;
    45  
    46  public class AndroidTest extends InstrumentationTestCase {
    47  	public AndroidTest() {}
    48  
    49  	public void testAccountManagement() {
    50  		// Create an encrypted keystore with light crypto parameters.
    51  		KeyStore ks = new KeyStore(getInstrumentation().getContext().getFilesDir() + "/keystore", Geth.LightScryptN, Geth.LightScryptP);
    52  
    53  		try {
    54  			// Create a new account with the specified encryption passphrase.
    55  			Account newAcc = ks.newAccount("Creation password");
    56  
    57  			// Export the newly created account with a different passphrase. The returned
    58  			// data from this method invocation is a JSON encoded, encrypted key-file.
    59  			byte[] jsonAcc = ks.exportKey(newAcc, "Creation password", "Export password");
    60  
    61  			// Update the passphrase on the account created above inside the local keystore.
    62  			ks.updateAccount(newAcc, "Creation password", "Update password");
    63  
    64  			// Delete the account updated above from the local keystore.
    65  			ks.deleteAccount(newAcc, "Update password");
    66  
    67  			// Import back the account we've exported (and then deleted) above with yet
    68  			// again a fresh passphrase.
    69  			Account impAcc = ks.importKey(jsonAcc, "Export password", "Import password");
    70  
    71  			// Create a new account to sign transactions with
    72  			Account signer = ks.newAccount("Signer password");
    73  
    74  			Transaction tx = new Transaction(
    75  				1, new Address("0x0000000000000000000000000000000000000000"),
    76  				new BigInt(0), 0, new BigInt(1), null); // Random empty transaction
    77  			BigInt chain = new BigInt(1); // Chain identifier of the main net
    78  
    79  			// Sign a transaction with a single authorization
    80  			Transaction signed = ks.signTxPassphrase(signer, "Signer password", tx, chain);
    81  
    82  			// Sign a transaction with multiple manually cancelled authorizations
    83  			ks.unlock(signer, "Signer password");
    84  			signed = ks.signTx(signer, tx, chain);
    85  			ks.lock(signer.getAddress());
    86  
    87  			// Sign a transaction with multiple automatically cancelled authorizations
    88  			ks.timedUnlock(signer, "Signer password", 1000000000);
    89  			signed = ks.signTx(signer, tx, chain);
    90  		} catch (Exception e) {
    91  			fail(e.toString());
    92  		}
    93  	}
    94  
    95  	public void testInprocNode() {
    96  		Context ctx = new Context();
    97  
    98  		try {
    99  			// Start up a new inprocess node
   100  			Node node = new Node(getInstrumentation().getContext().getFilesDir() + "/.ethereum", new NodeConfig());
   101  			node.start();
   102  
   103  			// Retrieve some data via function calls (we don't really care about the results)
   104  			NodeInfo info = node.getNodeInfo();
   105  			info.getName();
   106  			info.getListenerAddress();
   107  			info.getProtocols();
   108  
   109  			// Retrieve some data via the APIs (we don't really care about the results)
   110  			EthereumClient ec = node.getEthereumClient();
   111  			ec.getBlockByNumber(ctx, -1).getNumber();
   112  
   113  			NewHeadHandler handler = new NewHeadHandler() {
   114  				@Override public void onError(String error)          {}
   115  				@Override public void onNewHead(final Header header) {}
   116  			};
   117  			ec.subscribeNewHead(ctx, handler,  16);
   118  		} catch (Exception e) {
   119  			fail(e.toString());
   120  		}
   121  	}
   122  
   123  	// Tests that recovering transaction signers works for both Homestead and EIP155
   124  	// signatures too. Regression test for go-ethereum issue #14599.
   125  	public void testIssue14599() {
   126  		try {
   127  			byte[] preEIP155RLP = new BigInteger("f901fc8032830138808080b901ae60056013565b6101918061001d6000396000f35b3360008190555056006001600060e060020a6000350480630a874df61461003a57806341c0e1b514610058578063a02b161e14610066578063dbbdf0831461007757005b610045600435610149565b80600160a060020a031660005260206000f35b610060610161565b60006000f35b6100716004356100d4565b60006000f35b61008560043560243561008b565b60006000f35b600054600160a060020a031632600160a060020a031614156100ac576100b1565b6100d0565b8060018360005260205260406000208190555081600060005260206000a15b5050565b600054600160a060020a031633600160a060020a031614158015610118575033600160a060020a0316600182600052602052604060002054600160a060020a031614155b61012157610126565b610146565b600060018260005260205260406000208190555080600060005260206000a15b50565b60006001826000526020526040600020549050919050565b600054600160a060020a031633600160a060020a0316146101815761018f565b600054600160a060020a0316ff5b561ca0c5689ed1ad124753d54576dfb4b571465a41900a1dff4058d8adf16f752013d0a01221cbd70ec28c94a3b55ec771bcbc70778d6ee0b51ca7ea9514594c861b1884", 16).toByteArray();
   128  			preEIP155RLP = Arrays.copyOfRange(preEIP155RLP, 1, preEIP155RLP.length);
   129  
   130  			byte[] postEIP155RLP = new BigInteger("f86b80847735940082520894ef5bbb9bba2e1ca69ef81b23a8727d889f3ef0a1880de0b6b3a7640000802ba06fef16c44726a102e6d55a651740636ef8aec6df3ebf009e7b0c1f29e4ac114aa057e7fbc69760b522a78bb568cfc37a58bfdcf6ea86cb8f9b550263f58074b9cc", 16).toByteArray();
   131  			postEIP155RLP = Arrays.copyOfRange(postEIP155RLP, 1, postEIP155RLP.length);
   132  
   133  			Transaction preEIP155 =  new Transaction(preEIP155RLP);
   134  			Transaction postEIP155 = new Transaction(postEIP155RLP);
   135  
   136  			preEIP155.getFrom(null);           // Homestead should accept homestead
   137  			preEIP155.getFrom(new BigInt(4));  // EIP155 should accept homestead (missing chain ID)
   138  			postEIP155.getFrom(new BigInt(4)); // EIP155 should accept EIP 155
   139  
   140  			try {
   141  				postEIP155.getFrom(null);
   142  				fail("EIP155 transaction accepted by Homestead");
   143  			} catch (Exception e) {}
   144  		} catch (Exception e) {
   145  			fail(e.toString());
   146  		}
   147  	}
   148  }
   149  `
   150  
   151  // TestAndroid runs the Android java test class specified above.
   152  //
   153  // This requires the gradle command in PATH and the Android SDK whose path is available
   154  // through ANDROID_HOME environment variable. To successfully run the tests, an Android
   155  // device must also be available with debugging enabled.
   156  //
   157  // This method has been adapted from golang.org/x/mobile/bind/java/seq_test.go/runTest
   158  func TestAndroid(t *testing.T) {
   159  	// Skip tests on Windows altogether
   160  	if runtime.GOOS == "windows" {
   161  		t.Skip("cannot test Android bindings on Windows, skipping")
   162  	}
   163  	// Make sure all the Android tools are installed
   164  	if _, err := exec.Command("which", "gradle").CombinedOutput(); err != nil {
   165  		t.Skip("command gradle not found, skipping")
   166  	}
   167  	if sdk := os.Getenv("ANDROID_HOME"); sdk == "" {
   168  		// Android SDK not explicitly given, try to auto-resolve
   169  		autopath := filepath.Join(os.Getenv("HOME"), "Android", "Sdk")
   170  		if _, err := os.Stat(autopath); err != nil {
   171  			t.Skip("ANDROID_HOME environment var not set, skipping")
   172  		}
   173  		os.Setenv("ANDROID_HOME", autopath)
   174  	}
   175  	if _, err := exec.Command("which", "gomobile").CombinedOutput(); err != nil {
   176  		t.Log("gomobile missing, installing it...")
   177  		if out, err := exec.Command("go", "get", "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil {
   178  			t.Fatalf("install failed: %v\n%s", err, string(out))
   179  		}
   180  		t.Log("initializing gomobile...")
   181  		start := time.Now()
   182  		if _, err := exec.Command("gomobile", "init").CombinedOutput(); err != nil {
   183  			t.Fatalf("initialization failed: %v", err)
   184  		}
   185  		t.Logf("initialization took %v", time.Since(start))
   186  	}
   187  	// Create and switch to a temporary workspace
   188  	workspace, err := ioutil.TempDir("", "energi3-android-")
   189  	if err != nil {
   190  		t.Fatalf("failed to create temporary workspace: %v", err)
   191  	}
   192  	defer os.RemoveAll(workspace)
   193  
   194  	pwd, err := os.Getwd()
   195  	if err != nil {
   196  		t.Fatalf("failed to get current working directory: %v", err)
   197  	}
   198  	if err := os.Chdir(workspace); err != nil {
   199  		t.Fatalf("failed to switch to temporary workspace: %v", err)
   200  	}
   201  	defer os.Chdir(pwd)
   202  
   203  	// Create the skeleton of the Android project
   204  	for _, dir := range []string{"src/main", "src/androidTest/java/org/ethereum/energi3test", "libs"} {
   205  		err = os.MkdirAll(dir, os.ModePerm)
   206  		if err != nil {
   207  			t.Fatal(err)
   208  		}
   209  	}
   210  	// Generate the mobile bindings for Geth and add the tester class
   211  	gobind := exec.Command("gomobile", "bind", "-javapkg", "org.ethereum", "github.com/ethereum/go-ethereum/mobile")
   212  	if output, err := gobind.CombinedOutput(); err != nil {
   213  		t.Logf("%s", output)
   214  		t.Fatalf("failed to run gomobile bind: %v", err)
   215  	}
   216  	build.CopyFile(filepath.Join("libs", "energi3.aar"), "energi3.aar", os.ModePerm)
   217  
   218  	if err = ioutil.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "energi3test", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil {
   219  		t.Fatalf("failed to write Android test class: %v", err)
   220  	}
   221  	// Finish creating the project and run the tests via gradle
   222  	if err = ioutil.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil {
   223  		t.Fatalf("failed to write Android manifest: %v", err)
   224  	}
   225  	if err = ioutil.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil {
   226  		t.Fatalf("failed to write gradle build file: %v", err)
   227  	}
   228  	if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil {
   229  		t.Logf("%s", output)
   230  		t.Errorf("failed to run gradle test: %v", err)
   231  	}
   232  }
   233  
   234  const androidManifest = `<?xml version="1.0" encoding="utf-8"?>
   235  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   236            package="org.ethereum.energi3test"
   237  	  android:versionCode="1"
   238  	  android:versionName="1.0">
   239  
   240  		<uses-permission android:name="android.permission.INTERNET" />
   241  </manifest>`
   242  
   243  const gradleConfig = `buildscript {
   244      repositories {
   245          jcenter()
   246      }
   247      dependencies {
   248          classpath 'com.android.tools.build:gradle:2.2.3'
   249      }
   250  }
   251  allprojects {
   252      repositories { jcenter() }
   253  }
   254  apply plugin: 'com.android.library'
   255  android {
   256      compileSdkVersion 'android-19'
   257      buildToolsVersion '21.1.2'
   258      defaultConfig { minSdkVersion 15 }
   259  }
   260  repositories {
   261      flatDir { dirs 'libs' }
   262  }
   263  dependencies {
   264      compile 'com.android.support:appcompat-v7:19.0.0'
   265      compile(name: "energi3", ext: "aar")
   266  }
   267  `