首页 > 其他分享 >区块链钱包-android篇

区块链钱包-android篇

时间:2024-03-08 18:01:50浏览次数:20  
标签:return String wallet 钱包 mECKey android 区块 public


1:使用Protocol Buffers
 首先根目录gradle中添加依赖:

classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.3"

然后项目文件中添加plugin,添加依赖包:

apply plugin: 'com.google.protobuf'

protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.6.1'
}
plugins {
javalite {
artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
}
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.17.1'
}
}
generateProtoTasks {
all().each { task ->
task.plugins {
javalite {}
grpc {
// Options added to --grpc_out
option 'lite'
}
}
}
}
configurations {
all*.exclude group: 'com.android.support', module: 'support-v13'
}
}

dependencies {
api 'io.grpc:grpc-okhttp:1.17.1'
api 'io.grpc:grpc-protobuf-lite:1.17.1'
api 'io.grpc:grpc-stub:1.17.1'
}
 最后main下添加proto路径,添加proto文件;

2:tron基础类
       关于tron的基础类,我整理了个lib,使用时直接导入lib即可。

主要包括wallet钱包类,管理类等内容。

这里我主要贴出wallet的代码

package org.tron.walletserver;

import android.os.Build;
import android.support.annotation.RequiresApi;

import org.tron.common.crypto.ECKey;
import org.tron.common.utils.Utils;

import java.math.BigInteger;

public class Wallet {
private ECKey mECKey = null;

private boolean isWatchOnly = false;
private boolean isColdWallet = false;
private String walletName = "";
private String encPassword = "";
private String address = "";
private byte[] encPrivateKey;
private byte[] publicKey;


public Wallet() {
}

public Wallet(boolean generateECKey) {
    if(generateECKey) {
        mECKey = new ECKey(Utils.getRandom());
    }
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public Wallet(String privateKey) {
    setPrivateKey(privateKey);
}

public boolean isOpen() {
    return mECKey != null && mECKey.getPrivKeyBytes() != null;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public boolean open(String password) {
    if(encPrivateKey != null) {
        setPrivateKey(AddressUtils.decryptPrivateKey(encPrivateKey, password));
        return isOpen();
    } else {
        return false;
    }
}

public byte[] getPublicKey() {
    return mECKey != null ? mECKey.getPubKey() : publicKey;
}

public void setPublicKey(byte[] publicKey) {
    this.publicKey = publicKey;
}

public byte[] getPrivateKey() {
    return mECKey != null ? mECKey.getPrivKeyBytes() : null;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setPrivateKey(String privateKey) {
    if(privateKey != null && !privateKey.isEmpty()) {
        ECKey tempKey = null;
        try {
            BigInteger priK = new BigInteger(privateKey, 16);
            tempKey = ECKey.fromPrivate(priK);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        mECKey = tempKey;
    } else {
        mECKey = null;
    }
}


public boolean isWatchOnly() {
    return isWatchOnly;
}

public void setWatchOnly(boolean watchOnly) {
    isWatchOnly = watchOnly;
}

public boolean isColdWallet() {
    return isColdWallet;
}

public void setColdWallet(boolean coldWallet) {
    isColdWallet = coldWallet;
}

public String getWalletName() {
    return walletName;
}

public void setWalletName(String walletName) {
    this.walletName = walletName;
}

public String getEncryptedPassword() {
    return encPassword;
}

public void setEncryptedPassword(String password) {
    this.encPassword = password;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String getAddress() {
    if(mECKey != null) {
        return AddressUtils.encode58Check(mECKey.getAddress());
    }
    else if (publicKey != null){
        return AddressUtils.encode58Check(ECKey.fromPublicOnly(publicKey).getAddress());
    } else {
        return address;
    }
}

public void setAddress(String address) {
    this.address = address;
}

public ECKey getECKey() {
    return mECKey;
}

public byte[] getEncryptedPrivateKey() {
    return encPrivateKey;
}

public void setEncryptedPrivateKey(byte[] encPrivateKey) {
    this.encPrivateKey = encPrivateKey;
}

}
3:导入钱包

其实就一步操作,就是根据私钥 创建wallet对象。

//根据私钥创建钱包
Wallet wallet = new Wallet(privateKey);
//设置钱包名称,我这里不需要就设置成钱包地址了。
wallet.setWalletName(wallet.getAddress());
//项目存储导入的钱包
TronManager.storeTron(wallet);

4:创建钱包
       创建钱包需要两个参数,一个是钱包名称,一个是设置的密码,钱包名称还好,重要的是密码,因为转账,导出私钥助记词等信息时,都是需要密码验证的。

Wallet wallet = new Wallet(true);
wallet.setWalletName(name);
WalletManager.store(this,wallet, pwd);
store方法是使用SharedPreferences存储当前钱包的信息,其中我们可以通过密码来获取wallet的eckey从而得到钱包的公钥和私钥。

5:钱包信息
      这里主要用到项目中grpcClient类和walletmanager类。

这个类主要封装了对应的网络请求以及钱包管理

grpcClient类的initGrpc需要传入对应的fullnode和soliditynode,这个可以去下面的地址去选择,

documentation/Official_Public_Node.md at master · tronprotocol/documentation · GitHub

查询账户需要用到账户的地址:

Protocol.Account account = WalletManager.queryAccount(address, false);
GrpcAPI.AccountNetMessage accountNetMessage = WalletManager.getAccountNet(address);
GrpcAPI.AccountResourceMessage accountResMessage = WalletManager.getAccountRes(address);
  account可以查询balance和FrozenList;

accountNetMessage 可以查询账户的带宽信息。

具体代码如下:

double balance=mAccount.getBalance()/1000000.0d;
binding.tvWalletAccount.setText(balance+"");

        long frozenTotal = 0;
        for(Protocol.Account.Frozen frozen : mAccount.getFrozenList()) {
            frozenTotal += frozen.getFrozenBalance();
        }
        binding.tvWalletTronWeight.setText((frozenTotal/1000000)+"");

        GrpcAPI.AccountNetMessage accountNetMessage = TronUtil.getAccountNet(getActivity(), wallet.getWalletName());

        long bandwidth = accountNetMessage.getNetLimit() + accountNetMessage.getFreeNetLimit();
        long bandwidthUsed = accountNetMessage.getNetUsed()+accountNetMessage.getFreeNetUsed();
        long bandwidthLeft = bandwidth - bandwidthUsed;

        binding.tvWalletBandwidth.setText(bandwidthLeft+"");

6:转账

byte[] toRaw;
try {
toRaw = WalletManager.decodeFromBase58Check(sendAddress);
} catch (IllegalArgumentException ignored) {
Toast.makeText(this,"请输入一个有效地址",Toast.LENGTH_SHORT).show();
return;
}

    double amount=Double.parseDouble(sendAmount);
    Contract.TransferContract contract = WalletManager.createTransferContract(toRaw, WalletManager.decodeFromBase58Check(mWallet.getAddress()), (long) (amount * 1000000.0d));
    Protocol.Transaction transaction = WalletManager.createTransaction4Transfer(contract);
    byte[]  mTransactionBytes = transaction.toByteArray();
    try {
        mTransactionUnsigned = Protocol.Transaction.parseFrom(mTransactionBytes);
    } catch (InvalidProtocolBufferException e) {
        e.printStackTrace();
    }

根据上面的代码,获取到mTransactionUnsigned ,然后输入密码校验密码并获取到wallet的eckey。

设置时间戳,交易签名。

mTransactionSigned = TransactionUtils.setTimestamp(mTransactionUnsigned);
mTransactionSigned = TransactionUtils.sign(mTransactionSigned, mWallet.getECKey());
WalletManager.broadcastTransaction(mTransactionSigned);
最后一步是广播交易。

具体的代码可查看git。

git地址

本文由博客一文多发平台 OpenWrite 发布!

标签:return,String,wallet,钱包,mECKey,android,区块,public
From: https://www.cnblogs.com/zhjing/p/18061560

相关文章

  • Android 二维码相关(二)
    Android二维码相关(二)本篇文章继续讲述下如何使用zxing解析二维码图片,获取内容.1:创建RGBLuminanceSource对象.首先获取二维码图片的bitmap对象.Bitmapbitmap=BitmapFactory.decodeResource(getResources(),R.mipmap.test);根据getPixels()获取位图指定区域的像素颜......
  • Android 二维码相关(一)
    Android二维码相关(一)本篇文章主要记录下android下使用zxing来创建二维码.1:导入依赖api"com.google.zxing:core:3.5.1"2:创建二维码创建QRCodeWriter对象QRCodeWriterqrCodeWriter=newQRCodeWriter(); 将文本内容转换成BitMatrixBitMatrixencode=qrCod......
  • 解决 Android studio Connect to 127.0.0.1:[/127.0.0.1] failed: Connection refused
    前言由于代理变更,androidstudio会有一系列报错,其中一个是Connectto127.0.0.1:xxxxxx[/127.0.0.1]failed:Connectionrefused网上答案大都太片面了,无法完全解决问题,这里列举出四个可能的原因,希望对大家有用问题如下建议一下四种方案都尝试下,我相信总有一种能......
  • Android mount: bad /etc/fstab: No such file or directory
    没有root权限的原因,需要su切换到root用户https://github.com/termux/termux-packages/issues/7256 I/OerrorRMX1901CN:/#mount/dev/block/by-name/abl/mnt/mntablmount:'/dev/block/by-name/abl'->'/mnt/mntabl':I/Oerrorablxbl都会出现I/Oerror,不知道什么原因......
  • Android hexedit toybox tcsetattr /dev/pts/0: Permission denied
    cas:/$/data/local/tmp/toybox-aarch64hexedit/data/local/tmp/tree.statichexedit:tcsetattr/dev/pts/0:Permissiondenied 好像是不能用tcsetattr,selinux会拒绝 cas:/$ls-l/dev/ptsls:/dev/pts:Permissiondenied https://blog.zhanghai.me/fixing-line-e......
  • Android开发学习之路01
    今日跟着一个人进行了Androidstudio上创建数据库和数据表的联系,这应该是老师留的作业中,进行数据库的连接。原文链接:https://blog.csdn.net/fjh_xx/article/details/131404230一.前言二.SQLite数据库介绍1.什么是SQLite数据库2.特点3.SQLite操作API4.SQLite数据类型三.S......
  • android studio
    避坑:1.此处替换路径下载地址:https://mirrors.cloud.tencent.com/gradle/2.D:\app\gradle-6.7.1\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-compiler-embeddable\1.8.10\2a38b258da57285fb187fc329f7374c0751576af此处下载对应文件后将原文件替换注意修改......
  • Android Room DataBase
     AndroidRoomDataBase(一)https://blog.csdn.net/l_o_s/article/details/79346426AndroidRoomDataBase(二)https://blog.csdn.net/l_o_s/article/details/79348701AndroidRoomDataBase(三)https://blog.csdn.net/l_o_s/article/details/79388408使用AndroidJetpack......
  • Android.mk 使用 dagger2
    #Managesuseofannotationprocessors.##Atthemomentboththe-processorpathandthe-processor#flagsmustbespecifiedinordertouseannotationprocessors#asacodeindexingtoolthatwrapsjavacdoesn'tasyetsupport#thesamebehaviouras......
  • 同态加密+区块链,在大健康数据隐私保护中的应用
    PrimiHub一款由密码学专家团队打造的开源隐私计算平台,专注于分享数据安全、密码学、联邦学习、同态加密等隐私计算领域的技术和内容。近几年,越来越多的隐私计算技术被用于解决临床和研究数据共享中的隐私和安全问题。当然,对这些技术的法律评估主要集中在合规性方面,尤其是在欧......