My personal notes, example codes, best practices and sample projects.
Aditya Hajare (Linkedin).
WIP (Work In Progress)!
Open-sourced software licensed under the MIT license.
- Blockchain Basics
- Why Blockchain As Opposed To An Ordinary Database
- Key Concepts
+ Blockchain + Distributed Ledger + Transactions + Chaincode + Channel Events + Chaincode Lifecycle Endorsement Policy Rule + Peer Launch Modes + Client Side API + Arguments Sent To Chaincode + Transaction Flow + Chaincode Interface + The Fabric Model: What makes fabric ideal as an enterprise blockchain solution? - Assets - Chaincode/Smart Contracts - Ledger - Privacy - Security And Membership Services - Consensus + Identities + Policies + Peer + Ledger + Orderer + Channels
- Blockchain Technology Benefits
- Smart Contracts
- Development Environment Setup
- CouchDB
- Private Data Collections
- Range Queries
- Rich Queries
- Asset History Logs
- Programmatic Access Control
- Fabric Node SDK
- Common Errors
- It is a decentralized system. Decentralized means the network is powered by its users (Peers) without having any third party, central authority or middleman controlling it.
- Every Peer has a record of the complete history of all transactions as well as the balance of every account.
- This bookkeeping is not controlled by one party or a central authority (E.g. Central Bank).
- Its all Public, and available in one digital ledger which is fully distributed across the network. i.e. everybody sees what everybody is doing.
- The Blockchain acts as a public ledger.
- In blockchain all the transactions are logged including:
- Time
- Date
- Participants
- Amount of every single transaction
- Each node in the network owns the full copy of the blockchain.
- The nodes automatically and continuously agree about the current state of the ledger and every transaction in it.
- If anyone attempts to currupt a transaction, the nodes will not arrive at a consensus and hence will refuse to incorporate the transaction in the blockchain.
- So every transaction is public and thousands of nodes unanimously agreed that a transaction has occurred on date X at time Y.
- Everyone has access to shared single public source of truth.
- Blockchain in first instance is all about optimizing Shared B2B Processes.
- In a nutshell, a Database solves a Data Problem whereas a Blockchain solves a Digital Asset Problem.
- Database Solves a Data Problem:
- Mature technology exists.
- Centralized or Distributed.
- Fit for purpose.
- One party governs the data.
- Blockchain solves a Digital Asset Problem:
- Trade, trust and ownership.
- Digital Assets.
- Transactionality.
- Multiple parties govern the data.
- Remove intermediaries.
- Solve double spend problem.
- Need for time and trust in a network.
- Gives birth to new business models.
- Blockchain: It is a shared, replicated transaction system (Distributed Ledger) which is updated with the help of Smart Contracts and kept consistently synchronized through a process called Consensus. It is a append-only transaction system.
- Distributed Ledger: It is a database that is concensually shared and synchronized across multiple sites, institutions or geaographies and it is accessible by multiple people.
- Smart Contracts: It is a self-executing contract with the terms of the agreement between buyer and seller being directly written into lines of codes. The code and the agreement contained therein exists across a distributed, decentralized blockchain network.
- Consensus: The majority of opinion, agreement amoung a group of people.
- Private Blockchain vs. Public Blockchain: In public blockchain, anyone can send a transaction, while in private blockchain, only participants who are approved can send transactions.
- Permissioned Blockchain vs. Permissionless Blockchain: Permissionless blockchain allow people to act anonymously (you do not know their identity), while in permissioned blockchain the identities of participants are known.
- Examples of Public and Permissionless Blockchain: Bitcoin, Etherium.
- Examples of Private and Permissioned Blockchain: Hyperledger Fabric, JP Morgan.
- Cryptocurrencies (Bitcoin, Etherium etc.): Cryptocurrency is not same as a blockchain. Cryptocurrency use blockchain to store transactions. Most of the cryptocurrencies use their own type of blockchain with some aspects that make them unique and best for their own usecase.
- Distributed Ledger:
Distributed Ledgerplatforms are used for tracking theStateof anAsset.- An
Assetis a digital representation of any real world thing. - So anything in a real world, whether it's a tangible or intangible, that may be digitally represented, can be managed on a
Distributed Ledger. - Tangible assets examples: Cars, Houses, etc.
- Intangible assets examples: Stocks, Bonds, Certificates and any other kind of financial instruments.
- Transactions:
- The state of an
Asseton theDistributed Ledgeris managed by the way ofTransactions. In other words,Transactionsmanages theStatesof anAsset. Transactionrepresents the invocation of business logic that changes or manages theStateof theAssetson theDistributed Ledgerplatform.Chaincodeencapsulates the business logic.- All
Transactionsare recorded in theLedger. - The recorded
Transactionsare immutable. i.e. they cannot be updated or deleted.
- The state of an
- Chaincode:
Chaincodeimplements the business logic and exposes theStatemanagement features by way of one or more functions.- The functions exposed by
Chaincodeare executed from theApplicationsby way ofTransactions. - Not all of the
Transactionslead to the creation of entry inLedger. SomeTransactionsare performed to readStateof anAssetin theLedger. - Fabric Chaincode can be developed in
Golang,NodeJSorJava. - Any real world asset that can be degitized can be represented as a
Modelin theChaincode. - Each of the chaincode in the network is identified by a name which is unique across
Channel. Instantiation Policydetermines whichOrgcanEndorsetheTransactionfor creation of theChaincode.- Peers receive the chaincode package in the instantiate transaction and hence the installation of chaincode on peer is automatic: FALSE.
Shim APIis used for coding theChaincode.- Not all
Orgsneed to installChaincode. Following entities has theChaincode:Orgsparticipating in thetransactions.Orgsthat will query theledgers.Chaincode Endorsers
- Important points about
Chaincode:Chaincodemay implement multipleSmart Contracts.Chaincodeis packaged in standardTarfile format.Installationgenerates thePackage-ID.- Each
Orgapproves the specificPackagefor theirOrg. Package-IDmay be different acrossOrgs.- Whenever a
Chaincodeis approved by anOrg, theApprovalis added as aTransactioninto theLedgerof thatOrg.
- By default
State Datais setup inLevelDBbut we can configurePeerto storeState DatainCouchDBinstead ofLevelDB. CouchDBis aNoSQLdatabase which can be setup as aState Datastore forPeernode.CouchDBallows to execute rich queries againstState DatawhereasLevelDBdoesn't allow it.- Each
Chaincodeowns theState Datait manages. - Direct access to
State Datafrom oneChaincodeto another is not allowed. However,ChaincodecanInvokeorQueryotherChaincodeto access it'sState Data. - Invoke
Chaincodefrom anotherChaincode:- Since the
Chaincodeis invoked locally, both theChaincodes(caller and the calledChaincode) must be on the samePeer. Transactionexecutes in the sameTxnContext.Statechanges on both the caller and the calledChaincodetake effect only if they share a commonChannel.- No
Statechange takes place on the calledChaincodeif the caller and a calledChaincodesare on differentChannels. Transactionmessage is passed from the callerChaincodeto the calledChaincode.- On common
Channel:Statechanges take effect for both caller and a calledChaincode. - On different
Channel:Statechanges take effect only for the callerChaincode.
- Since the
- Channel Events:
- Events are emitted by the
Peers. - Applications may subscribe to the events.
Subscriptionis onChannellevel. i.e.Subscriptionrequires the specification of theChannel.- Subscribers can also specify the filter criteria on which the events are evaluated on the
Peer.
- There are 3 types of Events:
Block Event: Emitted by thePeerwhen a newBlockis added by thePeerto theLedger.Transaction Event: Emitted by thePeerwhen a specifiedTransactionis received in aBlock.Chaincode Event: Emitted by theChaincode.Chaincode Eventsare generated in response to theTransactionsagainst theChaincode.
Chaincode Eventsare not received by the subscriber when theChaincodeis executed by theEndorsers. The events are received by the subscriber when thePeeradds theTransactionto theLedger.- The subscriber can provide the name of the
Eventin which they are interested. - The
Transaction EventandChaincode Eventsare in theBlockpayload.
- Events are emitted by the
- Chaincode Lifecycle Endorsement Policy Rule:
- Network members sets up the
Lifecycle Endorsement Policy. - It decides:
- How many approvals are needed for a commit to be successful.
- It may have a rule that says some specific
OrganizationmustEndorsetheTransactionfor it can be committed successfully.
- This
Policyis embedded in theChannelGenesis. Rulescan be updated withChannelupdate transactions.Lifecycle Endorsement Policycan be specified asImplicitMeta Policyor aSignature Policy.- Default
Policyis theRule = "MEJORITY Endorsement". It means thatMore than HALF the members of the network MUST approve the Chaincode definition for it to be committed successfully. - The
PolicyruleRule = "ANY Endorsement"requiresOnly one approval for committing the Chaincode. - With the help of
Signature Policy, we can create complex/flexible expressions.
- Network members sets up the
- Peer Launch Modes:
Netmode:Chaincodeinstance launched byPeer. This is the Default mode.- Used in live network.
- Chaincode Logs are written to the container's file system.
Devmode:Chaincodeinstance launched by Developer.- Development time only.
- Chaincode Logs are written to the console.
- No need to install/upgrade for changes.
- To launch
PeerinDevmode:
# 1. Launch peer in dev mode peer node start --peer-chaincodedev # 2. Install chaincode to Peer # 3. Run chaincode on Terminal/Shell # 4. Instantiate the chaincode to Peer
- NOTE: Chaincode instance is not launched in the Docker container.
- Helper scripts:
##### BOTH COMMANDS USE ENV VARS! ##### # Builds the Golang chaincode /network/bin/cc-build.sh # go build $CC_PATH # Runs the Golang chaincode /network/bin/cc-run.sh # go run $GOPATH/src/$CC_PATH/*.go
- Example commands:
cd /network/bin/ # Initialize dev environment in Dev mode. # -d: Dev mode ./dev-init.sh -d # Set env vars for "acme" Org source ./set-env.sh acme # Check/verify env vars for Org ./set-chain-env.sh # Package and install chaincode on Peer # -p: Package chaincode ./chain.sh install -p # In new terminal, ssh into vagrant # Set Org context in new terminal source set-env.sh acme # Start chaincode in Terminal mode cc-run.sh # In other terminal, we can run following commands chain.sh instantiate # To instantiate the chaincode chain.sh invoke # To invoke chaincode chain.sh query # To query chaincode
- Client Side API:
Chaincodegets deployed on thePeer.Applicationsuse theFabric Client SDKfor interacting with theChaincode.- There are 2 APIs that are used by the
Applications.- Invoke API: Used for executing the business logic in the
Chaincodeby way ofTransactions. - Query API: Used for reading the
Stateof theAssetsfromDistributed Ledgerplatform.
- Invoke API: Used for executing the business logic in the
- Both
Invoke APIandQuery APIexecutes the functions exposed by theChaincode.
- Arguments Sent To Chaincode:
- The
Client Side APIexecutes the functions by passing data in JSON format to theChaincode. - The JSON object has a key called
Args, which is set to an array of string types. The first element in theArgsarray is thefunction namewhich will be executed by theChaincodein response of this API invocation on the client side. Rest of the arguments in theArgsarray are the parameters passed to the function called byChaincode.
{ "Args": ["FunctionName", "Param1", "Param2", "Param..n"] } - The
- Transaction Flow:
- When client executes an
InvokeAPI, theTransaction Proposalis created and it is sent to theEndorsing Peers. If everything is good with the proposed transaction, theEndorsing PeersSigntheTransaction Proposaland send it back to the client. The client then sends theSigned Transaction Proposalto theOrderer Servicefor including the transaction in theBlock.Orderer Serviceat some point creates theBlockand sends theBlockto thePeersin theNetwork. Not all of thePeershaveChaincodeinstalled on them. ThosePeerswill still receive theBlocksent byOrderer Service. - When client executes a
QueryAPI, any of thePeerwith aChaincodeinstalled on it, will execute theChaincode Functionand return response to the client. In this invocation, the client does not go through theOrderer Service.
- When client executes an
- Chaincode Interface:
- All Golang
Chaincodemust implement following 3 functions:Init(): Chaincode initialization logic. Called withinvoke --is-initflag.Invoke(): Contains business logic. Executed onQueryandInvoke [Without init flag].main(): Registers chaincode with the fabric runtime.
- All Golang
- The Fabric Model: What makes fabric ideal as an enterprise blockchain solution?
- Assets:
- Asset definitions enable the exchange of almost anything with monetory value over the network. For e.g. Whole foods, antique cars, currency features, bonds, stocks, digital goods etc.
- Asset within the network are represented as a collection of key-value pairs with state changes that records the transaction on the ledger or distributed ledger.
- Assets can be represented in
BinaryandJSONformat. - There are 2 types of Assets viz.
Tangible AssetsandIntangible Assets- Tangible Assets: Tangible assets are typically physical assets or properties owned by a company. For e.g. Computer equipment. Tangible assets are the main type of assets that companies use to produce their product and service.
- Intangible Assets: Intangible Assets don't exists physically, yet they have a monetory value since they represent potential revenue. For e.g. stock, bond, copyright of a song. The record company that owns the copyright would get paid a royalty each time the song is played.
- Chaincode/Smart Contracts:
- Chaincode contains the smart contracts.
- Many times chaincodes and smart contracts are used interchangeably because in most cases they mean exactly the same.
- Chaincode defines the asset and also enforces rules for interacting with the asset or any other information that is stored on the distributed ledger.
- Chaincode functions execute against the ledger's current state database and are initiated through transaction proposals.
- Chaincode execution results in a set of key-value pairs which are also called a
Right Set. Right Setcan be submitted to the network and thereby append to the ledger.- Chaincode execution is partitioned from transaction ordering, limiting the required level of trust and verification across node types, and optimizing network scalability and performance.
- Chaincode or Smart Contracts define all the business logic.
- Chaincode/Smart Contracts are stored on
Peernodes.
- Ledger:
- Ledger contains all of the state mutations or transactions. These state changes are produced by the invocation of chaincode.
- The immutable, shared ledger encodes the entire transaction history for each channel, and includes SQL-like query capability for efficient auditing and dispute resolution.
- Ledgers store all of the data.
- Ledgers are stored on
Peernodes.
- Privacy:
- Channels and Private Data Collections enable private and confidential multi-lateral transactions that are usually required by competing businesses and regulated industries that exchange assets on a common network.
- Security And Membership Services:
- In Fabric Network, all participants have known identities.
- Public key infrastructure is used to generate cryptographic cenrtificates. These certificates can be tied to an organization, a network component, a user or a client application. These certificates can be used to manage data access control.
- Role based governing with the help of certificates is the thing which made Fabric
Permissioned. - Permissioned membership provides a trusted blockchain network, where participants know that all transactions can be detected and traced by authorized regulators and auditors.
- Consensus:
- At a very high level, we can say Consensus Model has something to do with multiple participants agreeing on something.
- A unique approch to Consensus enables the flexibility and scalability needed for the enterprise.
- Assets:
- Identities:
- Every actor in a network has a digital identity. It is represented by
X-509certificate. - Identities determine resources and access to information for actors.
- This determination is done based on attribute called
Principalsin certificate. - The identity with attribute are called
Principals. We can think of aPrincipalas some sort of a userid. - Identities are created by a trusted
Certificate Authority. In fabric, we can use aCertificate Authority. - The process of handing out certificates is called
PKI(Public Key Infrastructure).PKIprovides a secure way of communication. - Just having certificate is not enough for any actor. We also need the network to acknowledge the certificate. For e.g. we need organization to say - "Yes this certificate belongs to my organization". The
Identitymust be registered in the organization'sMSP(Membership Service Provider). MSP(Membership Service Provider) turns verifiable identities into members of the blockchain network.PKI(Public Key Infrastructure) is a collection of internet technologies that provides secure communication in the network.PKI(Public Key Infrastructure):- Digital Certificates
- Public and Private Keys
- Certificate Authorities
- Certificate Revocation Lists
MSP- For a member to have an access to the network, we need 4 things:- Have an identity issued by a CA that is trusted by the network.
- Become member of an organization that is recognized and approved by the network members.
- Add the
MSPto either a consortium on the network or a channel. - Ensure the
MSPis included in the policy definitions on the network.
- Every actor in a network has a digital identity. It is represented by
- Policies:
- A policy is a set of rules that can define how a decision is made.
- Policies describe a who and a what.
- In Hyperledger,
Policiesare used for infrastructure management. - Uses of
Policiesin Hyperledger network:- Adding/Removing members from channel.
- Change the structure of blocks.
- Specify count of organizations for endorsement of transactions
- How do we write
Policyin Fabric:- Signature Policies:
- Turns verifiable identities into members of a blockchain network.
<OR | AND | NOutOf>
- ImplicitMeta Policies:
- Only used for channel configuration.
<ANY | ALL | MAJORITY>
- Signature Policies:
- Peer:
Chaincodes/Smart ContractsandLedgersare stored onPeernodes that are owned byOrganizationsinside the network.Peernodes can host multiple instances ofChaincodesandLedgers.- End-users communicate with the network by using applications that connect to the
Peernodes of theirOrganization. PeersuseChannelsto interact with other network components.- All
Peersbelong toOrganizations. Peershave anIdentityassigned to them via a digital certificate (x.509).- Single Peer itself cannot update information stored in ledger on it. Updating requires a consent of other Peers in network. The update transaction is done in 3 steps:
- Step #1:
Proposal.- Independently executed by
Peersand returnsEndorse Proposalresponses.
- Independently executed by
- Step #2:
OrderingandPackagingtransactions into blocks.OrdererreceivesEndorsedtransactions and then creates the blocks.
- Step #3:
ValidationandCommitof the transaction.- When
Peerreceives a new block from theOrderer, thePeerprocesses the block resulting in a new block being added to theLedger.
- When
- Step #1:
- Ledger:
- On the ledger, we are recording facts about current state of the object.
- Change history in ledger is immutable.
- In Fabric, ledger consists of 2 parts:
World State:- It is a database that holds the current value of the object.
- It can change frequently.
Blockchain:- It records all the transactions for the object that together results in a
Current World State. - Transactions are collected inside blocks that are appended to the blockchain.
- Blockchain data structure is very different from
World State. It's immutable. - Blockchain does not use a database.
- Blockchain is implemented as a file. The reason for this is because there are just few operations done on a Blockchain.
- Primary operations of a Blockchain is to append data to it. And a file is perfect for that.
- First block is called the
Genesis Block. It does not contain transaction data. It contains configuration of a initial state of a network channel. - Blocks are connected together with the
Headerof a block. - Each block in blockchain has following structure:
- Block Header: Contains following parts:
- Block Number: Integer starting at
0(Genesis Block), and increased by 1 for each new block. - Current Block Hash: Hash of all the transactions contained in the current block.
- Previous Block Header Hash: Hash from the previous
Block Header.
- Block Number: Integer starting at
- Block Data: Contains list of transactions arranged in order.
- Block Meta-Data: Contains certificate and the signature of the block creato which is used to verify the block.
- Block Header: Contains following parts:
- It records all the transactions for the object that together results in a
- Orderer:
- Orders transactions into blocks.
- Maintains list of Organizations that can create channels. This list of Organizations is called the
Consortium. Also, this list is stored in aSystem Channel(Channel for the Orderers). - Enforce access control for channels (Application Channels). This way they can restric user from Reading and Writing on a Channel.
- Manage structure of the blocks.
- We can tweak the structure of the blocks by setting the
BatchSizeandBatchTimeoutparameters.- BatchSize: Maximum transaction count in one block.
- BatchTimeout: Maximum time for a new block creation. This time is measured from the first transaction received in this new block.
- Ordering service implementations:
- Kafka (Deprecated since Fabric v2)
- Solo (Deprecated since Fabric v2)
- Raft (Recommended): It is a
Crash Fault Tolerant (CFT)ordering service. It implementsLeader-Followermodel.
- It is better to have multiple Orderer nodes that are owned by different Organizations. This way we make sure that even the ownership is decentralized.
Raftis a protocol for implementing distributedConsensus.- In
Raftthere are 2timeoutsettings which control the elections:- Heartbeat Timeout
- Election Timeout
- Raft Election Process: It's the amount of time a
Followerwaits until becoming aCandidate. AfterElection Timeout, theFollowerbecomes aCandidateand starts a new election term, votes for itself and sends outRequest Votemessages to other nodes. If the receiving node hasn't voted yet in this term then it votes for theCandidateand the node resets it'sElection Timeout. Once theCandidatehas a majority of votes, it becomes aLeader. TheLeaderbegins sending outAppend Entriesmessages to it'sFollowers. These messages are sent in intervals specified by theheartbeat timeout. Followers then respond to eachAppend Entriesmessage. This election term will continue until a follower stops receiving heartbeats and becomes a candidate. If 2 nodes become candidate at the same time then a split vote can occur. Once we have a leader elected, we need to replicate all changes to our system to all nodes. This is done by using the sameAppend Entriesmessage that was used forheartbeats. Raft can even stay consistent in the face of network partitions.
- Channels:
Channelsare created by creating the firstTransactionand submitting theTransactionto theOrdering Service. ThisChannelcreationTransactionspecifies the initial configuration of theChanneland it is used by theOrdering Serviceto write theChannels Genesis Block.- We can use
Configtxgentool to create the firstTransactionwhich will end up creatingChanneland writingGenesis Blockon thatChannel. - The
Configtxgentool works by reading thenetwork/configtx/configtx.yamlfile which holds all of the configurations for theChannel. This file usesChannel Profiles. Configtxgen:- Reads from the
network/configtx/configtx.yamlfile. - Can create a
Configuration Transactionfor theApplication Channel. - Can create a
Genesis Blockfor theSystem Channel.
- Reads from the
- Security:
- Since Blockchain is a distributed concensus based architecture, it's eliminates single point of failure and reduces the need for data intermediaries such as transfer agents or messaging system operators.
- It helps prevent frauds and malicious third parties from doing bad things.
- Its not fullproof and we do hear about hacks in the box or certainly in cryptocurrency or cryptocurrency exchanges but its very very difficult to hack or manipulate.
- Transparency:
- It provides transparency and in place multialise standards, protocols and shared processes.
- Trust:
- Its transparent and the immutable ledger makes it easy for different parties in a business network to collaborate, manage data and reach agreements.
- Programmability:
- Its programmable, so its able to execute things like smart contracts and help be more tamper proof and have deterministic software that automates the business logic.
- We can code to address many different things from governance to compliance, regulatory compliance, data privacy, identity, looking at things like "know your customer" types things or anti money laundring attributes.
- It manages that stakeholder participation, like for things like proxy voting.
- Privacy:
- It provides privacy.
- High-Performance:
- It can be a private network of hybrid networks and they are engineered to sustain hundreds/millions of transactions per second and also handle periodic surges in network activity.
- Scalability:
- Its highly scalable.
- Authenticity and Scarcity:
- Digitization really ensures data integrity and enables acid profits. It's really a full transaction history in that single shared source of truth.
- Streamlined Processes:
- Since it can automate almost everything, it can enable some more real time settlements, auditing, reporting and reduces processing times and the potential for error and the delays due to number of steps and intermediaries required to achieve the same level of confidence.
- Economic Benefits:
- Reduced infrastructure, operational and transaction cost.
- Market Reactivity:
- It can be very reactive to market.
- Contracts:
- A contract is formed when an offer by one party is accepted by the other party.
- Consideration is the price paid for the promise of the other party. The price may not necessarily involve money.
- For e.g. If you walk my dog, i will feed your cat.
- For e.g. If you walk my dog, i will pay you 15 Rs.
- Smart Contracts:
Contract terms are agreed to ----> Smart Contract placed on the Blockchain ----> Triggering event causes contract to be automatically executed
- Contract terms are agreed to: Hard coded and cannot be changed without both parties being aware.
- Smart Contract placed on the Blockchain: Public viewed and verified.
- Triggering event causes contract to be automatically executed: If/then statement coding.
- Install
Oracle Virtual Boxhttps://www.virtualbox.org/wiki/Downloads. - Install
Vagranthttps://www.vagrantup.com/downloads.
# Initialize vagrant and create Vagrantfile
vagrant init
# +-+-+-+-+-+-+-+-+ Configure Vagrantfile +-+-+-+-+-+-+-+-+
# Checkout boxes at: https://vagrantcloud.com/search
config.vm.box = "generic/ubuntu2010"
# Setup network
config.vm.network "private_network", ip "192.168.33.10"
# Mount folder
config.vm.synced_folder "./mount", "/home/vagrant/mount"
# Configure memory
config.vm.provider "virtualbox" do |vb|
vb.gui = true
vb.memory = "10000" #10 GB
end
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Bootup our virtual linux box
vagrant up
# SSH into our running virtual linux box
vagrant ssh
# +-+-+-+-+-+-+- Install HLF Pre-Requisites +-+-+-+-+-+-+-+
# https://hyperledger-fabric.readthedocs.io/en/release-1.4/prereqs.html
# install git
sudo apt install git -y
# install curl
sudo apt install curl -y
# install docker
sudo apt install build-essential -y
sudo apt install apt-transport-https ca-certificates gnupg-agent software-properties-common -y
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose -y
sudo usermod -aG docker $USER
newgrp docker
# install go
curl -o "go.tar.gz" https://storage.googleapis.com/golang/go1.17.1.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf "go.tar.gz"
export PATH=$PATH:/usr/local/go/bin
source ~/.bashrc
# install node
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt install nodejs -y
# install ohmyzsh
# NOTE: Default password for root account on ubuntu: vagrant
sudo apt install zsh -y
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"- Install Samples, Binaries and Docker Images:
# SSH into vagrant
vagrant ssh
# Go to /mount directory
cd mount
# Install samples, binaries and docker images
curl -sSL https://bit.ly/2ysbOFE | bash -s -- 2.2.4 1.5.2- Install
SSHplugin for VSCode. - While vagrant machine is up and running, execute following to get location of
IdentityFile:
vagrant ssh-config- Add new SSH host into VSCode SSH plugin:
# Host can be found in Vagrantfile. Look for following line:
# config.vm.network "private_network", ip: "192.168.33.10"
ssh vagrant@192.168.33.10 -i "C:/Aditya/Projects/HLF/.vagrant/machines/default/virtualbox/private_key"- Add
\binto path:
# In vagrant ssh, execute:
export PATH=/home/vagrant/mount/fabric-samples/bin:$PATH- We can use CouchDB as out
State Database. Ledgercontains aBlockchainand aState Database. Blockchain is implemented as a file and a State Database is implemented as a database.- By default, we use a
Go Level Databaseand this database is implemented in thePeernode. LevelDBstoresChain Codedata askey-valuepairs. It supports queries based onkey,key rangeandcomposite key.- As an alternative
LevelDB, we can useCouchDBas aState Databaseof theLedger. - With CouchDB:
- We can store data as
JSONobjects. - We can write more complicated queries for retrieving specific data.
- We can use
Indexesfor more efficient querying at larger data sets.
- We can store data as
- We need to decide which database we will be using as a State Database before setting up the network. Otherwise, we have to bring down the network, enable CouchDB and bring the network up again.
- Each
Peerhas its own instance of theCouchDB. - No data replication at the
CouchDBlevel. - Remote access is disabled to
CouchDB. CouchDBstores dates in format:YYYY-MM-DDThh:mm:ss.s.
- There are 3 levels of data privacy:
- Channels
- Private Data Collections
- Encryption
Private Data Collectionscan provide privacy for subsets ofOrganizationswithin aChannel.- Private data collection consists of:
- The private data itself
- Hash of the private data
- The Private data cannot be shared with the
Orderingservice. - The Private data is stored on a separate database. Nothing is stored in the
State Database. - Peers that don't have access to the Private Data Collections, don't have any data on their Peer node.
Gossip Protocolis used for communication betweenPeernodes. This is a reason why we need to connect at least onePeernode of theOrganizationto theChannelas anAnchor Peer. Because of this,Peersknow of each other's existence. Thats how we implement Peer to Peer communication usingGossip Protocol.- What can we do with
PDC (Private Data Collection):- Use a corresponding public key for tracking public state.
- Chaincode access control.
- Sharing private data out of band.
- Sharing private data with other collections.
- Transferring private data to other collections.
- Using private data for transaction approval.
- Keeping transactors private.
Memberson theChannelcan restrict visibility of data.Ledgeris COMMON so allTransactionsare still visible to all.TransactioninLedgerhasHASHof data that is stored inPrivate Data Collections.Private Data Collectionare configured using JSON at the time ofChaincodeInstantiateorUpgrade.PeersmanagesPDCdata in a separate set of datastores.PDCare isolatednamespaceswithinChaincode.PDC Key-Valuesare accessible withinChaincodeusingChaincode Stub API.Policiescontrol read access to thePDC.
- Range Queries require
Start Keyand theEnd Key. Start Keyis included in the result set.End Keyis exluced in the result set.- If
Start KeyandEnd Keyare not specified i.e. Empty strings are provided, then result set will have all the Keys from state data set. - Keys are indexed in
Lexical Order. - Maximum results returned in result set can be restricted by
Peer Config. - Commonly used functions from Chaincode Stub API for executing range queries are
GetStateByRange()andGetPrivateDataByRange(). Composite Key:- A key formed by combining 2 or more attributes of the record.
- Uniqueness is guarenteen only if all parts of the key are used.
- None of the
Keyattribute values inComposite Keycan contain anullcharacter. i.e.\0x00 - When the
PutStateis executed, the index is created in thestate database. GetState()andGetStateByRange()functions do not supportPartial Composite Keys.
- Requires data to be modeled as
JSON. Peersneed to useCouchDB.Indexesneed to be created for performance.- Restrictions on CouchDB JSON Documents:
- Key cannot begin with underscore
_. - Fields beginning with underscore
_are used internally. ~versionis a reserved field.
- Key cannot begin with underscore
- Rich queries for
CouchDBare created usingMango Querieslanguage. Mangoquery language:- Declarative
JSONquery language. - Inspired by
MongoDBquery language. - Adopted by
CloudantandCouchDB.
- Declarative
- Rich queries are not executed at the time of
Validation. This may lead to inconsistent state of chaincode. - Do not use
Rich QueriesinUpdate Transactions (Invoke)unless we can guarenteeNo Phantom Reads.
- Fabric manages
Assetsin theChaincode. Invoke Transactionchanges theStateon perKeybasis.- We can use
Queriesto get theCurrent Stateof theAsset. Queriesdon't provide history of theTransactionson specificAsset. i.e.Queriescannot get thePast State. for e.g. List all previous owners of the vehicle with idVin#1000.- To get the history of
TransactionsonAsset, we useHistory LogandHistory API. Asset History Logare managed on perPeerbasis.Peerson which theChaincodeneeds access to theHistory Logmust be configured toCreateandUpdatetheseHistory Logs.Peeronce enabled for managing theHistory Logs, will create the log on perChaincodeor perAssetbasis.Asset HistoryonPeeris managed in a separate datastore.- Regardless of what database is used as
State Database, theAsset Historyis always managed inGoLevelDBdatabase. History Logsare setup atPeerlevel. They are not replicated by way ofGossip.Peeris responsible for managing theAsset Logson it's own.History APIis used from within theChaincodeto access history.- To enable history database, look for following setting in
core.yaml:
history:
enableHistoryDatabase: true- Just like
Rich Query API, theHistory APIis also not re-executed inValidationphase of theTransaction. This may lead to inconsistentStateofChaincode. - Do not use
History APIinUpdate Transactions (Invoke)unless we can guarenteeNo Phantom Reads.
- Fabric uses
PKI (Public Key Infrastructure)forIdentity Management. - All users are issued a
X509certificate (Enrollmentcertificate). For e.g. Admin and other users in multiple roles. - All nodes in the network are also issued a
X509certificate. For e.g.Orderer,Peers,Clientetc. Authorizationdecision is made by the nodes based on the user'sRoleand thePoliciesthat have been set up for the network. For e.g. Only the identities assigned theRoleofAdmincan install and instantiate the chaincode.- At the network level, the
AccessandAuthorizationcontrol is achieved by way of configuration. i.e. we have to declare thePoliciesthat will drive theAccessandAuthorizationat node level. - For building
Access ControlinChaincode, check theClient Identity Chaincode Library: https://github.com/hyperledger/fabric-chaincode-go/tree/main/pkg/cid - Custom
Attributesare added to theX509certificates by theRegistrar. Client Identity Chaincode Libraryprovides access to theAttributesorIdentityset inX509certificates.Cryptogentool does not support addition ofAttributesin the certificates.- For additional
Attributessupport inX509certificates, theIdentitiesneed to be setup with afabric-ca.
- Module:
fabric-network:Gateway Class: Connection point for accessing the network.Network Class: Represents set ofPeersbelonging to a network or theApplication Channel.Contract ClassandTransaction Class: Exposes APIs (InvokeandQuery) for Chaincode interactions.Transaction Classexposes additional APIs for providing finer control over Chaincode interactions.- Example flow: Pattern: Invoking and Querying Chaincode:
- Application creates instance of
Gateway Classusingnewoperator. - Application then initializes the
Gateway InstancewithWalletand theConnection Profile. Walletholds the credentials information for the user.Connection Profileis provided in the form ofYAMLorJSONfile.- After initialization, the Application creates an instance of
Network Classby invoking a function onGateway Class. - Then, Application creates the instance of
Contract Classby invoking a function on theNetwork Classinstance. - Functions exposed by the
Contract Classare then used for executing theInvokeandQueryfunctions on theChaincode.
- Application creates instance of
fabric-networkmodule exposes classes for managingWallets.
Wallet:- A user may participate in multiple networks with different
Roles. - In other words, a user may have multiple
Identity Profilesto interact with different networks. Walletis construct that is used for managing theseIdentity Profiles.Walletcontains one or more userIdentity Contextand each of theseIdentity ContextorIdentity ProfileshaveCertificates,Private Keyand aPublic Key.IdentitiesinWalletare referred to by aLabelwhich is a free format string and it is unique for each of theIdentitiesmanaged in theWallet.Walletinterface:InMemoryWallet: Manages identities in memory.FileSystemWallet: Manages identities on user's filesystem.CouchDBWallet: Manages identities in a CouchDB Server.
- A user may participate in multiple networks with different
- Module:
Client ClassAPI:- Provides low level functions (via
Channel Class) for interacting with thePeerand theOrderer. - Acts as a factory for
Peers,Orderer,ChannelandChaincodeclasses. - Provides functions for managing the
client instanceconfiguration. - Manage
Channel Update Transactions. - Instance is
Stateful. i.e. We cannot re-use same instance against multipleChannel. Channelrelated updates require multipleAdminsignatures.Channel ConfigupdateTxsubmitted toOrderer.- Creates instances of
Peer Classthat are used forPeerqueries. - Provides functions for managing
Channel Configuration.
- Provides low level functions (via
- Module:
Channel ClassAPI:- Provides API for carrying out
Channel Aware QueriesandChannel Aware Tasks. - For e.g.
- Create new
Channel - Update existing
Channel - Access to
Ledger (Blk, Txn) - Joining
Peerto theChannel - Instantiation, Invoke and Querying of the
Chaincode - Getting finer control over flow of the
Transaction
- Create new
- Channel class instance is initialized with
PeersorOrdereronChannel. - Exposes functions for accessing the
Channel Configuration.
- Provides API for carrying out
- Error:
zsh: ./networkdown.sh: bad interpreter: /bin/bash^M: no such file or directory- Solution:
sed -i -e 's/\r$//' networkdown.sh- Error:
Docker not installed
# OR
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/json": dial unix /var/run/docker.sock: connect: permission denied- Solution:
# ssh into vagrant box
vagrant ssh
# snap install docker
sudo snap install docker
# To fix permission issue
# Change docker.sock file to be owned by "vagrant" user
sudo chown vagrant /var/run/docker.sock- Minifabric: How to install, approve, commit and initialize chaincode in a single command?
./minifab install,approve,commit,initialize -n simple -v 2.0 -p '"init","Aditya","35","Nishigandha","30"'- Minifabric: How to update endorsement policy?
./minifab anchorupdate
./minifab discover # This will create a folder "discover" at "/vars/discover"
./minifab channelquery # This will create a channel config file at "/vars/channel1_config.json". Make the changes and save this file.
# Do the channel update to apply new changes
./minifab channelsign,channelupdate