转载

hyperledger fabric 1.4 使用java开发智能合约

hyperledger fabric使用java开发智能合约,也较为简单,我们今天就来聊一聊如何使用java开发智能合约,如需完整的学习fabric,可以参考 视频教程

首先需要在pom里面引入fabric的智能合约的jar包,如下图所示,需要注意的点如下,引入maven-shade-plugin包,设置mainclass,且finalname必须为chaincode。

<dependencies>
        <dependency>
            <groupId>org.hyperledger.fabric-chaincode-java</groupId>
            <artifactId>fabric-chaincode-shim</artifactId>
            <version>1.4.0</version>
        </dependency>
</dependencies>

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>chaincode</finalName>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.fabric.chaincode.MyChaincode</mainClass>
                                </transformer>
                            </transformers>
                            <filters>
                                <filter>
                                    <!-- filter out signature files from signed dependencies, else repackaging fails with security ex -->
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

java-fabric的示例代码如下:~~~~

private static Log _logger = LogFactory.getLog(MyChaincode.class);

    @Override
    public Response init(ChaincodeStub stub) {
        return newSuccessResponse();
    }

    @Override
    public Response invoke(ChaincodeStub stub) {
        try {
            _logger.info("Invoke java simple chaincode");
            String func = stub.getFunction();
            List<String> params = stub.getParameters();
            if (func.equals("invoke")) {
                return invoke(stub, params);
            }
           else if (func.equals("query")) {
                return query(stub, params);
            }
            return newErrorResponse("Invalid invoke function name. Expecting one of: [/"invoke/", /"delete/", /"query/"]");
        } catch (Throwable e) {
            return newErrorResponse(e);
        }
    }

    private Response invoke(ChaincodeStub stub, List<String> args) {
        if (args.size() != 2) {
            return newErrorResponse("Incorrect number of arguments. Expecting 3");
        }
        String key = args.get(0);
        String json = args.get(1);
        if(StringUtil.isNullOrEmpty(key) || StringUtil.isNullOrEmpty(json)){
            return newErrorResponse("arguments error");
        }else{
            stub.putStringState(key,json);
            return newSuccessResponse("put success!");
        }
    }


    // query callback representing the query of a chaincode
    private Response query(ChaincodeStub stub, List<String> args) {
        if (args.size() != 1) {
            return newErrorResponse("Incorrect number of arguments. Expecting name of the person to query");
        }
        String key = args.get(0);
        //byte[] stateBytes
        String val    = stub.getStringState(key);
        if (val == null) {
            return newErrorResponse(String.format("Error: state for %s is null", key));
        }
        _logger.info(String.format("Query Response:/nName: %s, Amount: %s/n", key, val));
        return newSuccessResponse(val, ByteString.copyFrom(val, UTF_8).toByteArray());
    }

    public static void main(String[] args) {
        System.out.println("OpenSSL avaliable: " + OpenSsl.isAvailable());
        new MyChaincode().start(args);
    }

}

智能合约的安装和实例化,需要注意的是 -l java指定java语言为智能合约,智能合约的路径需要补全,go开发的话无需补全。

peer chaincode install -n jcode -v 1.0 -p /opt/gopath/src/github.com/chaincode/javachaincode/ -l java


peer chaincode instantiate -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n jcode -v 1.0 -c '{"Args":["init"]}' -P "AND ('Org1MSP.peer')"
原文  https://segmentfault.com/a/1190000021373026
正文到此结束
Loading...