区块链钱包-android篇

这篇具有很好参考价值的文章主要介绍了区块链钱包-android篇。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


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 发布!文章来源地址https://www.toymoban.com/news/detail-837809.html

到了这里,关于区块链钱包-android篇的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 区块链钱包开发(Android篇)

    On-chain 给一个钱包地址发送数字货币, 这笔交易在全网广播、被确认、被打包进区块。这是发生在链上的,被称为on-chain交易。on-chain钱包需要自己保管私钥。 Off-chain 相对于on-chain交易是off-chain交易。通常,通过交易所进行的交易是off-chain的,本人并没有私钥。私钥在交易所,

    2024年04月26日
    浏览(32)
  • 区块链钱包开发(Android篇),Android程序员必会

    布隆过滤器(Bloom Filter):过滤掉那些不包含有目标地址的交易信息,这一步能避免掉大量不相关的数据下载。 创建区块链 //创建区块链文件 File blockChainFile = new File(getDir(“blockstore”, Context.MODE_PRIVATE), “blockchain”); //创建SPVBlockStore,管理区块数据 blockStore = new SPVBlockStore(Co

    2024年04月09日
    浏览(70)
  • 区块链钱包开发(Android篇),深入解析android核心组件和应用框架

    作用: 1、备份更容易。按照比特币的原则,尽量不要使用同一个地址,一个地址只使用一次,这样会导致频繁备份钱包。HD钱包只需要在创建时保存主密钥,通过主密钥可以派生出所有的子密钥。 2、私钥离线更安全。主私钥离线存储,主公钥在线使用,通过主公钥可以派生

    2024年03月24日
    浏览(37)
  • 基于Java的Android区块链钱包开发(ETH篇)

    首先要生成12个助记词,区块链开发之生成12个助记词

    2024年02月11日
    浏览(51)
  • 如何在Windows、Mac和Linux操作系统上安装Protocol Buffers(protobuf)编译器

    🌷🍁 博主猫头虎 带您 Go to New World.✨🍁 🦄 博客首页——猫头虎的博客🎐 🐳《面试题大全专栏》 文章图文并茂🦕生动形象🦖简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍专栏》学会IDEA常用操作,工作效率翻倍~💐 🌊 《100天精通Golang(基础入门篇)》学会Golang语言

    2024年02月11日
    浏览(55)
  • 【Java万花筒】选择最适合您的数据序列化格式:比较 Avro、Protocol Buffers、JSON、XML、MessagePack和BSON

    在当今数据驱动的世界中,高效地处理和传输数据变得至关重要。选择合适的数据序列化格式对于数据存储、通信和处理的性能至关重要。本文将介绍并比较几种常用的数据序列化格式,包括Apache Avro、Protocol Buffers、JSON、XML、MessagePack和BSON。通过了解它们的概述、特点、应用

    2024年02月20日
    浏览(41)
  • 手把手教你使用Java生成助记词、私钥、地址|Java区块链钱包生成助记词、地址

    在spring boot 项目中的 pom.xml文件中加入需要的依赖 可见恢复的地址和我们生成地址一样。

    2024年02月11日
    浏览(40)
  • Golang区块链钱包_go语言钱包

    Golang区块链钱包的特点 Golang区块链钱包具有以下几个特点: 1. 高性能 Golang是一种编译型语言,具有快速的执行速度和较低的内存消耗。这使得Golang区块链钱包在处理大规模交易数据时表现出色,能够满足高性能的需求。 2. 并发支持 Golang内置了轻量级线程——goroutine,以及

    2024年04月15日
    浏览(47)
  • Golang区块链钱包

    随着区块链技术的发展,数字货币的应用逐渐普及。而区块链钱包作为数字货币的一种必备工具,也变得越来越重要。Golang作为一种简单、高效的编程语言,被广泛运用于区块链领域。本文将介绍Golang区块链钱包的基本概念、特点和使用方法,帮助读者了解和使用这一工具。

    2024年02月04日
    浏览(32)
  • 【区块链】虚拟货币钱包

    目前区块链中虚拟货币的钱包种类和应用多样,按照私钥存储方式的不同,可以将钱包分为『 热钱包 』和『 冷钱包 』两大类型。 热钱包又称在线钱包,是指互联网能够访问用户私钥的钱包,一般通过电脑(交易平台)或者手机 APP 进行操作。 『 热钱包 』 优点 实用性高(

    2024年02月16日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包