TRX(波场)JAVA离线签名

前言

        在做离线钱包的过程中,波场是有资料,但是资料最坑的一个币,不过还有最终顺利完成开发。

资料

        https://www.jianshu.com/p/275036a09be3   里面是别人收集的TRX相关信息。

官方Demo

        https://github.com/tronprotocol/wallet-cli/blob/master/src/main/java/org/tron/demo/TransactionSignDemo.java

说明

        因为我们是离线钱包,一次我们没用RPC的方式去获取块信息,是现在业务端获取到节点信息,在到离线的环境签名,再去广播。如果用本地节点或者超级节点RPC的方式的话,就用官方demo就好了。不过我们直接是用的api接口获取的数据,所有出来了一些问题。
        首先构建https://github.com/tronprotocol/wallet-cli项目,成功后拿到/build/libs/wallet-1.0-SNAPSHOT.jar,然后就开启你的代码之旅吧。

源码

import com.alibaba.fastjson.JSON;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.Map;

import org.bouncycastle.util.encoders.Hex;
import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Sha256Hash;
import org.tron.common.utils.ByteArray;
import org.tron.core.exception.CancelException;
import org.tron.protos.Contract;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.Transaction;
import org.tron.walletserver.WalletApi;

public class TransactionSignDemo {

	public static Transaction createTransaction(byte[] from, byte[] to, long amount,long blockTimestamp,long blockHeight,byte[] blockHash) {
		Transaction.Builder transactionBuilder = Transaction.newBuilder();
		//Block newestBlock = WalletApi.getBlock(-1);

		
		Transaction.Contract.Builder contractBuilder = Transaction.Contract.newBuilder();
		Contract.TransferContract.Builder transferContractBuilder = Contract.TransferContract.newBuilder();
		transferContractBuilder.setAmount(amount);
		ByteString bsTo = ByteString.copyFrom(to);
		ByteString bsOwner = ByteString.copyFrom(from);
		transferContractBuilder.setToAddress(bsTo);
		transferContractBuilder.setOwnerAddress(bsOwner);
		try {
			Any any = Any.pack(transferContractBuilder.build());
			contractBuilder.setParameter(any);
		} catch (Exception e) {
			return null;
		}
		contractBuilder.setType(Transaction.Contract.ContractType.TransferContract);
		transactionBuilder.getRawDataBuilder().addContract(contractBuilder).setTimestamp(System.currentTimeMillis())
				.setExpiration(blockTimestamp + 10 * 60 * 60 * 1000);
		Transaction transaction = transactionBuilder.build();
		Transaction refTransaction = setReference(transaction, blockHeight,blockHash);
		return refTransaction;
	}
	
	public static Transaction setReference(Transaction transaction, long blockHeight,byte[] blockHash) {
		//long blockHeight = newestBlock.getBlockHeader().getRawData().getNumber();
		//byte[] blockHash = getBlockHash(newestBlock).getBytes();
		byte[] refBlockNum = ByteArray.fromLong(blockHeight);
		Transaction.raw rawData = transaction.getRawData().toBuilder()
				.setRefBlockHash(ByteString.copyFrom(ByteArray.subArray(blockHash, 8, 16)))
				.setRefBlockBytes(ByteString.copyFrom(ByteArray.subArray(refBlockNum, 6, 8))).build();
		return transaction.toBuilder().setRawData(rawData).build();
	}
	
	public static Sha256Hash getBlockHash(Block block) {
		return Sha256Hash.of(block.getBlockHeader().getRawData().toByteArray());
	}

	public static String getTransactionHash(Transaction transaction) {
		String txid = ByteArray.toHexString(Sha256Hash.hash(transaction.getRawData().toByteArray()));
		return txid;
	}
	private static byte[] signTransaction2Byte(byte[] transaction, byte[] privateKey)
			throws InvalidProtocolBufferException {
		ECKey ecKey = ECKey.fromPrivate(privateKey);
		Transaction transaction1 = Transaction.parseFrom(transaction);
		byte[] rawdata = transaction1.getRawData().toByteArray();
		byte[] hash = Sha256Hash.hash(rawdata);
		byte[] sign = ecKey.sign(hash).toByteArray();
		return transaction1.toBuilder().addSignature(ByteString.copyFrom(sign)).build().toByteArray();
	}

	public static void main(String[] args) throws InvalidProtocolBufferException, CancelException {
		String privateStr = "你的私钥";
		byte[] privateBytes = ByteArray.fromHexString(privateStr);
		ECKey ecKey = ECKey.fromPrivate(privateBytes);
		byte[] from = ecKey.getAddress();
		byte[] to = WalletApi.decodeFromBase58Check("地址");
		long amount = 100_000_000L; 
		
		String blockStr = HttpUtil.get("https://apilist.tronscan.org/api/block/latest");
		Map blockInfo=JSON.parseObject(blockStr);
		System.out.println(blockInfo.toString());
		Long blockTimestamp = Long.parseLong(blockInfo.get("timestamp").toString());
		Long blockHeight = Long.parseLong(blockInfo.get("number").toString());
		
		byte[] blockHash = Hex.decode(blockInfo.get("hash").toString());
		//开始看官方demo改写的blockHashd,但是错的,签名没的问题,但是广播就报错TAPOS_ERROR,说块不在链上。 	
		byte[] blockHash2=Sha256Hash.of(blockInfo.get("hash").toString().getBytes()).getBytes();
		System.out.println("===blockHash:"+ByteArray.toHexString(blockHash));
		System.out.println("===blockHash2:"+ByteArray.toHexString(blockHash2));
		
		Transaction transaction = createTransaction(from, to, amount, blockTimestamp, blockHeight, blockHash);
		byte[] transactionBytes = transaction.toByteArray();
		byte[] transaction4 = signTransaction2Byte(transactionBytes, privateBytes);
		System.out.println("transaction4 ::::: " + ByteArray.toHexString(transaction4));
		
		//广播的URL:https://apilist.tronscan.org/api/broadcast
	}
}

以上就是我们签名的demo了,和原来的改变不大,但是却一度致命,开始的时候一直广播报错:TAPOS_ERROR,看了下这个错是块不在链上,但是我们set又get出来,都是正确的块hash值。而源码中有没的Block的源码,所以一度不知道怎么解决。还好后面发现Hex.decode()方法转的byte的后与打印交易的Transaction.toString()方法内容一样,于是广播,结果成功了。

这个只是一个demo,至于怎么获取私钥,怎么实现离线的,根据自己业务场景自己衡量哈。

转载于:https://my.oschina.net/bianxin/blog/3069007

你可能感兴趣的:(TRX(波场)JAVA离线签名)