GithubHelp home page GithubHelp logo

consenlabs / token-core-android Goto Github PK

View Code? Open in Web Editor NEW
647.0 42.0 198.0 194 KB

a blockchain private key management library on android

License: Apache License 2.0

Java 100.00%
ethereum eos bitcoin blockchain

token-core-android's Introduction

Token Core

TokenCore is a blockchain library. TokenCore provides the relatively consistent API that allows you to manage your wallets and sign transactions in BTC, ETH and EOS chains simultaneously. In addition, TokenCore introduces the concept of 'identity', you can use the same mnemonic to manage wallets on the three chains.

Installation

Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:

	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Step 2. Add the dependency

dependencies {
	implementation 'com.github.consenlabs:token-core-android:v0.1'
}

Step 3. Add the JAVA8 support to your build.gradle

android {
    ……
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
   ……
}

Step 4. (Optional) When you wants to debug your app in Android Oreo you shoud add the blow code to your build.gradle. Pls ref to https://issuetracker.google.com/issues/65941637 for more info.

android {
    ……
    packagingOptions {
        exclude 'lib/x86_64/darwin/libscrypt.dylib'
    }
   ……
}

Try the API

Init the storage to store the keystore file

public class MainActivity extends AppCompatActivity implements KeystoreStorage {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WalletManager.storage = this;
        WalletManager.scanWallets();
    }

    public File getKeystoreDir() {
        return this.getFilesDir();
    }
}

Create new Identity and derive the eth, btc wallets

// You should create or recover Identity first before you create other wallets
// The last param, Metadata.P2WPKH means that the derived btc wallet is a SegWit wallet
Identity identity = Identity.createIdentity("MyFirstIdentity", SampleKey.PASSWORD, SampleKey.PASSWORD_HINT, Network.MAINNET, Metadata.P2WPKH);


Wallet ethereumWallet = identity.getWallets().get(0);
Wallet bitcoinWallet = identity.getWallets().get(1);

Export Wallet

String prvKey = WalletManager.exportPrivateKey(ethereumWallet.getId(), SampleKey.PASSWORD);
System.out.println(String.format("PrivateKey: %s", prvKey));
String mnemonic = WalletManager.exportMnemonic(ethereumWallet.getId(), SampleKey.PASSWORD).getMnemonic();
System.out.println(String.format("Mnemonic: %s", mnemonic));
String json = WalletManager.exportKeystore(ethereumWallet.getId(), SampleKey.PASSWORD);
System.out.println(String.format("Keystore: %s", json));

// output:
// PrivateKey: f653be3f639f45ea1ed3eb152829b6d881ce62257aa873891e06fa9569a8d9aa
// Mnemonic: tide inmate cloud around wise bargain celery cement jungle melody galaxy grocery
// Keystore: {"id":"c7575eba-3ae3-4cc3-86ba-2eb9c6839cad","version":3,"crypto":{"ciphertext":"7083ba3dd5470ba4be4237604625e05fa6b668954d270beb848365cbf6933ec5","mac":"f4f9ea8d42ff348b11fc146c396da446cc975309b3538e08a58c0b218bddd15d","cipher":"aes-128-ctr","cipherparams":{"iv":"db3f523faf4da4f1c6edcd7bc1386879"},"kdf":"pbkdf2","kdfparams":{"dklen":32,"c":10240,"prf":"hmac-sha256","salt":"0ce830e9f888dfe33c31e6cfc444d6f588161c9d4128d4066ee5dfdcbc5d0079"}},"address":"4a1c2072ac67b616e5c578fd9e2a4d30e0158471"}

SignTransaction

EthereumTransaction tran = new EthereumTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to, BigInteger value, String data)
TxSignResult result = tran.signTransaction(chainId, SampleKey.PASSWORD, ethereumWallet);
String signedTx = result.getSignedTx(); // This is the signature result which you need to broadcast.
String txHash = result.getTxHash(); // This is txHash which you can use for locating your transaction record

Copyright and License

  Copyright 2018 imToken PTE. LTD.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

Thanks and more info

Thanks bitcoinj, CoreBitcoin and others library.

token-core-android's People

Contributors

kaichen avatar xuneal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

token-core-android's Issues

以导入私钥的方式创建ETH钱包,导出私钥报错

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at org.consenlabs.tokencore.wallet.Wallet.exportPrivateKey(Wallet.java:91)
at com.jungel.simple.MainActivity.onCreate(MainActivity.java:82)
at android.app.Activity.performCreate(Activity.java:7372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
at android.app.ActivityThread.-wrap12(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
at android.os.Handler.dispatchMessage(Handler.java:108) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7425) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 

eth怎么发送交易广播

我看eth的交易广播大多都是通过web3j实现,但是他要加载本地钱包Credentials ,才能发送,imtoken本地的钱包跟web3j又不同

关于内存泄漏

WalletManager.storage = this;
这句话会引起内存泄漏的问题怎么解决

eos签名交易

EOSTransaction 构造器
byte[] txBuf 这个值是怎么来的,我看test是写死的

jitpack.io library is not available

Looks like the build was failed.

https://jitpack.io/com/github/consenlabs/token-core-android/v0.1/build.log

I also tried build the library from local, it failed because gradle wrapper has problem.

错误: 找不到或无法加载主类 org.gradle.wrapper.GradleWrapperMain

异常:ScriptException("Push of data element that is larger than remaining data")

public void sign() {
    String pin = mEt_pin.getText().toString();
    String toAddress = mEt_transalate_address.getText().toString().trim();
    ArrayList<BitcoinTransaction.UTXO> list = new ArrayList<>();
    String network = mWallet.getMetadata().getNetwork();
    String privateKey = mWallet.exportPrivateKey(pin);
    ECKey ecKey = ECKey.fromPrivate(privateKey.getBytes());
    String publicKeyAsHex = ecKey.getPublicKeyAsHex();

    list.add(new BitcoinTransaction.UTXO(
            "d6e98b7a582a1b95e273e7ac903bde5c87bf7836cc73a13114d06383e71dd68a",
            0,
            9110000,
            mWallet.getAddress(),
            publicKeyAsHex,
            "0/0"
    ));

    BitcoinTransaction transaction = new BitcoinTransaction(toAddress, 0, 100000, 100,
            list);

    String chainId = Network.MAINNET.equals(network) ? ChainId.BITCOIN_MAINNET + ""
            : ChainId.BITCOIN_TESTNET + "";
    TxSignResult txSignResult = transaction.signTransaction(chainId, pin, mWallet);
    String signedTx = txSignResult.getSignedTx();
    String txHash = txSignResult.getTxHash();
    Log.d("sendBTC", "signedTx = " + signedTx);
    Log.d("sendBTC", "txHash = " + txHash);
}

UTXO的scriptPubKey参数是我的公钥吗?derivedPath是自己指定吗?

导入包后,编译正常,安装时报错。

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerFor_devDebug'

Caused by: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives

还有很多类似的

导出私钥报错:illegal_operation

之前的问题已经看过了。我这边创建钱包的方法有两个:

  1. Identity identity = Identity.createIdentity(name, passphrase, passHint, NET_STRING, Metadata.P2WPKH);//默认隔离见证
    
  2. Metadata metadata = new Metadata(ChainType.BITCOIN, NET_STRING, name, passHint, segWit);
    metadata.setSource(Metadata.FROM_MNEMONIC);
    Wallet mWallet = WalletManager.importWalletFromMnemonic(metadata, seedCode, BIP44Util.getBTCMnemonicPath(segWit, isMainNet), passphrase, true);
    

下面这个是通过助记词导入的。

在导出的时候调用方法:
WalletManager.exportPrivateKey(getWalletId(),getPassphrase());
就会报错,illegal_operation。但是导出助记词的方法是正常的。

请问这是什么原因?

Installation failed with message INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113

你好,导入你的库之后,安装app提示:Installation failed with message INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113,
安装的手机cpu类型是armv7l,在build里面配置了
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a','arm'
universalApk true
}
}

这个问题你知道是什么原因造成的吗

btc交易手续费的计算

构建BitcoinTransaction对象时,如何根据交易大小去计算手续费,项目中没有看到相关实现

Attempt to invoke virtual method 'void org.consenlabs.tokencore.wallet.Identity.addWallet(org.consenlabs.tokencore.wallet.Wallet)' on a null object reference

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.consenlabs.tokencore.wallet.Identity.addWallet(org.consenlabs.tokencore.wallet.Wallet)' on a null object reference at org.consenlabs.tokencore.wallet.WalletManager.persistWallet(WalletManager.java:303)
at org.consenlabs.tokencore.wallet.WalletManager.importWalletFromMnemonic(WalletManager.java:191)
at org.consenlabs.tokencore.wallet.WalletManager.importWalletFromMnemonic(WalletManager.java:195)

wallet overwrite

WalletManager persistWallet方法中调用的Identity.getCurrentIdentity().addWallet没有overwirte

Metadata().getName()获取的名称始终为btc

创建的时候是通过这种方式创建btc钱包的:
public static Wallet createWallet(String name, String passphrase, String passHint) {
LogUtil.e(TAG, "createWallet——>name:" + name + " passphrase:" + passphrase + " passHint:" + passHint);
Identity identity = Identity.createIdentity(name, passphrase, passHint, NET_STRING, Metadata.P2WPKH);//默认隔离见证
Wallet mWallet = identity.getWallets().get(1);
showWalletInfoLog(mWallet, passphrase);
LogUtil.e(TAG, "createWallet——>walletName:" + mWallet.getMetadata().getName());
WalletManager.scanWallets();
return mWallet;
}
}

之后通过wallet.getMetadata().getName();则输出的是:“BTC

导入钱包时候空指针问题,是不是少了什么环节?

public static Identity getCurrentIdentity() {
Class var0 = Identity.class;
synchronized(Identity.class) {
if (currentIdentity == null) {
currentIdentity = tryLoadFromFile();
}

        return currentIdentity;
    }
}

这个返回null,因为

try {
File file = new File(WalletManager.getDefaultKeyDirectory(), "identity.json");
ObjectMapper mapper = (new ObjectMapper()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
IdentityKeystore keystore = (IdentityKeystore)mapper.readValue(file, IdentityKeystore.class);
return new Identity(keystore);
} catch (IOException var3) {
return null;
}

这个文件不存在;

public static Wallet importWalletFromPrivateKey(Metadata metadata, String prvKeyHex, String password, boolean overwrite) {
IMTKeystore keystore = V3Keystore.create(metadata, password, prvKeyHex);
Wallet wallet = flushWallet(keystore, overwrite);
Identity.getCurrentIdentity().addWallet(wallet);
return wallet;
}

然后

Identity.getCurrentIdentity().addWallet(wallet); 这个就空指针了,怎么初始化这个 identity.json?

谢谢!!!

Why export PrivateKey of BITCOIN Error

because "HDMnemonicKeystore" to create BITCOIN
but export PrivateKey have:

public String exportPrivateKey(String password) {
if (keystore instanceof V3Keystore || keystore instanceof V3MnemonicKeystore) {
byte[] decrypted = keystore.decryptCiphertext(password);
if (keystore.getMetadata().getSource().equals(Metadata.FROM_WIF)) {
return new String(decrypted);
} else {
return NumericUtil.bytesToHex(decrypted);
}
}
throw new TokenException(Messages.ILLEGAL_OPERATION);
}

NO "HDMnemonicKeystore" and throw TokenException.

so how to export BITCION PrivateKey?

导出BTC钱包私钥报错,

因为在创建BTC钱包的时候是用的HDMnemonicKeystore
而在到处私钥的时候有做过滤:
public String exportPrivateKey(String password) {
if (keystore instanceof V3Keystore || keystore instanceof V3MnemonicKeystore) {
byte[] decrypted = keystore.decryptCiphertext(password);
if (keystore.getMetadata().getSource().equals(Metadata.FROM_WIF)) {
return new String(decrypted);
} else {
return NumericUtil.bytesToHex(decrypted);
}
}
throw new TokenException(Messages.ILLEGAL_OPERATION);
}

也就是说 只要不是V3Keystore 或者 V3MnemonicKeystore 类型的都会抛TokenException

所以想问下,如何导出BTC钱包私钥?????

Code contain sample code

the code HDMnemonicKeystore has a warning

// !!! Don't use this key in production !!!
  public static String XPubCommonKey128 = "B888D25EC8C12BD5043777B1AC49F872";
  public static String XPubCommonIv = "9C0C30889CBCC5E01AB5B2BB88715799";

so what can we use in product?

获取当前身份一直报错

com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class org.consenlabs.tokencore.foundation.crypto.Crypto]: missing type id property 'kdf' (for POJO property 'crypto')
at [Source: (File); line: 1, column: 306] (through reference chain: org.consenlabs.tokencore.wallet.keystore.IdentityKeystore["crypto"])

关于 Keystore 的加密与存储

在 imTome 公众号看到这样的描述:
加密后的 Keystore(私钥存储文件) 存储在沙盒文件系统。只有私钥签名的场景下 Keystore 才会配合密码的输入解开得到对应私钥。

请问:

1、我在电脑上跑了下测试方法,发现 Keystore 的 json 文件是明文存储,并没有加密,是需要调用某个加密方法吗?

2、Keystore 的存储位置不是通过 KeystoreStorage 这个接口设置的吗?沙盒文件系统 是什么意思?指的是的 Android 的私有目录吗?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.