android_test.go 11 KB

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