官方给出的demo可见:https://github.com/blockchain-jd-com/jdchain-starter.git
1. 注册用户
package com.hello.jdchain;
import com.jd.blockchain.crypto.HashDigest;
import com.jd.blockchain.crypto.KeyGenUtils;
import com.jd.blockchain.crypto.PrivKey;
import com.jd.blockchain.crypto.PubKey;
import com.jd.blockchain.ledger.BlockchainKeyGenerator;
import com.jd.blockchain.ledger.BlockchainKeypair;
import com.jd.blockchain.ledger.PreparedTransaction;
import com.jd.blockchain.ledger.TransactionTemplate;
import com.jd.blockchain.sdk.BlockchainService;
import com.jd.blockchain.sdk.client.GatewayServiceFactory;
public class App {
public static final String GW_IPADDR = "192.168.1.1";
public static final int GW_PORT = 8090;
/**
* peer节点的公钥
*/
public static final String PUB_KEY = "3snPdw7i7PbvsHumxdGnv8GHySqkfGsdfsdKEPobFQ1Pqgj1hnLUt72P";
/**
* peer节点私钥
*/
public static final String PRIV_KEY = "177gjsghLtEadqgot2JWdB97YbQJWiwNscRV34MUJsdfsdfsdfi9LysdwqjvEy9XgmXtvexz5pGb";
/**
* peer节点密码
*/
public static final String PASSWORD = "123456";
public static BlockchainKeypair adminKey;
public static BlockchainService blockchainService;
public static HashDigest ledgerHash;
public static BlockchainKeypair jdChainUser;
static{
//以peer节点上的用户
// 生成连接网关的账号
PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEY, PASSWORD);
PubKey pubKey = KeyGenUtils.decodePubKey(PUB_KEY);
adminKey = new BlockchainKeypair(pubKey, privKey);
// 连接网关
GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GW_IPADDR,
GW_PORT, false, adminKey);
// 获取网关对应的Service处理类
blockchainService = serviceFactory.getBlockchainService();
HashDigest[] ledgerHashs = blockchainService.getLedgerHashs();
// 获取当前账本Hash
ledgerHash = ledgerHashs[0];
}
/**
* 注册用户
*/
public static BlockchainKeypair registerUser(){
// 在本地定义注册账号的 TX;
TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash);
BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate();
System.out.println("user.getAddress().toBase58():" + user.getAddress().toBase58());
System.out.println("user.getAddress().toString():" + user.getAddress().toString());
System.out.println("user.getIdentity().getAddress().toBase58():" + user.getIdentity().getAddress().toBase58());
System.out.println("user.getIdentity().getAddress().toString():" + user.getIdentity().getAddress().toString());
System.out.println("user.getIdentity().getPubKey().toBase58():" + user.getIdentity().getPubKey().toBase58());
System.out.println("user.getIdentity().getPubKey().toString():" + user.getIdentity().getPubKey().toString());
System.out.println("user.getIdentity().getPubKey().toUTF8String():" + user.getIdentity().getPubKey().toUTF8String());
txTemp.users().register(user.getIdentity());
// TX 准备就绪;
PreparedTransaction prepTx = txTemp.prepare();
prepTx.sign(adminKey);
// 提交交易;
prepTx.commit();
return user;
}
public static void main(String[] args) {
//测试注册用户
jdChainUser = registerUser();
//测试注册数据账号
}
}
2. 注册数据账户
/**
* 注册数据账户
* @return
*/
public static BlockchainKeypair registerDataAccount(){
TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash);
//采用KeyGenerator来生成BlockchainKeypair;
BlockchainKeypair dataAccount = BlockchainKeyGenerator.getInstance().generate();
txTemp.dataAccounts().register(dataAccount.getIdentity());
txTemp.dataAccount(dataAccount.getAddress()).setText("address","wuhan",-1);
//add some data for retrieve;
strDataAccount = dataAccount.getAddress().toBase58();
System.out.println("strDataAccount:" + strDataAccount);
System.out.println("current dataAccount= "+ dataAccount.getAddress());
// txTemp.dataAccount(dataAccount.getAddress()).setText("cc-fin01-01","{\"dest\":\"KA001\",\"id\":\"cc-fin01-01\",\"items\":\"FIN001|5000\",\"source\":\"FIN001\"}",-1);
// txTemp.dataAccount(dataAccount.getAddress()).setText("cc-fin02-01","{\"dest\":\"KA001\",\"id\":\"cc-fin02-01\",\"items\":\"FIN002|2000\",\"source\":\"FIN002\"}",-1);
// TX 准备就绪
PreparedTransaction prepTx = txTemp.prepare();
prepTx.sign(adminKey);
prepTx.commit();
return dataAccount;
}
3. 写入数据
/**
* 写入数据
* dataAccount 数据账户地址
*/
public static void writeData(String dataAccount){
// 在本地定义注册账号的 TX;
TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash);
long startTime = System.currentTimeMillis();
for(int i=0;i<10;i++){
//add some data for retrieve;
txTemp.dataAccount(dataAccount).setText(i+"", "{\"dest\":\"KA001\",\"id\":\"" + i + "\",\"items\":\"FIN001|5000\",\"source\":\"FIN001\"}",-1);
}
long endTime = System.currentTimeMillis();
System.out.println("cost " + (endTime - startTime)/1000L + " s");
// TX 准备就绪
PreparedTransaction prepTx = txTemp.prepare();
prepTx.sign(adminKey);
// 提交交易;
prepTx.commit();
}
4. 读取数据
/**
* 查询数据
* @param dataAccount 数据账户地址
*/
public static void getData(String dataAccount) {
// 查询区块信息;
// 区块高度;
long ledgerNumber = blockchainService.getLedger(ledgerHash).getLatestBlockHeight();
// 最新区块;
LedgerBlock latestBlock = blockchainService.getBlock(ledgerHash, ledgerNumber);
// 区块中的交易的数量;
long txCount = blockchainService.getTransactionCount(ledgerHash, latestBlock.getHash());
// 获取交易列表;
LedgerTransaction[] txList = blockchainService.getTransactions(ledgerHash, ledgerNumber, 0, 100);
// 遍历交易列表
for (LedgerTransaction ledgerTransaction : txList) {
TransactionContent txContent = ledgerTransaction.getTransactionContent();
Operation[] operations = txContent.getOperations();
if (operations != null && operations.length > 0) {
for (Operation operation : operations) {
operation = ClientResolveUtil.read(operation);
// 操作类型:数据账户注册操作
if (operation instanceof DataAccountRegisterOperation) {
DataAccountRegisterOperation daro = (DataAccountRegisterOperation) operation;
BlockchainIdentity blockchainIdentity = daro.getAccountID();
}
// 操作类型:用户注册操作
else if (operation instanceof UserRegisterOperation) {
UserRegisterOperation uro = (UserRegisterOperation) operation;
BlockchainIdentity blockchainIdentity = uro.getUserID();
}
// 操作类型:账本注册操作
else if (operation instanceof LedgerInitOperation) {
LedgerInitOperation ledgerInitOperation = (LedgerInitOperation)operation;
LedgerInitSetting ledgerInitSetting = ledgerInitOperation.getInitSetting();
ParticipantNode[] participantNodes = ledgerInitSetting.getConsensusParticipants();
}
// 操作类型:合约发布操作
else if (operation instanceof ContractCodeDeployOperation) {
ContractCodeDeployOperation ccdo = (ContractCodeDeployOperation) operation;
BlockchainIdentity blockchainIdentity = ccdo.getContractID();
}
// 操作类型:合约执行操作
else if (operation instanceof ContractEventSendOperation) {
ContractEventSendOperation ceso = (ContractEventSendOperation) operation;
}
// 操作类型:KV存储操作
else if (operation instanceof DataAccountKVSetOperation) {
DataAccountKVSetOperation.KVWriteEntry[] kvWriteEntries =
((DataAccountKVSetOperation) operation).getWriteSet();
if (kvWriteEntries != null && kvWriteEntries.length > 0) {
for (DataAccountKVSetOperation.KVWriteEntry kvWriteEntry : kvWriteEntries) {
BytesValue bytesValue = kvWriteEntry.getValue();
DataType dataType = bytesValue.getType();
Object showVal = ClientResolveUtil.readValueByBytesValue(bytesValue);
System.out.println("writeSet.key=" + kvWriteEntry.getKey());
System.out.println("writeSet.value=" + showVal);
System.out.println("writeSet.type=" + dataType);
System.out.println("writeSet.version=" + kvWriteEntry.getExpectedVersion());
}
}
}
}
}
}
//根据交易的 hash 获得交易;注:客户端生成 PrepareTransaction 时得到交易hash;
HashDigest txHash = txList[0].getTransactionContent().getHash();
// Transaction tx = blockchainService.getTransactionByContentHash(ledgerHash, txHash);
// String[] objKeys = new String[] { "x001", "x002" };
// KVDataEntry[] kvData = blockchainService.getDataEntries(ledgerHash, commerceAccount, objKeys);
// 获取数据账户下所有的KV列表
KVDataEntry[] kvData = blockchainService.getDataEntries(ledgerHash, dataAccount, 0, 100);
if (kvData != null && kvData.length > 0) {
for (KVDataEntry kvDatum : kvData) {
System.out.println("kvData.key=" + kvDatum.getKey());
System.out.println("kvData.version=" + kvDatum.getVersion());
System.out.println("kvData.type=" + kvDatum.getType());
System.out.println("kvData.value=" + kvDatum.getValue());
}
}
}