fabric java sdk有发送createchannel2请求的代码吗
时间: 2024-01-21 15:16:40 浏览: 120
是的,以下是使用 Fabric Java SDK 发送 `createChannel` 请求的示例代码:
```java
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractEvent;
import org.hyperledger.fabric.gateway.DefaultContract;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Transaction;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallet.Identity;
import org.hyperledger.fabric.gateway.impl.GatewayImpl;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.ChannelConfiguration;
import org.hyperledger.fabric.sdk.ChannelConfiguration.ChannelConfigurationBuilder;
import org.hyperledger.fabric.sdk.ChannelConfiguration.SignaturePolicyEnvelope;
import org.hyperledger.fabric.sdk.ChannelConfiguration.TransactionBuilder;
import org.hyperledger.fabric.sdk.ChannelConfiguration.TransactionRequestType;
import org.hyperledger.fabric.sdk.ChannelConfigurationBuilderFactory;
import org.hyperledger.fabric.sdk.ChannelConfigurationSignature;
import org.hyperledger.fabric.sdk.ChannelConfigurationSignatureReader;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.NetworkConfig;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.ProposalResponse;
import org.hyperledger.fabric.sdk.SDKUtils;
import org.hyperledger.fabric.sdk.TransactionInfo;
import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.hyperledger.fabric.sdk.security.IdentityUser;
import org.hyperledger.fabric.sdk.security.keystore.KeyStore;
import org.hyperledger.fabric.sdk.security.keystore.KeyStoreFactory;
import org.hyperledger.fabric.sdk.security.keystore.KeyStoreReader;
import org.hyperledger.fabric.sdk.security.keystore.KeyStoreWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Properties;
public class CreateChannelSample {
private static final String CHANNEL_NAME = "mychannel";
private static final String CHANNEL_TX_PATH = "src/main/resources/channel-artifacts/channel.tx";
private static final String ORDERER_NAME = "orderer.example.com";
private static final String ORDERER_URL = "grpc://localhost:7050";
private static final String ORG_NAME = "Org1";
private static final String ORG_MSP_ID = "Org1MSP";
private static final String ORG_USER_NAME = "admin";
private static final String ORG_USER_PASSWORD = "adminpw";
private static final String ORG_PEER_NAME = "peer0.org1.example.com";
private static final String ORG_PEER_URL = "grpc://localhost:7051";
private static final String ORG_PEER_TLS_CERT_PATH = "src/main/resources/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt";
public static void main(String[] args) throws Exception {
// Load network configuration
NetworkConfig networkConfig = NetworkConfig.fromYamlFile(new File("src/main/resources/network.yaml"));
// Create wallet for user identity
Wallet wallet = Wallet.createFileSystemWallet(Paths.get("wallet"));
Identity identity = wallet.get("user1");
if (identity == null) {
Path certificatePath = Paths.get("src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/signcerts/User1@org1.example.com-cert.pem");
Path privateKeyPath = Paths.get("src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/keystore/priv_sk");
String certificate = new String(Files.readAllBytes(certificatePath));
PrivateKey privateKey = SDKUtils.getPrivateKeyFromPEM(new String(Files.readAllBytes(privateKeyPath)));
identity = IdentityUser.builder()
.name("user1")
.mspid(ORG_MSP_ID)
.certificate(certificate)
.privateKey(privateKey)
.build();
wallet.put("user1", identity);
}
// Create client
CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
KeyStore keyStore = KeyStoreFactory.getDefault().getKeyStore();
KeyStoreReader keyStoreReader = new KeyStoreReader(keyStore);
KeyStoreWriter keyStoreWriter = new KeyStoreWriter(keyStore);
keyStoreWriter.addPrivateKey("orderer", cryptoSuite.generatePrivateKey(), keyStoreReader.getCertificate("orderer"));
keyStoreWriter.addPrivateKey("peer", cryptoSuite.generatePrivateKey(), keyStoreReader.getCertificate("peer"));
keyStoreWriter.addPrivateKey("user", identity.getPrivateKey(), identity.getCertificate());
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
client.setUserContext((User) identity);
// Create channel configuration
ChannelConfigurationBuilder configBuilder = ChannelConfigurationBuilderFactory.newChannelConfigurationBuilder();
configBuilder.name(CHANNEL_NAME);
configBuilder.orderer(ORDERER_NAME, ORDERER_URL);
configBuilder.addPeer(ORG_PEER_NAME, ORG_PEER_URL, ORG_PEER_TLS_CERT_PATH);
configBuilder.addOrderer("orderer.example.com", "grpc://localhost:7050");
configBuilder.addOrganization(ORG_NAME, ORG_MSP_ID);
configBuilder.addAnchorPeer(ORG_NAME, "peer0.org1.example.com", "grpc://localhost:7051");
ChannelConfiguration configuration = configBuilder.build();
// Create channel configuration signature
SignaturePolicyEnvelope signaturePolicy = SignaturePolicyEnvelope.fromByteString(ByteString.copyFromUtf8("OR('Org1MSP.member')"));
TransactionBuilder transactionBuilder = TransactionBuilder.newBuilder();
transactionBuilder.setType(TransactionRequestType.CHANNEL_CONFIG);
transactionBuilder.setPayload(configuration.toByteString());
transactionBuilder.setChannelId(CHANNEL_NAME);
transactionBuilder.setSignaturePolicy(signaturePolicy);
transactionBuilder.setIdentity(identity);
transactionBuilder.setMSPID(ORG_MSP_ID);
byte[] transactionBytes = transactionBuilder.build().toByteArray();
byte[] signature = cryptoSuite.sign(identity.getPrivateKey(), transactionBytes);
ChannelConfigurationSignature configurationSignature = ChannelConfigurationSignature.newBuilder()
.setSignature(ByteString.copyFrom(signature))
.setSignatureHeader(ByteString.copyFrom(transactionBuilder.buildSignatureHeader()))
.build();
// Create gateway and connect to network
GatewayImpl.Builder gatewayBuilder = (GatewayImpl.Builder) GatewayImpl.builder();
gatewayBuilder.identity(wallet, "user1").networkConfig(networkConfig);
GatewayImpl gateway = (GatewayImpl) gatewayBuilder.connect();
Network network = gateway.getNetwork(CHANNEL_NAME);
Contract contract = network.getContract("mycc");
// Create channel
Transaction createChannelTransaction = network.getChannel().newTransaction("createChannel");
createChannelTransaction.setEndorsingPeers(EnumSet.of(network.getChannel().getPeers().iterator().next()));
createChannelTransaction.submit(configuration.toByteString(), configurationSignature.toByteArray());
// Wait for channel creation event
ContractEvent contractEvent = contract.getEvent("createChannelEvent");
Collection<ProposalResponse> responses = contractEvent.getTransactionEvent().getContractResponses();
for (ProposalResponse response : responses) {
TransactionInfo transactionInfo = network.getChannel().queryTransaction(response.getTransactionID());
if (transactionInfo.isValid()) {
System.out.println("Channel created successfully");
} else {
System.out.println("Failed to create channel");
}
}
// Disconnect from network
gateway.close();
}
}
```
该示例代码中,我们首先加载了 Fabric 网络配置文件 `network.yaml`,然后创建了一个钱包 `wallet`,并将一个用户身份 `identity` 添加到钱包中。接着,我们使用 `CryptoSuiteFactory` 创建了一个加密套件 `cryptoSuite`,并使用 `KeyStoreFactory` 创建了一个密钥库 `keyStore`。然后,我们创建了一个 HFClient 客户端,并指定了客户端的加密套件和用户身份。接下来,我们创建了一个频道配置 `configuration`,并使用 `TransactionBuilder` 构建了一个包含频道配置的交易。此外,我们还创建了一个频道配置签名 `configurationSignature`。然后,我们使用 GatewayImpl 连接到 Fabric 网络,并获取名为 `mycc` 的智能合约。接下来,我们使用 `network.getChannel().newTransaction("createChannel")` 创建了一个新交易,将 `configuration.toByteString()` 和 `configurationSignature.toByteArray()` 作为参数传递给 `submit()` 方法,以提交创建频道的交易。最后,我们等待 `createChannelEvent` 事件的发生,并检查交易是否成功。最终,我们使用 `gateway.close()` 断开了与 Fabric 网络的连接。
阅读全文