You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

HyperLedger Fabric Java SDK:替换Go链码为Java链码并运行测试

Got it, let's break down exactly how to swap out the Go example_cc.go chaincode with a Java equivalent in your EndToEndIT.java test. I’ve tackled this scenario before, so here’s a complete, actionable solution:

1. Equivalent Java Chaincode (example_cc.java)

This Java chaincode mirrors the core functionality of the Go version—handling init, put, get, and delete operations on the ledger. Save this as src/main/java/org/example/ExampleCC.java (you’ll need to set up the matching package structure):

package org.example;

import org.hyperledger.fabric.contract.Context;
import org.hyperledger.fabric.contract.ContractInterface;
import org.hyperledger.fabric.contract.annotation.Contract;
import org.hyperledger.fabric.contract.annotation.Default;
import org.hyperledger.fabric.contract.annotation.Transaction;
import org.hyperledger.fabric.shim.ChaincodeException;
import org.hyperledger.fabric.shim.ChaincodeStub;

@Contract(name = "example_cc")
@Default
public class ExampleCC implements ContractInterface {

    private static final String ERROR_KEY_NOT_FOUND = "KEY_NOT_FOUND";

    @Transaction(intent = Transaction.TYPE.SUBMIT)
    public void init(final Context ctx) {
        // No-op initialization, identical to the Go chaincode
    }

    @Transaction(intent = Transaction.TYPE.SUBMIT)
    public void put(final Context ctx, final String key, final String value) {
        ChaincodeStub stub = ctx.getStub();
        stub.putStringState(key, value);
    }

    @Transaction(intent = Transaction.TYPE.EVALUATE)
    public String get(final Context ctx, final String key) {
        ChaincodeStub stub = ctx.getStub();
        String value = stub.getStringState(key);
        if (value == null || value.isEmpty()) {
            throw new ChaincodeException("Key " + key + " not found", ERROR_KEY_NOT_FOUND);
        }
        return value;
    }

    @Transaction(intent = Transaction.TYPE.SUBMIT)
    public void delete(final Context ctx, final String key) {
        ChaincodeStub stub = ctx.getStub();
        stub.delState(key);
    }
}

Add this pom.xml to manage dependencies and build the chaincode into a shaded JAR:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>example_cc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.hyperledger.fabric-chaincode-java</groupId>
            <artifactId>fabric-chaincode-shim</artifactId>
            <version>2.5.5</version> <!-- Match your Fabric network version -->
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source> <!-- Java 11+ is required for Fabric Java chaincode -->
                    <target>11</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>org.hyperledger.fabric.contract.ContractRouter</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
2. Modify EndToEndIT.java to Use the Java Chaincode

Update the chaincode deployment logic in your test to point to the Java chaincode. Key changes include setting the chaincode type to JAVA and updating the path to the built JAR.

For Fabric 2.x+ (Approval/Commit Flow):

// Install the Java chaincode
InstallChaincodeRequest installRequest = InstallChaincodeRequest.newInstance();
installRequest.setChaincodeName("example_cc");
installRequest.setChaincodeVersion("1.0");
installRequest.setChaincodeType(ChaincodeType.JAVA);
// Path to the folder containing your shaded JAR (e.g., /home/user/java-chaincode/target)
installRequest.setChaincodePath("/path/to/your/java/chaincode/target");
channel.getPeer("peer0.org1.example.com").installChaincode(installRequest).submit();

// Approve chaincode for your organization
ApproveChaincodeForMyOrgRequest approveRequest = ApproveChaincodeForMyOrgRequest.newInstance();
approveRequest.setChaincodeName("example_cc");
approveRequest.setChaincodeVersion("1.0");
approveRequest.setChaincodeType(ChaincodeType.JAVA);
approveRequest.setSequence(1L);
approveRequest.setEndorsementPolicy(EndorsementPolicy.fromYamlFile(new File("src/test/resources/endorsement-policy.yaml")));
client.approveChaincodeForMyOrg(approveRequest).submit();

// Commit chaincode to the channel
CommitChaincodeDefinitionRequest commitRequest = CommitChaincodeDefinitionRequest.newInstance();
commitRequest.addPeer("peer0.org1.example.com");
commitRequest.addPeer("peer0.org2.example.com");
commitRequest.setChaincodeName("example_cc");
commitRequest.setChaincodeVersion("1.0");
commitRequest.setChaincodeType(ChaincodeType.JAVA);
commitRequest.setSequence(1L);
commitRequest.setEndorsementPolicy(EndorsementPolicy.fromYamlFile(new File("src/test/resources/endorsement-policy.yaml")));
client.commitChaincodeDefinition(commitRequest).submit();

For Fabric 1.x (Instantiate Flow):

InstantiateChaincodeRequest instantiateRequest = InstantiateChaincodeRequest.newInstance();
instantiateRequest.setChaincodeName("example_cc");
instantiateRequest.setChaincodeVersion("1.0");
instantiateRequest.setChaincodeType(ChaincodeType.JAVA);
instantiateRequest.setArgs(Collections.singletonList("init")); // Matches our no-op init method
channel.instantiateChaincode(instantiateRequest).submit();

Note: Existing invoke/evaluate calls in your test (like calling "put" or "get") don’t need changes—they’ll work with the Java chaincode since we kept the method names identical to the Go version.

3. Full Run Steps

Follow these steps to execute the modified test:

  • Step 1: Build the Java chaincode
    • Run mvn clean package in the chaincode project folder. This generates a shaded JAR in the target directory.
  • Step 2: Update test configuration
    • Ensure the chaincode path in EndToEndIT.java points to the target folder of your Java chaincode. If using Docker for the test network, mount this folder to the peer containers so they can access the JAR.
  • Step 3: Run the test
    • Execute EndToEndIT.java as you normally would (via your IDE or mvn test command).
  • Step 4: Verify results
    • Confirm all test steps pass: invoke "put" to store a value, evaluate "get" to retrieve it, invoke "delete" to remove it, etc.
Quick Troubleshooting Tips
  • Java Version: Ensure you’re using Java 11 or higher—Fabric’s Java chaincode runtime doesn’t support older versions.
  • Dependency Alignment: Match the fabric-chaincode-shim version in your pom.xml to your Fabric network’s version (e.g., 2.5.5 for Fabric 2.5.x).
  • Chaincode Access: If peers can’t find the JAR, double-check the mounted volume path in your Docker compose file for the test network.

内容的提问来源于stack exchange,提问作者Skadoosh

火山引擎 最新活动