Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Fabric and Composer to realize Block chain in Hyperledger

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how to use Fabric and Composer to achieve blockchain in Hyperledger. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

About Project Hyperledger

Hyperledger is the name of a umbrella project under which open source blockchain methods and tools are developed collaboratively. It was launched by the Linux Foundation in 2015 and enjoys enthusiastic participation from software giants such as IBM, Intel and Fujitsu, as well as large communities. Hyperledger's GitHub repository is now more active than ever. Anyone can participate in the development.

In Hyperledger, not only a single blockchain framework (or platform) has been developed. Instead, the focus is on using multiple approaches in parallel to create synergies, reusable components and flexibility. From a Hyperledger conceptual point of view, blockchain networks cannot be compared to representatives of cryptocurrencies such as Bitcoin or Ethernet. In contrast, the nodes of Hyperledger networks are distributed among participating organizations, which makes private, licensed, or federated block chain networks particularly interesting. First of all, we can forget the public block chain of work proof, equity proof and other consensus mechanisms. The organizations involved validate each other's transactions and interests as a consortium in terms of the application's business value and the trust involved. This also largely solves the scalability problem (we know from the Bitcoin network) and enables high transaction throughput.

The different blockchain methods for project Hyperledger 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 will cover Fabric in detail in this article because it has the most active community and is the most flexible variant. Because of its powerful modularity, fabric is universally available. "you can think of Hyperledger Fabric as similar to Apache Web Server," said Brian Behlendorf, executive director of the Linux Foundation Hyperledger. Other methods are more used to implement special situations in a limited environment.

Hyperledger Fabric-- A flexible Block chain Application platform

Using 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 blockchain network is based on the modeling of the desired organizational structure. Each participant has a fixed identity and can be identified by the certificate issued. In addition to authentication, authorization is also included. Using this role-based system, you can get flexible aspects of privacy and confidentiality in the licensed block chain. For certificate and participant management, you can use a structural certificate authority (a member service provider prior to version 1.0).

The definition of the asset (the project to be managed on the blockchain) depends entirely on the blockchain application. These assets, such as engine blocks from the automotive industry, are defined by key-value pairs models in JSON and / or binary format.

The concept of chain code is designed to implement business logic based on assets and their owners. This can be used to implement rules in languages such as Go,Java or Node.js that define read permissions or asset modifications. The execute chain code function reads and returns assets and / or creates and modifies assets and stores them in the local ledger database. After local persistent changes on the node, the changes are submitted to the network ("approved") and inserted into the block chain after they are accepted by other organizations. In the context of Ethernet Square or other public block chain platforms, chain codes can be compared with intelligent contracts.

The channel is used to realize the privacy domain. In the simplest scenario, the entire chain code is deployed on a single channel joined by all participants. However, in order to create an encapsulation area and allow only selected participants to communicate in it, you can configure a channel with a restricted group of participants. Each channel can deploy different chain code, so that functional isolation can be achieved. In addition, you can use AES to partially or fully encrypt communication in the channel.

As a result, a distributed ledger is maintained in each channel, which can be thought of as a cash book for linked 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, which become encrypted chains in a single connection list.

However, in order to provide a separate view of the ledger data to the client application, you can even perform complex read requests against the network. This is possible due to the use of document-oriented databases such as CouchDB. This provides flexible data access for clients connected to the Fabric network.

Use Composer to add simpler concepts

Hyperledger-Composer is one of the tools in the Hyperledger ecosystem. You can think of it as a framework for Fabric. If you want to develop, build, and manage Fabric networks, it is practical, if not mandatory. It introduces further concepts based on Fabric to provide elegant abstractions.

In addition to assets, you can define scenarios for network participants, transactions, and events in the Composer modeling language. The flow for each transaction type is implemented on a simple API through JavaScript code. Access control files can be used to restrict participants' access to certain resources. You can define common queries for data in ledgers in Composer Query Language, a language similar to SQL.

All necessary files must then be packaged into the BND (business network definition) in the .bna file. You can then install this archive on an existing Fabric network. The source code for BND can of course be developed and tested locally in our preferred editor, so version control can be done through Git. For prototyping and demonstration purposes, there is Composer Playground. This provides a modern, clear and intuitive Web interface with access to the local configuration of Composer CLI. With Playground, you can easily create, install, test, edit, import and export BND.

In Composer Playground, you can install, modify and test new business networks in a user-friendly manner without previous knowledge of sample block chain applications (such as vehicle life cycle, car auction or farm animal tracking). After setting up the tool, we can do the same thing locally so that we can leave the hosting playground after playing the game for a short time. This playground is ideal for using prototypes to validate ideas and understand the underlying Composer and Fabric models.

Use case: supply chain tracking of engine blocks

In order to use Hyperledger-Fabric and Composer to implement private block chain network, take engine tracking in the automobile industry as an example. In this case, there are manufacturers and distributors as network participants. The engine and its installed vehicle are shown as assets. The companies of manufacturers and distributors are introduced and identified as organizations in the network.

The Fabric chain code should provide the following functions:

1. Production of engine blocks with unique serial numbers.

two。 Transfer the engine cylinder block to the dealer after production.

3. Track the serial number of the vehicle.

4. Install the engine cylinder block into the registered vehicle.

The next step is to install the required tools and set up the project.

Development environment settings and project creation

First, you need to install all the requirements for Fabric listed in the documentation. Then we install the requirements of Composer and Composer and their associated tools themselves.

Then, it's best to familiarize yourself with the new environment. If we completely follow the instructions of the previous link, fabric-tools is now in our home directory. With the script described, we can start a simple Fabric network in Docker-Compose, gain peer administrator access, and stop and delete it again. First, we download the version 1.1 Docker image and start the network:

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

While the network is running, composer-playground web-UI can be started through composer-playground. It uses all the managed configurations of composer-cli and accesses the running Fabric network. From now on, we think of Fabric as a configurable platform / infrastructure whose status is changed through the appropriate tools. We do not directly use Fabric concepts to develop chain code, permissions, or any model, because Composer provides more advantages.

Implementation function

Now let's create our BND project in the directory of our choice. For Yeoman (a code generator that uses templates to set up a project, such as Maven Archtypes), there is a template (hyperledger-composer:businessnetwork. However, I have prepared a repository, and we can now use JavaScript ES6 and some good tools. We should start from the beginning of the branch. Master branches have a final version and a working version. Let's 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 is ideal for Composer because it has installable syntax highlighting extensions. After a little modification, you will find that it is a NPM project, so let's install all the dependencies from npm install. With npm test we can run unit tests, with npm run lint we can test code styles, and with npm run createArchive we can create the.bna files, and we complete the business network definition in a packaged format. Let's try to see if everything is all right right away.

Then we are familiar with the project structure. The lib folder contains the JS file that implements the transaction processor function. Of course, we want to test this business logic and store our unit tests in the test/ folder. Model definitions (participants, assets, transactions, etc.) are in models/.

We want to first model the desired blockchain network. To do this, we delete the contents of the model file and specify a new namespace in the first behavior:

Namespace org.acme.enginesupplychain

We model participant manufacturers and distributors and use inheritance of the Composer modeling language. We also want each participant to have an optional address in addition to his or her name. Let's 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: the engine block and the car with the engine installed later. Here, we understand that assets and participants can refer to each other. References always point to existing resources of any type. Our attributes that start with a small "o" always exist 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 available actions that can be performed on top of existing assets and actors. These are trading resources. After that, we test and implement the basic transaction logic for each of the following transaction 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 that we have defined what might happen, we can start to implement how it affects the ledger state when we submit the transaction. First, we are committed to creating engine assets. The engine should get the randomly generated ID in UUID format and should always belong to the manufacturer from the start. So let's empty the logic.js file and start from scratch. We define the constant modelsNamespace and the function uuid because we will need them more frequently. Next is the createEngineAsset function. The document block above the function is important so that Composer 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 ()} `} / * Creation of an 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 have also implemented other transaction types 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 transactions')}} / * * 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, and if we have experience, we don't need to know more. Only the boostrapping for this required object is still a bit overloaded with boilerplate code. The test first starts the in-memory Fabric network, installs the business network on it, and then authenticates it as the default administrator. Because this Composer provides the libraries composer-admin,composer-client,composer-common and composer-connector-embedded. After the test setup, we can now write test cases for the embedded network. The setup code is not included in the list because of its length, but can be viewed and tested on the main branch in test/EngineSupplychainSpec.js.

Unit test cases used to test transaction types usually have a similar pattern. They use their attributes and relationships to recreate the transaction, execute the transaction against the network, and then check the data status of the assets and participants involved. Let's take a look at the existing test cases for createEngineAsset.

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 +' .Manufacturers') 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)})})

The way to implement the definition of a business network in Hyperledger Composer should be made clear through these insights. In addition, BND can define more things for us. In permissions.acl, you can use the access control language to define access restrictions for participants with given simple conditions. Event and query capabilities are also useful and interesting for many applications.

Finally, let's take a look at the solution on the main branch. All these requirements have been implemented and tested. We now use npm run createArchive to generate the finished .bna file, and then in the dist/ folder. We can now import it into the Composer Playground we started in the console to try it on our local Fabric network. The way of passing Web UI should be self-evident, but it is also officially recorded.

Summary and prospect

We have learned about the important parts of the Hyperledger project. Specifically, we now know Fabric as a blockchain platform with basic concepts. Composer adds many important concepts that make it very easy for developers to implement and manage blockchain networks. Through the implementation of a block chain application case for engine block production and tracking, we have learned about a simple but powerful private / alliance block chain use case.

The final blockchain network is initially executed locally only. We have not yet expanded the configuration of peer organization and ordering services. But we can easily add more organizations and distribute peer nodes through multiple hosts. For blockchain networks spanned by real organizational alliances, we still have some problems to solve:

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

This still young platform already offers a lot of features and comfort. However, there are still many tasks to be done. From the developer's point of view, the unit test code still looks bloated. The library will soon be available, making it easier to implement the usual test patterns. We are eager to see how projects such as Hyperledger will continue to drive the adaptability of distributed ledger technologies in the business.

Troubleshooting

Ensure that all tools are compatible with Fabric 1.1. This means that all docker images for this version must be downloaded. The latest versions of Composer and Composer Playground should be installed. It is currently v0.19.1. All links to the Fabric and Composer documents in this article are intentionally fixed to Fabric 1.1 and the latest Composer version.

=

Share some interactive online programming tutorials related to Hyperledger fabric, ethernet, Bitcoin, EOS, Tendermint, etc.

This course is for beginners. It includes core concepts such as Hyperledger Fabric identity certificate and MSP service, authority policy, channel configuration and startup, chain code communication interface, as well as Fabric network design, nodejs chain code and application development. It is the best choice for Nodejs engineers to learn Fabric block chain development.

The course is aimed at beginners, including Hyperledger Fabric identity certificate and MSP service, authority policy, channel configuration and startup, chain code communication interface and other core concepts, as well as the operation practice of Fabric network design, java chain code and application development. It is the best choice for java engineers to learn Fabric block chain development.

The java ethernet development tutorial is mainly for java and android programmers to conduct a detailed web3j explanation of blockchain ethernet development.

Python ethernet, mainly for python engineers to use web3.py for block chain ethernet development of the detailed explanation.

Php Ethernet Square, mainly introduces the use of php for intelligent contract development interaction, account creation, transaction, transfer, token development, filter and transaction and so on.

Introduction to Ethernet Square tutorial, mainly introduces the intelligent contract and dapp application development, suitable for entry.

Yi Tai Fang development advanced tutorial, mainly introduces the use of node.js, mongodb, block chain, ipfs to achieve decentralized e-commerce DApp practice, suitable for advanced.

ERC721 focuses on Taifang pass practice, and the course focuses on the practical development of a digital art creation and sharing DApp. It deeply explains the concept, standard and development scheme of ethernet non-homogenization pass. The content includes the independent implementation of ERC-721 standard, explains the secondary development of OpenZeppelin contract code base, the actual combat project adopts Truffle,IPFS, and realizes the pass and decentralized stock exchange.

C # Ethernet Square, mainly explains how to use C # to develop .net-based Ethernet Square applications, including account management, status and transactions, intelligent contract development and interaction, filters and transactions, etc.

Java Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Java code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Java engineers.

Php Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Php code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Php engineers.

C # Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into C # code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare Bitcoin development course for C # engineers.

EOS introduction course, this course helps you quickly get started with the development of EOS block chain decentralized applications, covering core knowledge points such as EOS tool chain, accounts and wallets, issuing tokens, smart contract development and deployment, using code and intelligent contract interaction, and finally using all knowledge points to complete the development of a note DApp.

Play with EOS wallet development. This course focuses on the complete development process of mobile EOS wallet, and deeply studies the application development of EOS blockchain. The course covers the core concepts of EOS blockchain, such as accounts, computing resources, intelligent contracts, actions and transactions. It also explains how to use eosjs and eosjs-ecc development packages to access EOS blockchain, and how to integrate EOS blockchain support in React front-end applications. The content of the course is profound and simple, which is very suitable for front-end engineers to study the application development of EOS block chain.

Tendermint block chain development detailed understanding, this course is suitable for engineers who want to use tendermint for block chain development, the course content includes the core concepts of tendermint application development model, such as ABCI interface, Merkel tree, multi-version state library, etc., as well as rich practical code such as token issuance, it is the best choice for go language engineers to get started with block chain development.

The above is how to use Fabric and Composer to achieve blockchain in Hyperledger. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report