美文网首页
fabric2.2 test-network通过fabric-j

fabric2.2 test-network通过fabric-j

作者: wilesan | 来源:发表于2021-01-12 21:53 被阅读0次

    在idea中新建sprint-boot项目

    https://github.com/wilesanGH/test-network-java-sdk
    项目结构如下:

    QQ图片20210112214009.png
    • pom.xml中引用
            <dependency>
                <groupId>org.hyperledger.fabric-sdk-java</groupId>
                <artifactId>fabric-sdk-java</artifactId>
                <version>1.4.7</version>
            </dependency>
    
            <dependency>
                <groupId>org.hyperledger.fabric</groupId>
                <artifactId>fabric-gateway-java</artifactId>
                <version>2.2.0</version>
            </dependency>
    
    • 新建connection.json
    {
      "name": "basic-network",
      "version": "1.0.0",
      "dependencies": {
      },
      "client": {
        "organization": "Org1",
        "connection": {
          "timeout": {
            "peer": {
              "endorser": "300"
            },
            "orderer": "300"
          }
        }
      },
      "channels": {
        "mychannel": {
          "orderers": [
            "orderer.example.com"
          ],
          "peers": {
            "peer0.org1.example.com": {
              "endorsingPeer": true,
              "chaincodeQuery": true,
              "ledgerQuery": true,
              "eventSource": true
            },
            "peer0.org2.example.com": {
              "endorsingPeer": true,
              "chaincodeQuery": true,
              "ledgerQuery": true,
              "eventSource": true
            }
          }
        }
      },
      "organizations": {
        "Org1": {
          "mspid": "Org1MSP",
          "peers": [
            "peer0.org1.example.com"
          ],
          "certificateAuthorities": [
            "ca-org1"
          ],
          "adminPrivateKeyPEM": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/priv_sk"
          },
          "signedCertPEM": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem"
          }
        },
        "Org2": {
          "mspid": "Org2MSP",
          "peers": [
            "peer0.org2.example.com"
          ],
          "certificateAuthorities": [
            "ca-org2"
          ],
          "adminPrivateKeyPEM": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore/priv_sk"
          },
          "signedCertPEM": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts/Admin@org2.example.com-cert.pem"
          }
        }
      },
      "orderers": {
        "orderer.example.com": {
          "url": "grpcs://192.168.33.100:7050",
          "mspid": "OrdererMSP",
          "grpcOptions": {
            "ssl-target-name-override": "orderer.example.com",
            "hostnameOverride": "orderer.example.com"
          },
          "tlsCACerts": {
            "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt"
          },
          "adminPrivateKeyPEM": {
            "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/priv_sk"
          },
          "signedCertPEM": {
            "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem"
          }
        }
      },
      "peers": {
        "peer0.org1.example.com": {
          "url": "grpcs://192.168.33.100:7051",
          "grpcOptions": {
            "ssl-target-name-override": "peer0.org1.example.com",
            "hostnameOverride": "peer0.org1.example.com",
            "request-timeout": 120001
          },
          "tlsCACerts": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
          }
        },
        "peer0.org2.example.com": {
          "url": "grpcs://192.168.33.100:9051",
          "grpcOptions": {
            "ssl-target-name-override": "peer0.org2.example.com",
            "hostnameOverride": "peer0.org2.example.com",
            "request-timeout": 120001
          },
          "tlsCACerts": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt"
          }
        }
      },
      "certificateAuthorities": {
        "ca-org1": {
          "url": "https://192.168.33.100:7054",
          "grpcOptions": {
            "verify": true
          },
          "tlsCACerts": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem"
          },
          "registrar": [
            {
              "enrollId": "admin",
              "enrollSecret": "adminpw"
            }
          ]
        },
        "ca-org2": {
          "url": "https://192.168.33.100:8054",
          "grpcOptions": {
            "verify": true
          },
          "tlsCACerts": {
            "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem"
          },
          "registrar": [
            {
              "enrollId": "admin",
              "enrollSecret": "adminpw"
            }
          ]
        }
      }
    }
    

    这个就是test-network默认搭建的网络结构,其中的192.168.33.100是我之前的虚机的ip,之间在Vagrantfile中设置的。这里在的各种证书的路径就是resource下面的crypto-config下面的两个文件,这两个peerOrganizations 和 orderOrganizations是test-network启动以后,在test-network目录下的organizations目录下面的文件,直接copy过来。放在crypto-config中。

    • 创建fabric.config.properties
    # 网络配置
    networkConfigPath = src/main/resources/connection.json
    #证书路径
    certificatePath = src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/signcerts/User1@org1.example.com-cert.pem
    # 私钥路径
    privateKeyPath = src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/keystore/priv_sk
    
    # 通道名称
    channelName = mychannel
    
    # 合约名称
    #contractName = hello
    contractName = basic
    
    • TestApplication.java
    package com.fabric.test;
    
    import org.hyperledger.fabric.gateway.*;
    import org.hyperledger.fabric.sdk.Peer;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.Reader;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.security.InvalidKeyException;
    import java.security.PrivateKey;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.EnumSet;
    import java.util.Properties;
    
    @SpringBootApplication
    public class TestApplication {
    
        public static void main(String[] args) {
            //SpringApplication.run(TestApplication.class, args);
    
            try {
                //获取相应参数
                Properties properties = new Properties();
                InputStream inputStream = TestApplication.class.getResourceAsStream("/fabric.config.properties");
                properties.load(inputStream);
    
                String networkConfigPath = properties.getProperty("networkConfigPath");
                String channelName = properties.getProperty("channelName");
                String contractName = properties.getProperty("contractName");
                //使用org1中的user1初始化一个网关wallet账户用于连接网络
                String certificatePath = properties.getProperty("certificatePath");
                X509Certificate certificate = readX509Certificate(Paths.get(certificatePath));
    
                String privateKeyPath = properties.getProperty("privateKeyPath");
                PrivateKey privateKey = getPrivateKey(Paths.get(privateKeyPath));
    
                Wallet wallet = Wallets.newInMemoryWallet();
                wallet.put("user1", Identities.newX509Identity("Org1MSP",certificate,privateKey));
    
                //根据connection.json 获取Fabric网络连接对象
                Gateway.Builder builder = Gateway.createBuilder()
                        .identity(wallet, "user1")
                        .networkConfig(Paths.get(networkConfigPath));
                //连接网关
                Gateway gateway = builder.connect();
                //获取通道
                Network network = gateway.getNetwork(channelName);
                //获取合约对象
                Contract contract = network.getContract(contractName);
                /*******自己编写****************/
                Contract contract1 = network.getContract("integral");
                byte[] queryAllPic = contract1.evaluateTransaction("GetAllIntegrals");
                System.out.println("所有图片:"+new String(queryAllPic, StandardCharsets.UTF_8));
    
                /***********************************/
                //查询现有资产
                //注意更换调用链码的具体函数
                byte[] queryAllAssets = contract.evaluateTransaction("GetAllAssets");
                System.out.println("所有资产:"+new String(queryAllAssets, StandardCharsets.UTF_8));
    
                // 增加新的资产
                byte[] invokeResult = contract.createTransaction("CreateAsset")
                        .setEndorsingPeers(network.getChannel().getPeers(EnumSet.of(Peer.PeerRole.ENDORSING_PEER)))
                        .submit("asset8","blue","20","Klay","88");
                        //.submit("asset5", "LaoWang", "666");
                System.out.println(new String(invokeResult, StandardCharsets.UTF_8));
    
                //查询更新后的资产
                byte[] queryAllAssetsAfter = contract.evaluateTransaction("GetAllAssets");
                System.out.println("更新资产:"+new String(queryAllAssetsAfter, StandardCharsets.UTF_8));
    
                //查询单个资产
                byte[] queryOneAsset = contract.createTransaction("ReadAsset")
                        .submit("asset8");
                System.out.println("更新资产:"+new String(queryOneAsset, StandardCharsets.UTF_8));
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        private static X509Certificate readX509Certificate(final Path certificatePath) throws IOException, CertificateException {
            try (Reader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8)) {
                return Identities.readX509Certificate(certificateReader);
            }
        }
    
        private static PrivateKey getPrivateKey(final Path privateKeyPath) throws IOException, InvalidKeyException {
            try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
                return Identities.readPrivateKey(privateKeyReader);
            }
        }
    
    
    }
    

    这个是主程序,先就通过这些配置文件找到证书、通道等再调用通道里面的合约。这里面只写了部分的方法调用,可根据上一节的内容,调用更多的方法。

    相关文章

      网友评论

          本文标题:fabric2.2 test-network通过fabric-j

          本文链接:https://www.haomeiwen.com/subject/irvgoktx.html