Using hyperledger fabric and composer to implement blockchain applications

Pen Pavilion 2021-05-15 01:35:11 阅读数:592

本文一共[544]字,预计阅读时长:1分钟~
using hyperledger fabric composer implement

At present, it is the topic of blockchain that cannot be bypassed in the technical field . But beyond cryptocurrency , There are more interesting applications that can bring many exciting software ecosystems . This also applies to Hyperledger project , The project provides a very modular blockchain framework . Let's see how to use Hyperledger Fabric and Composer How easy it is to implement blockchain applications .

About the project Hyperledger

Hyperledger It's a umbrella Name of the project , Under this project, open source blockchain methods and tools are developed in collaboration . It consists of Linux Foundation in 2015 Launched in 2013 , And enjoy IBM, Intel, Fujitsu and other software giants, as well as the large community's enthusiastic participation .Hyperledger Of GitHub Repositories are now more active than ever . Anyone can participate in the development .

stay Hyperledger in , Not only has a single blockchain framework been developed ( Or platform ). contrary , The point is to use multiple methods in parallel , Create synergy , Reusable components and flexibility . from Hyperledger From a conceptual point of view , Blockchain networks cannot be compared with representatives of cryptocurrencies such as bitcoin or Ethernet . contrary ,Hyperledger The nodes of the network are distributed in the participating organizations , This makes it private , Licensing or alliance blockchain networks are particularly interesting . First , We can forget the working proof of public blockchain , Proof of equity and other consensus mechanisms . The organizations involved verify each other's transactions and interests as a consortium from the business value of the application and the trust involved . This also largely solves the problem of scalability ( We learned from the bitcoin network ) And can achieve high transaction throughput .

project Hyperledger The different blockchain approaches are Fabric,Burrow,Iroha,Indy and Sawtooth. private , Licensed and federated blockchains can be developed with all of these blockchains , But each implementation follows a different approach .

We'll go into details in this article Fabric, Because it has the most active community , And the most flexible variant . Because of its powerful modularity ,fabric It's universally available . “ You can take Hyperledger Fabric Be regarded as similar to Apache Web Server”,Linux The foundation Hyperledger Executive director Brian Behlendorf say . Other methods are more used to implement special situations in a limited environment .

Hyperledger Fabric —— Flexible blockchain application platform

Use Fabric As a platform , You can develop a completely independent distributed ledger solution .Fabric Contains concepts that can be implemented as freely as possible . The foundation of blockchain network is the modeling of the required organizational structure . Each participant has a fixed identity , You can identify yourself by issuing certificates . In addition to authentication , It also includes authorization . Using this role-based system , Flexible aspects of privacy and confidentiality in licensed blockchains . For the management of certificates and participants , You can use the fabric certification authority (1.0 Member service providers before version ).

The definition of assets ( Projects to be managed on the blockchain ) It's all up to the blockchain application . These assets , For example, engine blocks from the automotive industry are made up of JSON and / Or binary format key value definition of the model .

The concept of chain code aims to implement business logic based on assets and their owners . This can be used to achieve Go,Java or Node.js And so on , These rules define read permissions or asset modifications . The execution chain code function can read and return assets and / Or create and modify assets and store them in the local ledger database . After local persistence changes on the node , Submit changes to the network (“ recognition ”) And insert it into the blockchain after other organizations accept it . In the context of Ethereum or other public blockchain platforms , You can compare chain codes with smart contracts .

Channels are used to implement the privacy domain . In the simplest scenario , The whole chain code is deployed on a single channel joined by all participants . however , To create an encapsulation area and allow only selected participants to communicate in it , Channels with restricted participant groups can be configured . Each channel can deploy different chain code , So that functional isolation can be achieved . Besides , have access to AES Partially or completely encrypts communications in a channel .

result , Maintain a distributed ledger in each channel , This can be thought of as a cash book linking transactions . Each participant keeps a copy of the ledger for each channel to which they belong . This creates a blockchain data structure for each existing channel in the network . Like blockchain , Transactions are stored in blocks , These blocks become encryption chains in a single connection list .

however , To provide a separate view of ledger data to client applications , You can even perform complex read requests against the network . Because of the use of CouchDB Such a document oriented database , It's possible . This is for connecting to Fabric The client side of the network provides flexible data access .

Use Composer Add simpler concepts

Hyperledger-Composer yes Hyperledger One of the tools in the ecosystem . You can think of it as Fabric Framework . If you want to develop , Build and manage Fabric The Internet , So even if it's not mandatory , It's also practical . It introduces based on Fabric A further concept of , To provide elegant abstractions .

Except for assets , You can also do it in Composer Network participants are defined in the modeling language , The scheme of transactions and events . Every type of transaction flows through JavaScript The code is simple API Implemented on . Access control files can be used to restrict participants' access to certain resources . Can be in Composer Query Language Common queries for data in the ledger are defined in , It's a kind of similarity SQL Language .

then , All required files must be packaged into .bna In the document BND( Business network definition ). then , You can install this archive on an existing Fabric On the Internet .BND Of course, the source code can be developed and tested locally in our preferred editor , So you can use Git Version control . For prototyping and demonstration purposes , Yes Composer Playground. It provides a modern , Clear and intuitive, usable Web Interface , Accessible Composer CLI Local configuration of . Use Playground, You can easily create , install , test , edit , Import and export BND.

stay Composer Playground in , You can install it in a user-friendly way , Modify and test new business networks , Without previous sample blockchain application knowledge ( For example, vehicle life cycle , Car auctions or farm animal tracking ). After setting up the tool , You can do the same locally , So we can leave the hosting playground after a short time of playing games . This playground is perfect for prototyping ideas and understanding the underlying Composer and Fabric Model .

Use cases : Supply chain tracking of engine blocks

In order to use Hyperledger-Fabric and Composer Realize private blockchain network , Take the engine tracking in the automotive industry as an example . under these circumstances , There are manufacturers and distributors as network participants . The engine and the vehicle it is mounted on are shown as assets . Companies of manufacturers and distributors are introduced and identified as organizations in the network .

Fabric The chain code should provide the following functions :

  • 1. Produce engine block with unique serial number .
  • 2. Deliver the engine block to the dealer after production .
  • 3. Tracking the serial number of the vehicle .
  • 4. Install the engine block into a registered vehicle .

The next step is to install the required tools and setup items .

Development environment settings and project creation

First , You need to install the Fabric All the requirements of . Then we install Composer and Composer And the requirements of the tools themselves .

then , It's better to familiarize yourself with the new environment . If we follow exactly the instructions in the previous link , be fabric-tools Now in our home directory . By describing the script , We can do it in Docker-Compose Start a simple Fabric The Internet , Get peer administrator access and stop and delete it again . First , We download 1.1 Version of Docker Mirror and start the network :

export FABRIC_VERSION=hlfv11 && ./downloadFabric.sh && ./startFabric.sh

When the network is running ,composer-playground web-UI Can pass composer-playground start-up . It USES composer-cli And access the running Fabric The Internet . from now on , We will Fabric As a configurable platform / Infrastructure , Its state is changed by the right tools . We don't use... Directly Fabric Concept development chain code , Permissions or any model , because Composer Provides more advantages .

Implementation function

Now we create our BND project . about Yeoman( Use the template to set up the code generator for the project , Such as Maven Archtypes), There's a template (hyperledger-composer:businessnetwork. however , I've prepared a repository , We can also use it now JavaScript ES6 And some great tools . We should branch from the beginning “ initial ” Start .master Branches have final and working versions . We first clone the initial branch of the repository .

git clone -b initial git@github.com:jverhoelen/fabric-composer-engine-supplychain.git

Now we open the folder in the editor of our choice .Visual Studio Code Very suitable Composer, Because it has installable syntax highlighting extensions . With a little modification, you'll find that it's a NPM project , So we go from npm install Start installing all dependencies . Use npm test We can run unit tests , Use npm run lint We can test code styles , And use npm run createArchive We can create the.bna file , We complete the business network definition in a packaged format . Let's see if everything is OK right now .

Then we get familiar with the project structure .lib The folder contains JS file . Of course , We want to test this business logic and store our unit tests in the test/ In the folder . Model definition ( participants , assets , Trading, etc ) stay models/ in .

We want to model the required blockchain network first . So , We delete the contents of the model file , And in the first line, it specifies a new namespace :

namespace org.acme.enginesupplychain

We model for participant manufacturers and distributors , And use Composer Modeling language inheritance . We also want each participant to have an optional address in addition to their name . We put these attributes into a concept :

participant Member identified by memberId {
o String memberId
o String name
o Address address optional
}
participant Manufacturer extends Member {
}
participant Merchant extends Member {
}
concept Address {
o String country
o String city
o String street
o String streetNo
}

Then we introduce the assets of our network : Engine blocks and cars with engines installed later . ad locum , We understand that assets and participants can refer to each other . References always point to existing resources of any type . We use small “o” The starting attribute always exists in the resource itself .

asset Engine identified by engineId {
o String engineId
o EngineProperties data
--> Manufacturer manufacturer
--> Car currentCar optional
--> Merchant merchant optional
}
asset Car identified by carId {
o String carId
o String legalDocumentId
}
concept EngineProperties {
o String brand
o String model
o Double horsePower
o Double cubicCapacity
o Integer cylindersAmount
}

After modeling the system , We define all the available operations that can be performed on top of existing assets and participants . These are trading resources . after , We test and implement the underlying trading logic for each of the following trading models .

transaction EngineMerchantTransfer {
--> Engine engine
--> Merchant merchant
}
transaction EngineCarInstallation {
--> Engine engine
--> Car car
}
transaction EngineCreation {
--> Manufacturer manufacturer
o EngineProperties data
}
transaction CarCreation {
o String legalIdDocument
}

Now we've defined what might happen , We can start implementing how it affects ledger status when we submit a transaction . First , We are committed to creating engine assets . The engine should be UUID The format is randomly generated ID, And should always belong to the manufacturer from the beginning . So we empty out logic.js File and start from scratch . We define constants modelsNamespace And the function uuid, Because we're going to need them more often . Next is createEngineAsset function . The document block above the function is very important , In order to Composer You can identify the type of transaction that is implemented when the code is packaged .

/* global getAssetRegistry getFactory */
const modelsNamespace = 'org.acme.enginesupplychain'
function uuid() {
const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`
}
/**
* Creation of a Engine asset triggered by physical production.
* @param {org.acme.enginesupplychain.EngineCreation} tx - the transaction to create an engine
* @transaction
*/
async function createEngineAsset(tx) { // eslint-disable-line no-unused-vars
const engineRegistry = await getAssetRegistry(modelsNamespace + '.Engine')
const engine = getFactory().newResource(modelsNamespace, 'Engine', uuid())
const engineData = getFactory().newConcept(modelsNamespace, 'EngineProperties')
engine.data = Object.assign(engineData, tx.data)
engine.manufacturer = tx.manufacturer
await engineRegistry.add(engine)
}

In this way , We've also implemented other types of transactions EngineMerchantTransfer,EngineCarInstallation and CarCreation.

/**
* An engine is transfered to a merchant.
* @param {org.acme.enginesupplychain.EngineMerchantTransfer} tx - the engine transfer transaction
* @transaction
*/
async function transferEngineToMerchant(tx) { // eslint-disable-line no-unused-vars
const engineRegistry = await getAssetRegistry(modelsNamespace + '.Engine')
tx.engine.merchant = tx.merchant
await engineRegistry.update(tx.engine)
}
/**
* An engine is installed in a car.
* @param {org.acme.enginesupplychain.EngineCarInstallation} tx - the engine into car installation transaction
* @transaction
*/
async function installEngineToCar(tx) { // eslint-disable-line no-unused-vars
const engineRegistry = await getAssetRegistry(modelsNamespace + '.Engine')
if (tx.car) {
tx.engine.currentCar = tx.car
await engineRegistry.update(tx.engine)
} else {
return Promise.reject('No target car was set on the transaction!')
}
}
/**
* A car is created.
* @param {org.acme.enginesupplychain.CarCreation} tx - transaction to create a new car
* @transaction
*/
async function createCar(tx) { // eslint-disable-line no-unused-vars
const carRegistry = await getAssetRegistry(modelsNamespace + '.Car')
const factory = getFactory()
const carId = uuid()
const car = factory.newResource(modelsNamespace, 'Car', carId)
car.legalDocumentId = tx.legalIdDocument
await carRegistry.add(car)
}

Unit testing of the function itself is relatively simple , If we have experience , We don't need to know more . Only for the object you need boostrapping Still a little bit overloaded with boilerplate code . The test starts with... In memory Fabric The Internet , Install a business network on it , Then authenticate it as the default Administrator . Because of this Composer Provides a library composer-admin,composer-client,composer-common and composer-connector-embedded. After testing the setup , We can now write test cases for embedded networks . Because of its length , The setup code is not included in the list , But it can be in test/EngineSupplychainSpec.js View and test on the main branch in .

Unit test cases used to test transaction types usually have similar patterns . They use their attributes and relationships to recreate transactions , Execute transactions for the network , Then check the data status of the assets and participants involved . Let's see createEngineAsset Existing test cases for .

describe(‘EngineSupplychainSpec’, () => {
// setup is done in the before and beforeEach hook
// results are the bnc (BusinessNetworkConnection), target namespace
// as well as test assets, participants and required registries
describe('createEngineAsset', () => {
it('should create an Engine by submitting a valid EngineCreation transaction', async () => {
const factory = bnc.getBusinessNetwork().getFactory()
const engineCreationTrans = factory.newTransaction(namespace, 'EngineCreation')
engineCreationTrans.data = factory.newConcept(namespace, 'EngineProperties')
engineCreationTrans.data.brand = 'Audi'
engineCreationTrans.data.model = 'Fancy engine model'
engineCreationTrans.data.horsePower = 400
engineCreationTrans.data.cubicCapacity = 4000
engineCreationTrans.data.cylindersAmount = 10
const manufacturerRegistry = await bnc.getParticipantRegistry(namespace + '.Manufacturer')
await manufacturerRegistry.addAll([])
engineCreationTrans.manufacturer = factory.newRelationship(namespace, 'Manufacturer', testManufacturer.$identifier)
await bnc.submitTransaction(engineCreationTrans)
const allEngines = await engineRegistry.getAll()
allEngines.length.should.equal(2)
})
})
})

stay Hyperledger Composer The way to implement business network definition in should be made clear through these insights . Besides ,BND There are more things that can be defined for us . stay permissions.acl in , You can use the access control language to define access restrictions for participants given simple conditions . For many applications , Event and query functions are also very useful and interesting .

Last , Let's look at the solution on the main branch . All of these requirements have been implemented and tested . We use now npm run createArchive Generate the finished .bna file , And then in dist/ In the folder . We can now import it into the Composer Playground in , So that in our local Fabric Try it on the Internet . adopt Web UI It should be self-evident , But it's also officially recorded .

Summary and Outlook

We already know Hyperledger An important part of the project . say concretely , We now know Fabric As a blockchain platform with basic concepts .Composer Added a lot of important concepts , It makes it very convenient for developers to implement and manage blockchain network . Through the implementation of the engine block production and tracking of the blockchain application case , We learned about a simple but powerful private / Alliance blockchain use cases .

The final blockchain network was initially only executed locally . We haven't expanded the configuration of peer organization and subscription services yet . But we can easily add more organizations and distribute peers across multiple hosts . For blockchain networks crossed by real organizational alliances , We still have some problems to solve :

How do we manage organizations and peer nodes ? How organizations automatically add new peers to the network ? How do we get a fair and homogeneous network that can withstand failure ? How customers communicate with the network ?

This still young platform has provided a lot of functionality and comfort . however , There are still many tasks to be done . From a developer's point of view , Unit test code still looks very bloated . Soon there will be a library , It makes it easier to implement the usual test pattern . We are eager to see Hyperledger How to continue to promote the adaptability of distributed ledger technology in business .

Troubleshooting

Make sure that all tools are connected to Fabric 1.1 compatible . This means that you have to download all of this version of docker Mirror image . The latest version of Composer and Composer Playground. At present, it is v0.19.1. In this paper Fabric and Composer All links to the document are intentionally fixed to Fabric 1.1 And the latest Composer edition .

======================================================================

Share some Hyperledger fabric、 The etheric fang 、 The currency 、EOS、Tendermint And other interactive online programming practical courses related to blockchain :

  • Hyperledger Fabric Blockchain development details , This course is for beginners , The content includes Hyperledger Fabric The identity certificate and MSP service 、 Authority strategy 、 Channel configuration and startup 、 Chain code communication interface and other core concepts , Also contains Fabric Network design 、nodejs Chain code and operation practice of application development , yes Nodejs Engineers learn Fabric The best choice for blockchain development .
  • Hyperledger Fabric java Blockchain development details , The course is for beginners , The content includes Hyperledger Fabric The identity certificate and MSP service 、 Authority strategy 、 Channel configuration and startup 、 Chain code communication interface and other core concepts , Also contains Fabric Network design 、java Chain code and operation practice of application development , yes java Engineers learn Fabric The best choice for blockchain development .
  • java Ethereum development tutorial , Mainly aimed at java and android Programmers develop blockchain Ethereum web3j Detailed explanation .
  • python The etheric fang , Mainly aimed at python Used by the Engineer web3.py Detailed explanation of blockchain Ethereum development .
  • php The etheric fang , It mainly introduces the use of php Conduct smart contract development interaction , Create an account 、 transaction 、 Transfer accounts 、 Token development, filters and transactions .
  • Introduction to Ethereum , It mainly introduces smart contract and dapp application development , Suitable for entry .
  • Advanced course of Ethereum development , It mainly introduces the use of node.js、mongodb、 Blockchain 、ipfs Realize decentralization of e-commerce DApp actual combat , Suitable for advanced .
  • ERC721 Ethereum proves the actual battle , The course is a digital art creation and sharing DApp The actual development of the main line , In depth to explain the concept of Ethereum heterogeneity pass 、 Standards and development programs . It contains ERC-721 Autonomous implementation of standards , Explain OpenZeppelin Second development of contract code base , The actual project adopts Truffle,IPFS, It has realized the general stock exchange and decentralized general stock exchange .
  • C# The etheric fang , It mainly explains how to use C# Based on Development .Net The Ethereum application of , Including account management 、 Status and transactions 、 Smart contract development and interaction 、 Filters and trading etc .
  • java Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to Java Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes Java A rare bitcoin development learning course for Engineers .
  • php Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to Php Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes Php A rare bitcoin development learning course for Engineers .
  • c# Bitcoin development tutorial , This course is for beginners , It covers the core concepts of bitcoin , For example, blockchain storage 、 Decentralized consensus mechanism 、 Keys and scripts 、 Trade with UTXO etc. , At the same time, it also explains in detail how to C# Bitcoin support function is integrated in the code , For example, create an address 、 Manage your wallet 、 Construct naked transactions, etc , yes C# A rare bitcoin development learning course for Engineers .
  • EOS Introductory tutorial , This course helps you get a quick introduction to EOS Development of decentralized application of blockchain , Content covered EOS Tool chain 、 Accounts and wallets 、 Issue tokens 、 Smart contract development and deployment 、 Use code to interact with smart contracts and other core knowledge points , At last, we use all the knowledge points to complete a note DApp Development of .
  • Play in depth EOS Wallet development , This course uses mobile phones EOS The whole development process of wallet is the main line , Learn more EOS Blockchain application development , The course covers accounts 、 Computing resources 、 Intelligent contract 、 Actions and transactions, etc EOS The core concept of blockchain , It also explains how to use eosjs and eosjs-ecc Development package access EOS Blockchain , And how to React Integration of front-end applications EOS Blockchain support . The content of the course is simple , It's very suitable for front-end engineers to study deeply EOS Blockchain application development .
  • tendermint Blockchain development details , This course is suitable for the students who want to use tendermint Engineers who develop blockchain , The course includes tendermint The core concepts in the application development model , for example ABCI Interface 、 Ms merkel tree 、 Multi version state library, etc , It also includes rich practical codes such as token issuance , yes go The best choice for language engineers to get started with blockchain development .

Original translation of Huizhi , Reprint please indicate the source . Here is the original Use Hyperledger Fabric and Composer Implement blockchain applications

版权声明:本文为[Pen Pavilion]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2021/05/20210515012020243q.html