我使用命令行创建了超级结构网络。现在我想从java sdk执行chaincode事务,任何人都可以共享从java调用链代码的步骤。
答案 0 :(得分:0)
假设(假设)您在命令行中从BYFN网络(http://hyperledger-fabric.readthedocs.io/en/release-1.1/build_network.html)启动了第一个网络, 您可以使用 Fabric Java SDK 依赖关系来访问,查询和调用链代码。 请参阅此代码:
public class Test {
final HFClient client = HFClient.createNewInstance();
Channel channel;
QueryByChaincodeRequest qpr;
void setupCryptoMaterialsForClient() throws CryptoException,
InvalidArgumentException {
// Set default crypto suite for HF client
client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
client.setUserContext(new User() {
public String getName() {
return "PeerAdmin";
}
public Set<String> getRoles() {
return null;
}
public String getAccount() {
return null;
}
public String getAffiliation() {
return null;
}
public Enrollment getEnrollment() {
return new Enrollment() {
public PrivateKey getKey() {
PrivateKey privateKey = null;
try {
File privateKeyFile = findFileSk("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore");
privateKey = getPrivateKeyFromBytes(IOUtils
.toByteArray(new FileInputStream(
privateKeyFile)));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return privateKey;
}
public String getCert() {
String certificate = null;
try {
File certificateFile = new File(
"D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem");
certificate = new String(IOUtils
.toByteArray(new FileInputStream(
certificateFile)), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return certificate;
}
};
}
public String getMspId() {
return "Org1MSP";
}
});
}
static File findFileSk(String directorys) {
File directory = new File(directorys);
File[] matches = directory.listFiles((dir, name) -> name
.endsWith("_sk"));
if (null == matches) {
throw new RuntimeException(format(
"Matches returned null does %s directory exist?", directory
.getAbsoluteFile().getName()));
}
if (matches.length != 1) {
throw new RuntimeException(format(
"Expected in %s only 1 sk file but found %d", directory
.getAbsoluteFile().getName(), matches.length));
}
return matches[0];
}
static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException,
NoSuchProviderException, NoSuchAlgorithmException,
InvalidKeySpecException {
final Reader pemReader = new StringReader(new String(data));
final PrivateKeyInfo pemPair;
try (PEMParser pemParser = new PEMParser(pemReader)) {
pemPair = (PrivateKeyInfo) pemParser.readObject();
}
PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(
BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);
return privateKey;
}
void createChannel() throws InvalidArgumentException, TransactionException, ProposalException {
channel = client.newChannel("mychannel");
Properties ordererProperties = new Properties();
ordererProperties
.setProperty(
"pemFile",
"D:/FabricCert/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt");
ordererProperties.setProperty("trustServerCertificate", "true"); // testing
// environment
// only
// NOT
// FOR
// PRODUCTION!
ordererProperties
.setProperty("hostnameOverride", "orderer.example.com");
ordererProperties.setProperty("sslProvider", "openSSL");
ordererProperties.setProperty("negotiationType", "TLS");
ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime",
new Object[] { 5L, TimeUnit.MINUTES });
ordererProperties.put(
"grpc.NettyChannelBuilderOption.keepAliveTimeout",
new Object[] { 8L, TimeUnit.SECONDS });
channel.addOrderer(client.newOrderer("orderer.example.com",
"grpcs://localhost:7050", ordererProperties)); // use the network orderer container URL
Properties peerProperties = new Properties();
peerProperties.setProperty("pemFile",
"D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt");
peerProperties.setProperty("trustServerCertificate", "true"); // testing // // PRODUCTION!
peerProperties.setProperty("hostnameOverride",
"peer0.org1.example.com");
peerProperties.setProperty("sslProvider", "openSSL");
peerProperties.setProperty("negotiationType", "TLS");
peerProperties
.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize",
9000000);
channel.addPeer(client.newPeer("peer0.org1.example.com",
"grpcs://localhost:7051",peerProperties)); // use the network peer container URL
channel.initialize();
}
void queryChain() throws InvalidArgumentException, ProposalException, ChaincodeEndorsementPolicyParseException, IOException {
// get channel instance from client
Channel channel2 = client.getChannel("mychannel");
int blocksize = (int) channel2.queryBlockchainInfo().getHeight();
System.out.println("NO of Blocks: "+blocksize);
// create chaincode request
qpr = client.newQueryProposalRequest();
// build cc id providing the chaincode name. Version is omitted here.
ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("mycc")
.build();
qpr.setChaincodeID(fabcarCCId);
// CC function to be called.
qpr.setFcn("query");
qpr.setArgs(new String[] { "a" });
Collection<ProposalResponse> res = channel2.queryByChaincode(qpr,channel2.getPeers());
// display response
for (ProposalResponse pres : res) {
String stringResponse = new String(
pres.getChaincodeActionResponsePayload());
System.out.println("Query Response from Peer " + pres.getPeer().getName() + ":" +stringResponse);
}
}
void invokeChain() throws InvalidArgumentException, ProposalException, ChaincodeEndorsementPolicyParseException, IOException {
Channel channel = client.getChannel("mychannel");
TransactionProposalRequest req = client.newTransactionProposalRequest();
ChaincodeID cid = ChaincodeID.newBuilder().setName("mycc").build();
req.setChaincodeID(cid);
req.setFcn("invoke");
req.setArgs(new String[] { "b", "a", "5" });
Collection<ProposalResponse> resps = channel
.sendTransactionProposal(req);
channel.sendTransaction(resps);
System.out.println(resps.iterator().next().getMessage());
}
public static void main(String args[]) throws Exception {
Test t = new Test();
t.setupCryptoMaterialsForClient();
t.createChannel();
t.invokeChain();
//t.queryChain(); For querying
}
}
确保您获取并访问适当的证书以进行注册和容器访问。加密材料将在crypto-config.yaml文件可用的文件夹中生成