What is consensus in a blockchain?

A blockchain is a decentralized ledger that runs on a peer to peer network. In the case of a public blockchain like Bitcoin, thousands or perhaps millions of anonymous users participate in this blockchain. How do we achieve trust in such a system, or in a private blockchain? This is where the consensus comes in. The consensus assures that the participants will trust each other and the validity of the next block. A consensus ensures that the network’s rules will be followed and that there is only one truth in the blockchain environment.

Depending on the type of blockchain you have, you will need a different consensus algorithm to make sure the last block in the blockchain reflect the state of the world at each moment. In this article, we will briefly explore different consensus algorithms.

Proof of Work

Let’s start with the one from the Bitcoin and Ethereum’s blockchains. The Proof of Work algorithm requires the miners to solve a complex mathematical problem involving cryptography. It is a lottery where computing powers play a big role. Basically, you take a block’s data and encrypt it with a counter until you get a valid hash.

Pros: Difficult to find a valid hash, but very easy to control of the hash is valid. It makes it impossible to cheat the system. Scales well with a great number of nodes.

Cons: Takes a unbelievable amount of power. Not very environment-friendly. Susceptible to attacks if one party controls 51% of the computing power.

Proof of Stake

Ethereum is moving towards a Proof of Stake consensus. The miner of the next block is chosen based on various combinations of random parameters such as the amount of coin they have, how long has it been since the owner had the coin… There are different instances of this algorithm like Proof of Deposit or Proof of Burn. Very simply put, if node X has 1 coin and node Y has 2 coins, node Y would be twice as likely to be called to validate a block.

Pros: More energy efficient that Proof of Work

Cons: More security issues? There seems to not be a big punishment for working on different chains at the same time. This could create a vulnerability when trying to create and keep a single truth.

Proof of Elapsed Time (PoET)

The Proof of Elapsed Time is a consensus used in the Hyperledger’ Sawtooth project. The participants each request a wait time from a secure enclave. The participant with the shortest wait time is elected the leader, waits the amount of time it was given and proposes a block.

Pros: Leader changes all the time, the same person doesn’t choose the next block every single time.

Cons: The secure enclave is a complex technology, potentially easier to cheat than Proof of Work. There is also a tendency towards centralization because we must use third party trusted certification authority to make sure the enclave is indeed secure.

Simplified Byzantine Fault Tolerance (SBFT)

In this algorithm, the block’s validator is a known entity. It could be a regulator in a business network for example. This validator creates and proposes a new block of transactions. In a SBFT consensus, a certain number of nodes must accept the block, depending on the number of faulty nodes.

In such a system, 2f+1 nodes at minimum must accept the new block in a business network, where f is the number of faulty nodes.

For example, let’s take a system with 30 participants. There are 5 faulty nodes in the network. For the new block to be validated, 11 (25+1) nodes must accept the block. If the number of faulty nodes goes up to 10, 21 (210+1) nodes must agree on the new block.

Faulty in this sense could be malicious or non functioning nodes.

Pros: Faster than Proof of Work, better scalability.
Cons: Tendency to centralization. One validator proposes the next block.

Proof of Authority (PoA)

Suited for private networks where trust doesn’t need to be distributed. The concept is relatively simple: some individuals in the networks are recognized as validators after some conditions are met, such as identity checks. These validators are responsible for maintaining the blockchain’s data.

Pros: Well suited for private networks. Makes it very fast.
Cons: Sacrifices trust.


This was a very quick overview on some consensus algorithm used in the blockchain world. I wanted to make a short article to show some of the possibilities. Of course, there are many others possible. Overall, we can distinguish three types of consensus:

  • The standard Proof of Work consensus
  • Permissioned voting based consensus ( PoA, SBFT )
  • Permissioned lottery based consensus ( PoET )

Which consensus is chosen in a blockchain implementation depends on the type of network and data handled.

Lottery types would be more suited for large networks. Voting types are better suited for smaller networks, and reduce the latency to a minimum.

Read more



In my last article, I started to explore what characteristics a blockchain would need to have to be helpful to a business, and a business network. Now it is time to dive in and use some solutions that are already existing.

Private blockchains or public blockchains?

There are several frameworks and tools that can be used to create a blockchain for a business network. We could go down the path of a public blockchain with Ethereum. It is a possible solution. However, in my learning, I chose to go down a different path and use a private blockchain framework. I believe private blockchains make more sense for businesses than public ones. The anonymity provided by the Ethereum blockchain ( for example ) isn’t especially useful. The cryptocurrency also is not particularly useful. Some businesses will find a permissionless blockchain like Ethereum more attractive, but it makes more sense for networks to use a private blockchain.

In certain networks, you would need a permissioned blockchain that you can only join by invitation or permission. I chose to explore the Hyperledger framework, especially Fabric and Composer.

Hyperledger is an open source set of tools. It is hosted by the Linux Foundation and tries to explore how to use blockchains in a real-world business environment. There are a LOT of huge companies behind this thing ( IBM, Airbus, Intel, JPMorgan, Hitachi, Bosch …).

Hyperledger Fabric is the first framework born out of this adventure. It is a blockchain implementation using container technology and smart contracts.

However, we will start by using a tool called Hyperledger Composer. Composer is built on top of Fabric and will allow us to build rapidly a business network using Javascript. There is also a very helpful playground in the browser that we will use.

What we will cover in this article

  • Create a business network using the differents Composer tools
  • Create some transactions with the Composer REST API
  • Create a simple application and use our business network with a REST API

Let’s go!

Setting everything up

  • You will need Docker

  • You’ll need the Composer CLI tools: npm install -g composer-cli

  • This will run a REST server to expose our business network:
    npm install -g composer-rest-server

  • Some things for generating code:

npm install -g generator-hyperledger-composer
npm install -g yo

  • Next, we’ll need a local Hyperledger Fabric runtime, where our business network will be deployed.

Create a directory and let’s name it fabric-tools

mkdir ~/fabric-tools && cd ~/fabric-tools

Inside this new directory, run the following command:

curl -O https://raw.githubusercontent.com/hyperledger/composer-tools/master/packages/fabric-dev-servers/fabric-dev-servers.zip
unzip fabric-dev-servers.zip

This gives you all you need to run a local Hyperledger Fabric runtime.

Run: ./downloadFabric.sh
Next, run: ./startFabric.sh, then ./createPeerAdminCard.sh

Great, we’re all set up, we can start writing some code.

Creating a business network

You could choose to create your own business network from scratch. But, to speed things up, I made one for you. I chose a land registry network for my example.

In a network, there are three types of resources:

  • Participant: The types of entities that participate in the network. In my example, there are 5 differents types of participants:
    • PrivateIndividual: They buy and sell their properties
    • Bank: They afford loans ( or not )
    • Notary: They validate transactions
    • RealEstateAgent: They facilitate transactions between PrivateIndividuals
    • InsuranceCompany: You do need insurance on real estate right?
  • Assets: Assets are what transactions are made of. In this network, there are 3 different assets:
    • RealEstate: Because it’s a land registry, remember?
    • Insurance: From the InsuranceCompany participants
    • Loan: From the Bank participant, you know, to finance the real estate thing
  • Transactions: Without transactions, nothing would move. Transactions make things happen. I have 3 differents transactions in my network:
    • BuyingRealEstate: One PrivateIndividual buys, another sells. What happens then?
    • ContractingLoan: Between a Bank and a PrivateIndividual
    • ContractingInsurance: Between a PrivateIndividual and an InsuranceCompany

Ok, this is the outline of our business network. Let’s create it.

A business network archive is composed of 4 different types of files in Hyperledger:

  • Model file. Where you describe your participants, assets and transactions. We use a modeling language to describe this. Don’t worry, it’s not that complicated.

  • Access File. Hyperledger Fabric is a permissioned blockchain. We need to defined who gets to see what. For simplicity sake, we won’t do anything crazy in this file. Everybody will see everything. In this, we use an Access Control Language (ACL) to express permissions.

  • Script File. Written in Javascript. This defines what happens when a transaction happens in the network.

  • Query File. Used to execute queries. Written in a native query language. We won’t use this file for now. Another time.

Generating code

We’ll use Yeoman to set up the code for us. Run:

yo hyperledger-composer:businessnetwork

Enter land-registry for the network name. Complete as you wish for the author fields.

Select Apache-2.0 as the license

Enter org.acme.landregistry as the namespace.

Great, now you have all the files you need.

The model file

Let’s start by the model. This is where we define our participants, assets and transactions. Open up the org.acme.landregistry.cto file and put this in there:

 * Business network model

namespace org.acme.landregistry

participant PrivateIndividual identified by id {
  o String id
  o String name
  o String address
  o Double balance default = 0.0

participant Bank identified by id {
  o String id
  o String name
  o Double balance default = 0.0

participant InsuranceCompany identified by id {
  o String id
  o String name
  o Double balance default = 0.0
participant Notary identified by id {
  o String id
  o String name
  o String address
  o Double balance default = 0.0
participant RealEstateAgent identified by id {
  o String id
  o String name
  o Double balance default = 0.0
  o Double feeRate
asset RealEstate identified by id {
  o String id
  o String address
  o Double squareMeters
  o Double price
  --> PrivateIndividual owner

asset Loan identified by id {
   o String id
   o Double amount
   o Double interestRate
   --> PrivateIndividual debtor
  --> Bank bank
  --> RealEstate realEstate
   o Integer durationInMonths
asset Insurance identified by id {
  o String id
  --> RealEstate realEstate
  --> PrivateIndividual insured
  --> InsuranceCompany insuranceCompany
  o Double monthlyCost
  o Integer durationInMonths

transaction BuyingRealEstate {
  --> PrivateIndividual buyer
  --> PrivateIndividual seller
  --> RealEstate realEstate
  --> Loan loan
  --> RealEstateAgent realEstateAgent
  --> Notary notary
  --> Insurance insurance
transaction ContractingInsurance {
  --> PrivateIndividual insured
  --> InsuranceCompany insuranceCompany
  --> RealEstate realEstate
  o Double monthlyCost
  o Integer durationInMonths
transaction ContractingLoan {
  --> PrivateIndividual debtor
  --> Bank bank
  --> RealEstate realEstate
  o Double interestRate
  o Integer durationInMonths


Ok, there is quite a few things to uncover here. I think it reads relatively easily. First, I define our 5 participants types. They will all be uniquely identified by their id field. As you can see, this modeling language is strongly typed. You need to specify the type for each field. Nothing fancy for our participants, some String and Double types.


Our assets will also be identified by their id field. But, this time, you can see some arrows ( –> ) in the assets definitions. The arrows define relationships. A RealEstate asset has a relationship with a PrivateIndividual, its owner. A Loan has 3 differents relationships: the PrivateIndividual requesting a loan, the Bank that emits the loan and the RealEstate asset the loan finances.


3 transactions in our model. They are not identified by any field like the other resources. The fields specified here will be passed to the functions declared in our script file. Let’s see this now.

The Script File

Back to good old Javascript. This is where we define what happens during a transaction. Open the logic.js file in the lib folder:

'use strict';

 * Contracting an insurance
 * @param {org.acme.landregistry.ContractingInsurance} insurance
 * @transaction

 function contractingInsurance( insurance ){
    return getAssetRegistry('org.acme.landregistry.Insurance')
      var factory = getFactory()
      var insuranceId = insurance.insured.id + '' + insurance.insuranceCompany.id + '' + insurance.realEstate.id
      var insuranceAsset = factory.newResource('org.acme.landregistry', 'Insurance', insuranceId)
      insuranceAsset.insured = insurance.insured
      insuranceAsset.insuranceCompany = insurance.insuranceCompany
      insuranceAsset.realEstate = insurance.realEstate
      insuranceAsset.durationInMonths = insurance.durationInMonths
      insuranceAsset.monthlyCost = insurance.monthlyCost
      return assetRegistry.add(insuranceAsset)

 * Contracting a loan
 * @param {org.acme.landregistry.ContractingLoan} loan
 * @transaction

function contractingLoan( loan ){
  return getAssetRegistry('org.acme.landregistry.Loan')
    var factory = getFactory()
    var loanId = loan.debtor.id + '' + loan.realEstate.id + '' + loan.bank.id
    var loanAsset = factory.newResource('org.acme.landregistry', 'Loan', loanId) 
    loanAsset.debtor = loan.debtor
    loanAsset.bank = loan.bank
    loanAsset.interestRate = loan.interestRate
    loanAsset.durationInMonths = loan.durationInMonths
    loanAsset.realEstate = loan.realEstate
    loanAsset.amount = loan.realEstate.price
    return assetRegistry.add(loanAsset)

 * Buying Real Estate
 * @param {org.acme.landregistry.BuyingRealEstate} trade
 * @transaction

function buyingRealEstate( trade ){
  var notaryFees = 0.1 * trade.realEstate.price
  var realEstateAgentFees = trade.realEstateAgent.feeRate * trade.realEstate.price
  var insuranceCostFirstMonth = trade.insurance.monthlyCost
  var totalCost = notaryFees + realEstateAgentFees + insuranceCostFirstMonth 
  // Updates the seller's balance
  trade.seller.balance += trade.realEstate.price
  // Check if the buyer has enough to pay the notary, real estate agent and insurance
  if( trade.buyer.balance < totalCost ){
    throw new Error('Not enough funds to buy this!')
  trade.buyer.balance -= totalCost
  trade.realEstate.owner = trade.buyer
  trade.realEstateAgent.balance += realEstateAgentFees
  trade.notary.balance += notaryFees
    return (

Ok, we have three functions, one for each transaction. You use JSDoc description and tags to describe what transaction your function is supposed to work on. As you can see, you provide the namespace, { org.acme.landregistry.ContractingInsurance } for example, followed by @transaction.


In our model, to buy real estate, you first need to contract a loan and an insurance. This function creates an Insurance asset. We use the getAssetRegistry function to retrieve the insurance's asset registry. We then create a new Insurance asset and defines its properties. Finally, we add the new asset to the registry.

Note: All the registries that we use return promises.


Exactly the same concept. Get the Loan registry, create a new Loan, add it. Note how I chose to dynamically create each asset ID. In a larger network, we would need to come up with something different. In our case, it'll be fine.


Finally, we can buy some real estate. There are a few things going on here. First, I must explain a few rules about our network:

  • Everyone is paid during this transaction. Not before.

  • A notary must validate a transaction. She takes 10% of the real estate price as her fee. This is more or less what it costs in France in such transactions. So, if you buy a house for 100000€, you would need to pay an extra 10000€ to the notary.

  • Each transaction is conducted with a real estate agent. What the agent gets is specified in the model ( feeRate ).

  • The insurance has a montly cost. During the transaction, the buyer must pay the first month.

  • I assume that the buyer contracts a loan ONLY for the real estate price. Other costs must be paid by herself. As you can see in the function, if the buyer's balance can't cover the insurance's first month, the notary's fees and the real estate agent's fees, the transaction doesn't happen.

  • Transactions are atomic. Meaning, everything happens or nothing happens. If an error happens while we update one of our participants at the end of the transaction, we go back to the state we had before the transaction.

  • The rules I chose for the network are arbitrary. Some are based on how it works in France, others are chosen to make things a bit simpler.

In this function, we pay everyone. Then, we fetch every single registries we need and we update them all. Transaction done!

Permissions file

Finally, the permission file. We won't do anything crazy here. Just copy and paste this in the .acl file. We can define permissions depending on the participants, as you should in a private blockchain, but that would be outside the scope of this article. Put this in the permissions.acl file:

rule Default {
    description: "Allow all participants access to all resources"
    participant: "ANY"
    operation: ALL
    resource: "org.acme.landregistry.*"
    action: ALLOW

rule SystemACL {
  description:  "System ACL to permit all access"
  participant: "ANY"
  operation: ALL
  resource: "org.hyperledger.composer.system.**"
  action: ALLOW

Basically, let everyone do whatever they want. Not what you would like in a production-ready blockchain, but good enough for now.


Everything is ready! Now, we can deploy our business network in the Hyperledger Fabric. We'll need to run a few commands:

First, we need to create a Business Network Archive that the Fabric can use. To do this, in the land-registry folder, run this:

composer archive create -t dir -n .

This will create a .bna file.

Next, we'll install the composer runtime with:

composer runtime install --card PeerAdmin@hlfv1 --businessNetworkName land-registry

The PeerAdmin card is the one you created by running /.createPeerAdminCard.sh earlier.

Next, we'll deploy the business network:

composer network start --card PeerAdmin@hlfv1 --networkAdmin admin --networkAdminEnrollSecret adminpw --archiveFile land-registry@0.0.1.bna --file networkadmin.card

Finally, we'll need to import the network administrator card into the network:

composer card import --file networkadmin.card

Playing around

Everything is ready. We can now create the REST API by running composer-rest-server.

  • Enter admin@land-registry as the card name.
  • Never use namespaces, then NO, then YES, then NO. ( Just YES to WebSockets )

You can navigate to localhost:3000/explorer now.

We have now access to a REST API to interact with our business network. As you can see, we have everything we defined earlier: paticipants, assets and transactions.

First things first, we need to create our participants and at least one RealEstate asset so we can make a transaction.

Let's go to the PrivateIndivual item, and select the /POST route. I'll create two participants here.

I'll name one PrivateIndividual Joe, with the id joe. I'll also give him 50000 in his balance. Give whatever address you want. Hit Try it out to create Joe.

The other individual will be Sophie, with the id sophie. She'll have 10000 in her balance. Give her an address and hit Try it out.

Make sure the response code is 200 every time. You can double check by going to the /GET route and fetch the data.

Let's move to the other participants now. The concept is the same, just jump between the different items.

The notary will be Ben, with the id ben. The real estate agent will be called Jenny, id jenny. Her feeRate will be set to 0.05 ( 5% ). The bank will be HSBC, id hsbc. Finally, the insurance company will be AXA, id axa.

Now, let's create a RealEstate asset. Same concept, got to the /POST route and give it the following data:

    "$class": "org.acme.landregistry.RealEstate",
    "id": "buildingOne",
    "address": "France",
    "squareMeters": 100,
    "price": 100000,
    "owner": "resource:org.acme.landregistry.PrivateIndividual#sophie"

As you can see in the owner field, I decided to give this asset to Sophie, by specifying her id. This is the relationship between RealEstate and PrivateIndividual.

A transaction

Great, now, we can make a transaction! Sophie decides to sell her house, and Joe decides to buy it. First, Joe needs to go to his bank and contract a loan. In our network, we do not create a Loan asset directly. The transaction ContractingLoan is responsible for the creation of the asset. So choose the ContractingLoan transaction in the list, and the /POST route. To create our loan, give it the following data:

  "$class": "org.acme.landregistry.ContractingLoan",
  "debtor": "org.acme.landregistry.PrivateIndividual#joe",
  "bank": "org.acme.landregistry.Bank#hsbc",
  "realEstate": "org.acme.landregistry.RealEstate#buildingOne",
  "interestRate": 2.5,
  "durationInMonths": 300

Again, you need to specify a few relationships for this transaction. The debtor is Joe, so I specify his id joe. The bank is hsbc and the real estate financed is buildingOne. I chose a 2.5% interest rate over 300 months ( 25 years ).

Note: Remember to give the participant or asset ID in the relationship. So => joe NOT Joe.!

Submit and you will see your new Loan if you go to the Loan items and use the /GET route.

Next, let's contract an insurance. The concept is the same, the transaction ContractingInsurance is responsible for the creation of the asset. Move to this item and choose the /POST route again:

  "$class": "org.acme.landregistry.ContractingInsurance",
  "insured": "org.acme.landregistry.PrivateIndividual#joe",
  "insuranceCompany": "org.acme.landregistry.InsuranceCompany#axa",
  "realEstate": "org.acme.landregistry.RealEstate#buildingOne",
  "monthlyCost": 150,
  "durationInMonths": 12

Again, the insured is joe. The insuranceCompany is axa, and the realEstate is still buildingOne. I chose 150 for the monthly insurance's costs for a 12 months duration. Submit and check that the Insurance asset has been created by checking the /GET route under Insurance.

We finally have all the pre-requisites to execute our BuyingRealEstate transaction. Move to said transaction and give it the following data:

  "$class": "org.acme.landregistry.BuyingRealEstate",
  "buyer": "org.acme.landregistry.PrivateIndividual#joe",
  "seller": "org.acme.landregistry.PrivateIndividual#sophie",
  "realEstate": "org.acme.landregistry.RealEstate#buildingOne",
  "loan": "org.acme.landregistry.Loan#joebuildingOnehsbc",
  "realEstateAgent": "org.acme.landregistry.RealEstateAgent#jenny",
  "notary": "org.acme.landregistry.Notary#ben",
  "insurance": "org.acme.landregistry.Insurance#joeaxabuildingOne"

Same concept, we specify the relationships in the transaction by adding the proper ids. joe is the buyer, sophie is the seller, jenny is the real estate agent, joebuildingOnehsbc is the loan's id, joeaxabuildingOne is the insurance's id, buildingOne is the real estate's id and ben is the notary's id.

When this transaction is submitted. You will see that the RealEstate asset has now a new owner Joe. You can also also see that the participant's balances have been updated:

  • Sophie's balance is now 110000 ( Her 10000 + the real estate's price of 100000 )

  • Joe's balance is now 34850. ( His 50000 - notary's fees of 10000 - real estate agent's fees of 5000 - the insurance's first month of 150 )

  • The notary's balance is now 10000

  • The real estate agent's balance is now 5000.

Great, we interacted with our business network and a blockchain. Now, let's create a simple User Interface that will interact with this REST API and retrieve some data.

Create a simple application with Composer and Fabric

We will not do anything too fancy, just something to show how straightforward it is to work with the business network in the Hyperledger Composer world.

This simple application will be built using the create-react-app tool. We will be able to do 4 things will it:

  • GET and display PrivateIndividual participants
  • GET and display RealEstate assets
  • POST and create new PrivateIndividual participants
  • POST and create new RealEstate assets

Of course, there are no limits to what you can do with the REST API, I chose arbitrarly which routes we will use here.


First, we need to install the create-react-app tool:

npm install -g create-react-app

Next, create your app:

create-react-app <APP_NAME>

This will create a React application in your app folder. You don't have to setup anything. Now, we need to change a couple of things to make sure we can talk to the REST API.

The proxy and port

We are going to retrieve data from our REST API running in localhost:3000. We will run our app in a different port. To make sure our React application goes to the right place to get the data and avoid cross-origin issues, go to your package.json file.

In the file, you will simply add the line:

"proxy": "http://localhost:3000/"

That's it for the proxy. Now, in that same file, look in the scripts object for the start command. The start command should look like this now:

"start": "PORT=3001 react-scripts start"

Because the REST API will run on port 3000, this will simply run the React app on the port 3001, and not ask us a different port everytime we start it.

The code!

I tried to make things very simple. Just raw code, no CSS, no fancy stuff. Two files: App.js and Client.js. You'll create the file Client.js and add this:

function search(query, cb) {
    return new Promise( (resolve,reject) => {
        return fetch(`api/${query}`, {
            accept: "application/json"
            .then(data => resolve(data));


function create(type, data){
    return new Promise((resolve, reject) => {
        return fetch(`api/${type}`, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            method: 'post',
            body: JSON.stringify(data)
        .then(() => resolve())


function parseJSON(response) {
  return response.json();

const Client = { search, create };
export default Client;

What do we have here? Basically, we have two functions: search and create. The function search will handle our GET requests, the create one will handle our POST requests. If you didn't explore the REST API a bit, every route begins with the prefix /api. In our case, http://localhost:3000/api/, that's our prefix. The proxy key we added in our package.json will send every request to the right place. We just have to make sure the rest of our query is good.


  • GET and POST PrivateIndividual => http://localhost:3000/api/PrivateIndividual
  • GET and POST RealEstate => http://localhost:3000/api/RealEstate

Now, let's move to the App.js file:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Client from './Client'

class App extends Component {

    state = {
        privates: [],
        realEstate: []

    componentWillMount = () => {

    getPrivateIndividual = () => {
        .then(data => {
                privates: data

    getRealEstate = () => {
        .then(data => {
                realEstate: data
            for( let i = 0; i < this.state.realEstate.length; i++ ){
                let privateIndividual = this.state.realEstate[i].owner.split('#')[1]
                    .then(data => {
                        let realEstate = this.state.realEstate
                        realEstate[i].ownerName = data.name

    handlePrivateInputChange = e => {
        const {name, value} = e.target
            [name]: value

    submitPrivate = () => {
        const data = {
            "$class": "org.acme.landregistry.PrivateIndividual",
            "id": this.state.name.toLowerCase(),
            "name": this.state.name,
            "address": this.state.address,
            "balance": this.state.balance

        Client.create('PrivateIndividual', data)
        .then(() => {

    handleRealEstateInputChange = e => {
        const { value, name } = e.target
            [name]: value

    submitRealEstate = () => {
        const data =  {
            "$class": "org.acme.landregistry.RealEstate",
            "id": this.state.id,
            "address": this.state.realEstateAddress,
            "squareMeters": this.state.squareMeters,
            "price": this.state.price,
            "owner": `org.acme.landregistry.PrivateIndividual#${this.state.owner}`

        Client.create('RealEstate', data)
        .then(() => {

  render() {

    return (

Add PrivateIndividual

Add RealEstate

Private Individual

{this.state.privates.map((p, i) => (
Name: {p.name} Balance: {p.balance}

Real Estate Assets

{this.state.realEstate.map((r, i) => (
ID: {r.id} Address: {r.address} Price: {r.price} Owner: {r.ownerName}
); } } export default App;

There is nothing crazy here either. The HTML is composed of two forms: one to create a new PrivateIndividual and another to create a new RealEstate asset. Below these, we loop through the data we have and create simple boxes to display our assets and participants.

In the componentWillMount function, we retrieve our data. submitPrivate and submitRealEstate do what they are told 😉 .Notice the shape of the object we sent to the API.

Running the app

Make sure your REST API is running. If not, re-run composer-rest-server. Then, in the land-registry folder, run your React app with npm start.

Now, you can play along with your private blockchain!

Note: In the React application, I skipped things like error handling, CSS styling and other POST routes for transactions. The article seems long enough and, I hope, clear enough so that you could manage these things on your own. Have fun!

Read more

blockchain logos


The Blockchain technology gained a lot of popularity lately, partly thanks to cryptocurrencies like Bitcoin. In a previous article, I explored several possible use cases for the blockchain technology outside of the cryptocurrency realm. In this article, I will explain what a blockchain would look like to become more relevant and sustainable for businesses. A blockchain designed for a business network will still be a distributed ledger based on a peer-to-peer network, but there are some key differences between a blockchain supporting something like Bitcoin and another built for a business network.

Assets over cryptocurrency

Because the Bitcoin’s blockchain was built specifically for cryptocurrencies, it took some time to realize that we could use blockchains for something else than cryptocurrencies. Instead of using a token in the shared ledger ( bitcoin, ether… ), any other asset could be used. Are cryptocurrencies really useful for businesses to run their operations? Building trust, improving security, reducing costs and delays, these are the things a business will look for when using a blockchain. Private blockchains don’t need a token or coin to operate.

Identity over anonymity

In Bitcoin, everybody is anonymous. You don’t know who you are sending your bitcoins to, or receiving bitcoins from. In a private blockchain, anonymity is not what you need. You need to know where the money is coming from, and you need to know who your customers are. You need privacy, not anonymity. Let’s use a example of a simple business network:

In a normal network, each entity would have its own ledger, its own record of transactions. Which means that everytime a transaction occurs in the network, each entity concerned by the transactions would have to update their ledgers. If company C1 buys from company C2 and company C1 needs a loan from bank B1 and an insurance from the insurance company I1, every single one of those organisations would need to update their books. This is not an efficient way to do things.

With a blockchain, only one ledger would be updated. But, contrary to the Bitcoin blockchain, not everybody can see everything. By implementing an authentification system, company C1 can only see the transactions that it is involved in. The company would have access to the complete details of the transaction it made with C2, the loan with B1 and the insurance with I1. C1 would not have access to informations about C2 transactions ( if C1 is not involved ), or the banks in the network ( assuming C1 is still not involved ).

Privacy, not anonymity.

Selective endorsement over proof-of-work

In Bitcoin, and other blockchains, we verify transactions through mining. The whole network has to work to confirm transactions and blocks are safe. In a private blockchain in a business network, we would use selective endorsement. The network would choose who controls, verifies and confirms transactions within the network. Going back to the previous example, the transaction between C1 and C2 could be controlled by C1’s bank and C2’s bank. You could choose any number of entities to verify transactions in the network.

Four Requirements

In simpler terms, a blockchain designed for a business network needs to meet four requirements:

  • Shared Ledger: Every actor in the network shares the same ledger. It is append-only. Can’t modify or delete a past transaction.

  • Smart contracts: Every business has rules. In a blockchain, you would write smart contracts. Basically, you take a business rule and translate it into code that gets executed with each transaction. For example, if company C1 ships a product to a customer, I could write code to make sure that C1 and the shipper are paid only when the customer received the product. We could also write rules that would define the conditions of a loan. The examples are infinite.

  • Privacy: As I said earlier, privacy over anonymity. We still need to know who we are dealing with. Transactions are still secure, verifiable but authenticated. You are still going to have a fair share of cryptography.

  • Trust: A key component, we achieve trust by choosing which participant endorse transactions. Because transactions can’t be modified or deleted later, we have a reliable audit trail.


How a business would benefit from a blockchain?

  • Time: Transactions would be a lot faster. We could go from days to real time.
  • Costs: Less intermediates and overheads.
  • Risks: Prevents tampering, fraud and cyber-crime.
  • Trust: Increases trust thanks to shared record keeping and processes


Blockchains go way beyond the cryptocurrency world. I’ll even make a prediction by saying it will transform the global economy in the future. Blockchain is a very young technology still, and we have only scratch the surface of what will be possible, but the future looks bright.

Read more

Some clarification

The purpose of mining is probably a little confusing at first. I will keep the Bitcoin blockchain as an example throughout this article. Mining is NOT about creating new bitcoins. Mining is the mechanism that allows the blockchain to be a decencentralized security. It secures the bitcoin system and enable a system without a central authority. Do not confuse the rewards given to miners ( new bitcoin ) with the process itself.

Mining in Bitcoin

Miners validate new transactions and record them on the global ledger ( blockchain ). On average, a block ( the structure containing transations ) is mined every 10 minutes. Miners compete to solve a difficult mathematical problem based on a cryptographic hash algorithm. The solution found is called the Proof-Of-Work. This proof proves that a miner did spend a lot of time and resources to solve the problem. When a block is ‘solved’, the transactions contained are considered confirmed, and the bitcoin concerned in the transactions can be spend. So, if you receive some bitcoin on your wallet, it will take approximately 10 minutes for your transaction to be confirmed.

Miners receive a reward when they solve the complex mathematical problem. There are two types of rewards: new bitcoins or transaction fees. The amount of bitcoins created decreases every 4 years ( every 210,000 blocks to be precise ). Today, a newly created block creates 12.5 bitcoins. This number will keep going down until no more bitcoin will be issued. This will happen around 2140, when around 21 millions bitcoins will have been created. After this date, no more bitcoin will be issued.

Miners can also receive rewards in the form of transaction fees. The winning miner can ‘keep the change’ on the block’s transactions. As the amount of bitcoin created with each block diminishes, the transactions fees received by the miner will increase. After 2140, the winning miner will only receive transaction fees as his reward.

The amount of bitcoin issued with each block is divided by 2 every 210 000 blocks. So we can calculate the maximum amount of bitcoin with some code.

// First 210 000 blocks reward const start_reward = 50 // The reward is modified every 210000 blocks const reward_interval = 210000 const max_btc = () => { // 50 BTC = 5000000000 Satoshis // Satoshis are the smallest denomination in bitcoin let current_reward = 50 * 10 ** 8 let total_btc = 0 while( current_reward > 0 ){ total_btc += reward_interval * current_reward current_reward = current_reward / 2 } return total_btc } console.log(`The maximum amount of BTC created will be ${max_btc()} Satoshis, or ${max_btc() / 10**8} BTC`) // The maximum amount of BTC created will be 2100000000000000 Satoshis, or 21000000 BTC

So, yeah, 21 millions will be probably the maximum amount of bitcoin issued in the end!

How does it work, anyway?

The question is, how can everyone in the network agree on an universal ‘truth’ about bitcoin ownership, without having to trust anyone in said network? The blockchain is not created or managed by any central authority. Every node has access to the public ledger of transactions that acts as an authoritative record. Somehow, every node in the network, acting on those insecure informations, come up to the same conclusions and are able to replicate the same ledger. Let’s try to explore how this works.

It will probably help if we take a real life example. Meet block #502426. We’ll follow the lifecycle of this block from its construction to its final validation. Let’s say the winning miner was called Joe.

The previous block

In the world of Bitcoin, it takes approximately 10 minutes to validate a new block. Our miner Joe was competing to validate the block 502425, the previous one. Unfortunately, someone else solved the problem before him. But, the end of one block’s competition means the beginning of a new one. As soon as the block 502425 was mined, Joe updated his local copy of the blockchain and starts to create a candidate block, the block 502426. While Joe’s computer ( or node ) was searching for the Proof of Work for the previous block, it was also listening for new transactions. Those new transactions are added to the memory pool or transaction pool. This is where transactions wait until they can be included in a new block and validated.

Creating the candidate block

When Joe’s node is notified that the current block has a valid Proof of Work, it starts constructing a candidate block by gathering the transactions in the transaction pool. It removes the transactions already present in the previous block, if there are any. The block is called a candidate block because it doesn’t have a valid Proof of Work yet.

So, we can see that block #502426 has 3189 transactions inside it. This was the number of transactions present in Joe’s transaction pool when he created his candidate block.

Coinbase transaction

The first thing Joe’s node does is creating the coinbase transaction. Very simply, this is his reward for mining the block. This transaction says => Pay Joe’s wallet address xxx BTC to reward him for finding a valid Proof of Work. This transaction is different from the other ones because, as I explained earlier, the bitcoins in the reward are created from nothing. They do not come from someone’s wallet. Joe’s node also calculates the transaction fees in the block.

Joe’s reward = Reward for mining block + transactions fees

In this case, we can see that the block reward is 12.5 BTC ( Block Reward in left column ) and the transactions fees are equal to 4.86507997 BTC ( Transaction fees in left column ).

12.5 + 4.86507997 = 17.36507997 BTC

You can see the details of this transaction in the list below.

You can see No Inputs (Newly Generated Coins). Like I said, coinbase transactions do not come from anyone’s wallet, so they can’t have any inputs. You only have the winning miner’s wallet address here.

Constructing the block header

In a previous article, I described what was contained in a block. Joe’s node has the responsability to create a proper block header for the block he is mining. In the article, I mostly focused on the merkle tree, a summary of transactions and mentioned that there are three different sets of data in a block header: the previous block hash, the merkle tree root and data for the mining competition. We’ll dig deeper in the last one.

Data fields

This metadata set contains:

  • The Version: This is a version number to track the software and/or protocol upgrades.
  • Timestamp: Seconds from Unix Epoch. When the block was created.
  • Target: Proof of Work algorithm target for this block
  • Nonce: Counter used for the Proof of Work algorithm

When the block #502426 was mined, the version number was 2. It becomes 0x20000000 when converted in little-endian format in 4 bytes. ( Version in the left column )

Next, we get the 4-byte timestamp. This is the number of seconds elapsed since the January 1, 1970. We see the timestamp for this block is 2018-01-03 21:12:39 ( Timestamp in left column ). If we convert this in seconds, we get 1515013959 seconds.

The target field defines the required Proof of Work to make this a valid block. To put it simply, the target is generated by the network and defines what makes a block’s hash valid or not. If your hash is higher than the target, it is not valid. This is what is used to calculate the difficulty. In our block, the difficulty is 1,931,136,454,487.72. Take a look at the block’s hash:


There are 18 leading zeros. This is our difficulty. Every hash with less than 18 leading zeros is invalid ( every hash with 17 leading zeros and less would be lower that the required target ).

Let’s dig deeper into how we calculate this:
In the left column, you have a bits field, with the value 402690497. This is the target bits. This number expresses the Proof-of-Work target as a coefficient/exponent format.

If we convert this number in hexadecimal, we get this: 0x180091C1.

The first two hexadecimals digits ( 18 ) are the exponent, the next six ( 0091C1 ) are the coefficient. Here is the formula used to calculate the target from this:

target = coefficient * 28 * (exponent – 3)
So by using the hexadecimal value above, we can calculate the target:

target = 0x0091C1 * 2 0x08 * (0x18 – 0x03)
target = 0x0091C1 * 2 0x08 * 0x15
target = 0x0091C1 * 20xA8
Which in decimal is =>

target = 37,313 * 2168
target = 1.3960451 * 1055
target = 13960451000000000000000000000000000000000000000000000000
Back to hexadecimal (and a 64 length string) is =>

target = 0x00000000000000000091C100000013DE20D232FECCC0229E9BC3DD600000000000
This represents the higher limit the hash must have. If the hash is lower than this target, it is valid ( here => 18 leading zeros ).

As for the difficulty, we divide the highest difficulty possible by the target found:

00000000FFFF00000000000000000000 /

= 1C1A0B3CF57

Which in decimals => 1,931,136,454,487

This means that compared to the first block every mined ( where the difficulty was 1 ), this block was 1.9 trillion times more difficult to solve. I may have skipped the decimals in this, but I hope you get the idea.

The last field is the nonce. It is initialized to zero.

Everything is now ready for Joe’s node to mine the block. The goal is to find a value for the nonce that will results in hash lower than the target. So, the mining node will try billions or trillions of nonce values before it gets a valid hash.


In a picture, mining is:

As you can see, mining is like a lottery. There is no way to predict which nonce will solve the problem.

In a previous article, I implemented a simple blockchain that demonstrates the concept of a nonce and how it changes the hash created.

In the case of Bitcoin, the hash function used is called SHA256. A hash algorithm always produces the same arbitrary length data given the same inputs. It is impossible to compute the same hash with two different inputs ( collision ). It is also impossible to predict the output of any given data in advance.

SHA256 always produces an output 256 bits long. Mining is finding the nonce, the only input that changes every time we run the hash function. It is very easy to prove that the nonce found indeed produces a valid hash. All the informations are available, everyone can run the hash function and confirm if the hash is valid or not. Because it is also impossible to predict what the nonce will be, it also act as a proof that the miner worked to get a valid hash ( Hence => Proof-of-Work ).

Adjusting the target

In Bitcoin, a block is mined every 10 minutes or so. The difficulty is calculated so that it never deviates too much from this limit. If the difficulty stays the same in the long term, while computer power increases, it will take less and less time to mine a block. To make sure this doesn’t happen, the Proof of Work target is a dynamic parameter. In the Bitcoin world, the target is adjusted every 2016 blocks. Then, we check the amount of time it took to mine those 2016 blocks. It should have taken 20160 minutes ( 2016 * 10 minutes ). The difficulty increases or decreases depending on the time it took to mine those blocks.

Success !!

Joe’s node is getting to work and starts hashing the block’s header. After approximately 10 minutes, it discovers a valid hash. We can see the nonce used was 2469953656 ( Nonce in left column ).

Joe’s node immediately transmits the block to all its peers. They need to validate the new block before propagating it to its peers. This is the part where a dishonest miner can be found out. If the data is invalid, the miner would have wasted his time and computing power. Valid data includes:

  • Block header hash is less than the target
  • Block size is within acceptable limits
  • Block timestamp is less than two hours in the future.
  • The first transaction is a coinbase transaction ( and only the first )
  • The coinbase transaction has a valid reward.
  • All transactions within the blocks are valid ( also have a checklist on their own )

Every node validates independently new blocks following the exact same rules. This assures that miners cannot cheat. This is a key component of the decentralized consensus.

If the block is valid, the other miners will update their own copy of the blockchain with the new block 502246. Joe’s block hash is now used by all the miners to mine the block 502247.

Read more


The blockchain technology is the core concept behind cryptocurrencies like Bitcoin. But cryptocurrencies are only one possible application of the blockchain. In this post, we will explore other uses cases for this interesting technology and how it could potentially change the world we are living in.

Case 1: No more banks?

Let’s start with the more obvious because it got the most attention. A blockchain rests on a decentralized ledger. There are no third parties involved in the process. In the case of a bitcoin transaction, your bitcoin goes from one wallet to another, without having to rely on an institution or government to make it happen. In our current society, we trust banks to execute a lot of operations concerning money. The blockchain would allow users to skip the middlemen and just deal with one another.

With that being said, it seems like we are a very, very long way from this scenario becoming reality. Cryptocurrencies are simply too volatile to be trusted to replace the current system. It is interesting to note that banks seem to be active about the blockchain technology. A company called R3 recently worked with more than 40 banks to imagine a possible future for blockchain with banking establishments. R3 recently launched a version of its blockchain backed by a dozen banks.

Why would banks be involved in a concept that could essentially make them obsolete? Well, blockchain has a lot of potential applications, as you’ll read next, but we can easily imagine how banks ( and a lot of other organizations ) could reduce their costs by not having to deal with third parties organisms.


R3 Blog

Case 2: Make Uber and AirBnB useless ?

When you think about it, plateforms like Uber and AirBnB share the same concept. They are intermediates, they centralize the informations their users need. A ‘bank for cabs’, or ‘bank for rooms’ if you will. You need a ride, someone else has a car, you use Uber to share your informations. Of course, in the process, Uber takes a little something, driving the costs up. Same for AirBnB. While those companies and their services are not as essential in our societies as banks, the blockchain could suppress the need for them.

For example, arcade.city is a project created by a former Uber driver. It relies on a peer-to-peer network, you don’t need to use a third party to find a driver or a passenger. Nobody but the two agents ( the one with the car and the one without ) decide on the price. You don’t even need to use money. If you want to exchange a car ride for a sandwich or a ticket to a football game, what’s the big deal? Blockchain works on decentralized trust, nobody gets in the middle of your transaction.

slock.it is a company hoping to replace Airbnb. The slock.it blockchain technology is based on Ethereum.

Case 3: Local energy markets ?

The electricity market is a top to bottom system. Someone produces the electricity, someone consumes it. But, in today’s world, some consumers are able to produce their own electricity. How do we deal with people who have solar panels and an excess of electricity? How do you make them part of the network?

The SolarCoin allows people to make electricity transactions between private individuals. We could imagine a market where individuals buy and sell their energy using the blockchain to secure the transactions. Again, costs would go down, because nobody but the seller and the buyer would intervene in the transaction.

Case 4: Smart contracts

So far, you may have recognize that a few things seems to happen when using a blockchain: costs go down because intermediates disappear, the decision process is much faster because it is automated and it is safer because the blockchain is transparent.

We could imagine countless applications for smart contracts. Imagine contracting an insurance, you and the insurance company agree on some terms. The smart contract takes the informations it needs, and as soon as the conditions are met, the payment is made.

A airline could create insurances using the blockchain technology to compensate people where a plane is late. The smart contract would gather informations about the planes time of departure, and whenever a plane would be late, the user would be compensated. Without her having to do anything, filling a form or make a phone call.

AXA, a french insurance company, invested 55 millions $ in a canadian company called Blockstream.

A management school in Marseille (France) already uses the blockchain to certify its degrees.

Project managers, art professionals and many more could benefit from such a technology to prevent fraud.

Case 5: Prevent medecines frauds?

Blockchain is a transparent way to store informations, nobody controls it and it is secure. It could be a great way to trace medicines and make sure the drugs you are using are approved by organisations you can trust. The Health World Organization estimates 700 000 people die every year because of counterfeit drugs. Between 10% and 30% of drugs are counterfeit in third world countries.

Still on the health department, Estonia used the blockchain to secure 1 million health records. source

Case 6: Safer land registers?

Not a (huge) problem in rich countries, but in certain countries, lands are not registered in any database. How do you prove a land is yours? What prevents your neighbor, or anyone else, to come over and take your land?

Land registers in some countries are either non existant, or obsolete for a lot of rural areas. Not being able to prove ownership of your land is a huge obstacle to development.

In Ghana, a startup called Bitland uses the blockchain to register land acts. Apparently, they use something called Graphene.

In Honduras, the government registered its entire territory on a blockchain with the help of a company called Epigraph.

Case 7: Better democracies?

When we think about democracies, we think about voting. That is what it is. We ask everyone in a country, state, organization, company and count the votes to determine a winner.

The blockchain could again help with the process. The transparence of the blockchain could make sure no frauds happen, and enable a safe online vote.

It could work like this: an organization ( country, company ) wants to organize a vote. Let’s say a company with 100 employees. The company will use a protocol to create its own tokens ( like Bitcoin is a token ). It will emit 100 tokens, one for each employee. Every employee has access to a wallet, that will be used as a public ballot box. An employee would then transfer the token with the data that represents its vote. Like in the Bitcoin world, each employee would have a key ( part public, part private ) that would prove she is indeed the owner of the wallet.

We are obviously far away from being able to hold large scale elections with blockchain, as there are a lot of problems to solve first, but this is another use case that could be interesting to explore.


The more I read and learn about blockchain, the more I am convinced that it will change our societies for the better. These 7 examples are just a short list of what could be possible, and we probably just scratched the surface.

Sources: ( in French )
7×7 Article

Les Echos

Read more


In my previous article, I tried to described the concept of a blockchain with code. This time, I’ll try to describe the structure of a single block. I will use the Bitcoin blockchain to explain blocks, but keep in mind that the concepts will remain more or less the same. It could be useful to read my last article to understand a few things first.
Continue reading Blockchain: what is inside a block?

Read more



Bitcoin and cryptocurrencies made a lot of noise lately. I have been rather disappointed by the turn the cryptocurrencies took, from an amazing concept to what seems just another way to make quick money ( or not… ).

But I became very interested by the technologies enabling cryptocurrencies, and obviously by the concept of a blockchain. The concept is fascinating, and not limited to Bitcoin and friends. We could imagine many applications for such a technology. So, in a proper developer manner, I decided to code one blockchain, or what I think is a blockchain, to understand better what it is.
Continue reading Trying to understand blockchain by making one!

Read more



CSS allows you to apply styles to elements when their state changes, when the documents changes or when certains patterns are found in the document. We call them pseudo-classes. They are always preceded by a colon (:). They always refer to the element they are attached to, not their descendants. This is an important point to remember moving forward.

Most of the pseudo-classes are structural. They work with the structure of your markup. I want to target the third paragraph, the first link, the last list item …

Continue reading CSS 101: Structural pseudo-classes

Read more



CSS ( Cascading Style Sheets ) is a language that allows you to describe the styles your markup should have. For a long time, I took CSS for a very simple thing that turns your text to a certain color, adds a little border here, maybe a cute animation here.

Then, I started to meet developers who were really good at CSS, and well, it’s a lot more than that… So, I’m spending some time becoming better at it, and we start with the basics.


We could style our markup by adding a style attribute to each element:

<p style="color:red;">Paragraph</p>
<span style="color: red; font-size=14px;">Span element</span>

I let you imagine how many different rules you would have to write this way… let alone apply any kind of changes…

In CSS, we can use differents selectors. They allow us to group different elements and apply the same style rules to this group. We will explore:

  • Element selectors
  • Class and ID selectors
  • Attribute selectors

Element selectors

For markup, I will use HTML throughout this article. We can group our styles by elements. Give each *

* element a certain style for example.

The h1 and p tags are grouped and share the same rules. Instead of creating three different rules to style the paragraphs and two rules for my headers, I only make one for each.

You can also group different elements together by separating them with commas in CSS:

Do not forget the commas in this case! If you do, it won’t group the elements, but select the descendents elements.

Class and ID selectors


To allow more flexibility while selecting your elements, you can specify one or more classes to an element. Each class is space-separated. We use the class attribute.

<p class="danger"></p>
<h1 class="danger title"></h1>

In CSS, you use a period ( . ) to indicate that you are targetting a specific class name. You can chain several classes one after another.

.danger {
 /* Will style the paragraph */

 /* Will style the h1*/

Note that the order is not important. If you specify .title.danger, the effect will be the same. It also doesn’t need to be an exact match. If you add a third class to your header, it will still follow the rules in the .danger.title block.


ID are very similar to classes. The main differences are that an ID can only be used for one element. An element can only have one ID, because ID can’t have space-separated values. ID have more weight than classes. If you have an element with an ID and a class that change the same thing ( the color for example ), the style describe in the ID rules. Finally, ID are targetted by a pound sign ( # ) in a CSS declaration.

Attribute selectors

Class and ID are special attributes that CSS is able to handle in a special way. But in our markup, there are a LOT more attributes we can use. CSS allows us to target those in different ways to suit your needs

  • Simple attribute selector

You write CSS rules to check if an element has a special attribute specified. We don’t even care about the value. For example, I want to target all p element who have a key attribute:

p[key] {
  color: red;

/* OR, all elements with a key attribute, not just p */
  color: red;

As you can see, we use [] in CSS to target attributes. So this is the first one, very general.

  • Exact attribute values

This time, we are looking for the exact attribute value.

  /* If the href is https://google.com, it won't match */
  a[href="google.com"] {
    color: purple;

  /* The following are NOT equal */
  [class="danger warning"] {
    color: red;

  .danger.warning {
    color: orange;

Again, we are looking for an exact match. So, if we use the bracket notation, the element needs to have the classes danger and warning, in this order AND only those two. Quite different from the dot notation…

  • Partial attribute values

Finally, if you really want to have great control over the attributes you are using, you’ll need to use the following attribute selectors.

  /* Attribute contains val in a space-separated list of words */
  /* Would match "friend" in "my friend Joe" */

[attribute*="val"] {
  /* Select any element with an attribute whose value CONTAINS val */

[attribute^="val"] {
  /* Select any element with an attribute whose value BEGINS with val */

[attribute$="val"] {
  /* Select any element with an attribute whose value ENDS with val*/

  Select any element with an attribute whose value starts with val followed by a dash (val-) 
  OR whose value is exactly equal to val.

[attribute="val"i] {
  /* Add a i after the value to make it case insensitive ( The value will be case insensitive, NOT the attribute name. */



There you have it. A quick overview of the different ways you can select elements with CSS. There are of course a lot of different things possible with these tools. But it should give you enough to play around.

Read more


In the last few weeks, I was very intrigued by React native. I kept seeing more and more articles like this one, so I decided to take a deeper dive into React Native and actually use it, for real.

Meteor is the framework I use at work, and I now have some experience with it. I thought about connecting the React Native application with a Meteor back-end. This article will show you how to get things started.

Creating the Meteor app

First things first, we will create a Meteor application.

meteor create serverMeteor

For now, that is all we need. We’ll come back to that.

Creating our React Native app

I’ll use the very useful create-react-native-app tool. You can get more info on this, check this link. It will also explain how to use the Expo client app to see your work, very useful!

So, we run a command like this:

create-react-native-app reactFront

Now, you’ll have two folders. One named meteorServer that contains your Meteor application, and an other named reactFront where you will find your react-native application.

React-Native: Creating a simple PhoneBook

For the sake of brevity, we will create something simple. The user will have a form with two inputs. The first will take a name, the second a phone number.

After modifications, here is how App.js looks like:

import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';

export default class App extends React.Component {
    this.state = {
      name: '',
      number: ''

  addPhoneNumber = () => {
      number: '',
      name: ''

  render() {
    return (
      <View style={styles.container}>
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}

          title='Save Phone Number'/>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 20
  input: {
    borderWidth: 2,
    borderColor: 'gray',
    height: 50,
    margin: 10

I added two TextInput elements and a Button element. I also added some styles for the input. In React Native, we use StyleSheet.create({}) to control styles. Or you could style use the inline objects as in React.

On my iOS simulator it looks like this:

Ok, for now, when we click ( or tap ) on the button. Nothing happens. It logs the values in the console and reset them. Let’s move on to the back-end.

Meteor: Preparing the method and publication

Go to the folder where your Meteor application is located. Mine was called serverMeteor.

Let’s create a /imports folder, and inside this /imports, we’ll add an /api folder. Just to follow the proper Meteor conventions.

Here is the plan: we will create a Meteor method that our React Native app will call when we click on the Save Phone Number button. This method will save the name and the number to the Meteor mongo database.

Then, we will create a publication that our React Native application will subscribe to. It will simply return all the entries we have. Let’s go!

In /imports/api/, let’s create a PhoneNumbers.js file that will hold our small back-end logic.

export const PhoneNumbers = new Mongo.Collection( 'phoneNumbers' )

  addPhoneNumber( data ){
      name: data.name,
      number: data.number
    }, err => {
      if (err){
        return err
      } else {
        return null

Meteor.publish( 'getAllNumbers', () => {
  return PhoneNumbers.find({})

Nothing fancy here. We create our collection, our method addPhoneNumber and our publication getAllNumbers. And that’s it for Meteor. Let’s make the two applications talk to one another.

React Native: Adding react-native-meteor

Go back to the React Native folder. We will use the react-native-meteor package to connect both applications.

npm install --save react-native-meteor

Here are the changes we need to make:

  • Call the addPhoneNumber method when we click our button.
  • Subscribe to our getAllNumbers publication
  • Display the numbers in a list
  • Make sure our React Native app is aware of our Meteor application.

Let’s start with the method call. If you’ve work with Meteor/React before, this will look very familiar:

// In our App component
addPhoneNumber = () => {
    const data = {
      number: this.state.number,
      name: this.state.name

    Meteor.call('addPhoneNumber', data, err => {
      if( err ){
        console.log( err )
      } else {
          number: '',
          name: ''

Next, let’s subscribe to our publication. For this, we will wrap our App component in createContainer provided by react-native-meteor. Let’s import it at the top of our file:

import Meteor, { createContainer } from 'react-native-meteor'

Good, now we will NOT export our App component, but the createContainer wrapper. Like so:

// The App Component will be defined above like so:
// class App extends React.Component{ ... } 

export default createContainer( () => {
  return {
    phoneNumbers: Meteor.collection('phoneNumbers').find({})
}, App) // Need to specify which component we are wrapping

Ok, that’s done. So we will get the phone numbers in a nice array. We will display them in a list. Nothing fancy, we will use the FlatList component. Don’t forget to import FlatList from react-native. Our render function will look like so:

// Still in the App component my friend
  render() {
    return (
      <View style={styles.container}>
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}

          title='Save Phone Number'/>

          keyExtractor={(item, index) => item._id}
          renderItem={({item}) => (
              <Text>{item.name} || {item.number}</Text>
          )} />

FlatList takes the array of data and loops through it in the renderItem function. I’m just displaying the name and the phone number. keyExtractor is used to create keys for each element we render in this list, just like React needs in the web. Each key will be the ObjectID returned from MongoDB.

Finally, let’s make sure our React Native application knows where to get those informations:

//I have only one component anyway...

We use the connect method from react-native-meteor.

Note: Because I am only using the iOS simulator here, I can use localhost. If you use the android simulator, you will need to use the IP address of your machine ( 192.168.xx.xx:3000/websocket for example).

Clicking on the Save Phone Number button will populate the database in our Meteor application. Our subscription to the publication will retrieve the informations and display them!

Just a final picture to show you how it looks on my iOS simulator:

Well, there you have it. You can now connect a React Native application to a Meteor application without a problem. Have fun!

Warning: It seems that using npm5 with create-react-native-app is buggy and doesn’t work properly. You should probably use npm4 or yarn to make sure you don’t encounter any problems for now.

Read more