Java-sdk调用智能合约示例

397 阅读2分钟
  • 两种调用方式:fabric-sdk以及fabric-gateway

  • 导入maven包

    <dependency>
        <groupId>org.hyperledger.fabric</groupId>
        <artifactId>fabric-gateway-java</artifactId>
        <version>2.0.0</version>
    </dependency>
    
  • 创建java项目,在resource下创建crypto-config目录,将服务器上/root/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/test-network/organizations目录下的peerOrganizations与ordererOrganizations复制过来

  • 在resource下创建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.0.99: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.0.99: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.0.99: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.0.99: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.0.99: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"
            }]
        }
    }
    

    }

  • 创建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/59157e7b19fe2eacad4baca256296e93022c51e5bc0102eec4e0b23f54db85f8_sk
    # 通道名字
    channelName = mychannel
    # 链码名字
    contractName = mylocks
    
  • 项目结构如下

    -resource
        --crypto-config
            ---ordererOrganizations.example.com
            ---peerOrganizations
        --connnection.json
        --fabric.config.properties
    
  • skd调用样例

    public class SdkDemo {
        public static void main(String[] args) {
            try {
                //获取fabric.config.properties文件中的相应参数
                Properties properties = new Properties();
                InputStream inputStream = SdkDemo.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);
    ​
                // Submit transactions that store state to the ledger.
                byte[] createCarResult = contract.createTransaction("set").submit("123", "我是来测试是否上链的");
                System.out.println("====println==============>" + new String(createCarResult, StandardCharsets.UTF_8));
    ​
                // Evaluate transactions that query state from the ledger.
                byte[] queryAllCarsResult = contract.evaluateTransaction("get", "123");
                System.out.println("==================>" + new String(queryAllCarsResult, 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, IOException {
            try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
                return Identities.readPrivateKey(privateKeyReader);
         }
    }