Java连接Hyperledger示例Demo

前言

主要借助fabric-gateway-java jar包提供更简单快速的连接hyperldger网络的方法。
前提条件:

  • 区块链网络已经启动(以first-network为例)
  • 测试链码已经部署(链码可以在服务器端正常调用查询)

配置文件设置

主要包括以下三块内容

  1. pom 文件
  2. crypto-config文件夹
  3. connection.json文件

pom文件配置

我们主要是使用fabric-gateway-java完成连接区块链,首先添加依赖:

		<dependency>
            <groupId>org.hyperledger.fabric</groupId>
            <artifactId>fabric-gateway-java</artifactId>
            <version>2.0.0</version>
        </dependency>

crypto-config文件夹

crypto-config是节点证书、密钥相关信息,在我们启动first-network时会生成对应的相关信息。

root@lamaxiya:/opt/gopath/src/github.com/hyperledger/fabric-samples/first-network# ll
drwxr-xr-x  4 root root  4096 Nov 30 20:52 crypto-config

我们需要把该文件夹复制到我们的测试项目中resources文件夹下如下图。
复制过来的文件夹内容

connection.json文件

可以是yaml格式也可以是json格式,该文件主要是节点的配置文件路径和连接信息。主要内容如下面文件所示。

{
  "name": "basic-network",
  "version": "1.0.0",
  "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
        }
      }
    },
    "mychannel2": {
      "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-network/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/priv_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config-network/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-network/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore/priv_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config-network/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts/Admin@org2.example.com-cert.pem"
      }
    }
  },
  "orderers": {
    "orderer.example.com": {
      "url": "grpcs://10.112.246.186:7050",
      "mspid": "OrdererMSP",
      "grpcOptions": {
        "ssl-target-name-override": "orderer.example.com",
        "hostnameOverride": "orderer.example.com"
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config-network/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt"
      },
      "adminPrivateKeyPEM": {
        "path": "src/main/resources/crypto-config-network/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/priv_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config-network/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem"
      }
    }
  },
  "peers": {
    "peer0.org1.example.com": {
      "url": "grpcs://10.112.246.186: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-network/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
      }
    },
    "peer0.org2.example.com": {
      "url": "grpcs://10.112.246.186: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-network/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt"
      }
    }
  },
  "certificateAuthorities": {
    "ca-org1": {
      "url": "https://10.112.246.186:7054",
      "grpcOptions": {
        "verify": true
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config-network/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem"
      },
      "registrar": [
        {
          "enrollId": "admin",
          "enrollSecret": "adminpw"
        }
      ]
    },
    "ca-org2": {
      "url": "https://10.112.246.186:8054",
      "grpcOptions": {
        "verify": true
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config-network/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem"
      },
      "registrar": [
        {
          "enrollId": "admin",
          "enrollSecret": "adminpw"
        }
      ]
    }
  }
}

根据你具体复制过来的文件位置还有你的服务地址ip更换相应内容

新建java测试项目

新建java测试项目,编写对应Demo1.java如下java文件。

package com.example.themeleaf.test;

import com.alibaba.fastjson.JSON;
import com.example.themeleaf.utils.CryptoUtils;
import com.example.themeleaf.utils.StringUtils;
import com.example.themeleaf.utils.constant.enums.TestKey;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.gateway.impl.GatewayImpl;
import java.io.IOException;
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;

/**
 * @author 测试
 * @title: demo1
 * @projectName fabricdemo
 * @description: fabric2.0 java SDK使用
 */
@Slf4j
public class Demo1 {
    /**
     * 连接配置文件路径
     */
    private static final Path NETWORK_CONFIG_PATH = Paths.get("src", "main", "resources", "connection.json");

    /**
     * 连接用户的证书、密钥文件路径
     */
    private static final Path CREDENTIAL_PATH = Paths.get("src", "main","resources", "crypto-config",
            "peerOrganizations", "org1.example.com", "users", "User1@org1.example.com", "msp");
    public static void main(String[] args) {
        X509Certificate certificate;
        PrivateKey privateKey;
        Gateway gateway;
        try {
            //使用org1中的user初始化一个网关wallet账户用于连接网络
            Wallet wallet = Wallets.newInMemoryWallet();
            Path certificatePath = CREDENTIAL_PATH.resolve(Paths.get("signcerts", "User1@org1.example.com-cert.pem"));
            certificate = readX509Certificate(certificatePath);
            Path privateKeyPath = CREDENTIAL_PATH.resolve(Paths.get("keystore", "priv_sk"));
            //获取连接的私钥信息
            privateKey = getPrivateKey(privateKeyPath);
            //初始化钱包用户信息
            wallet.put("user",Identities.newX509Identity("Org1MSP",certificate,privateKey));
            //根据connection.json 获取Fabric网络连接对象
            GatewayImpl.Builder builder = (GatewayImpl.Builder) Gateway.createBuilder();
            builder.identity(wallet, "user").networkConfig(NETWORK_CONFIG_PATH);
            //连接网关
            gateway = builder.connect();
            //获取mychannel通道
            Network network = gateway.getNetwork("mychannel");
            //获取部署的合约,合约名字时记得改为自己安装时的合约
            Contract fakename = network.getContract("fakename");
            //调用合约中的接口
            byte[] bytes = fakename.evaluateTransaction("ReadUserCaInfoByUserId", "ceshi100");
            //输出测试结果
            System.out.println(new String(bytes));
        } 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);
        }
    }
}

下面是运行上述文件输出的结果:
运行结果展示

小结

本篇文章主要是利用fabric提供的first-network网络进行的连接测试,仅供学习参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LamaxiyaFc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值