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