blockchain logos

Introduction

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.

Benefits

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

Conclusion

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:

00000000000000000020c60222099aaebc6e7795784f74628ec640b223d3d339

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 /
00000000000000000091C100000013DE

= 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.

Mining

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

Introduction

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.

sources:
Reuters

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.

Conclusion

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

Introduction

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

blockchain

Introduction

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

Introduction

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

Introduction

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.

Selectors

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

Classes

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 */
}

.danger.title{
 /* 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

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 */
[key]{
  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~="val"]{
  /* 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*/
}

[attribute|="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. */
}

Examples:

Conclusion

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

Introduction

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 {
  constructor(){
    super()
    this.state = {
      name: '',
      number: ''
    }
  }

  addPhoneNumber = () => {
    console.log(this.state)
    this.setState({
      number: '',
      name: ''
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>
      </View>
    );
  }
}

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' )

Meteor.methods({
  addPhoneNumber( data ){
    PhoneNumbers.insert({
      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 {
        this.setState({
          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( () => {
  Meteor.subscribe('getAllNumbers')
  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}>
        <TextInput
          style={styles.input}
          placeholder='Enter a name'
          onChangeText={name => this.setState( {name} )}
          value={this.state.name}/>
        <TextInput
          style={styles.input}
          keyboardType='numeric'
          placeholder='Enter a phone number'
          onChangeText={number => this.setState( {number} )}
          value={this.state.number}/>

        <Button
          onPress={this.addPhoneNumber}
          title='Save Phone Number'/>

        <FlatList
          data={this.props.phoneNumbers}
          keyExtractor={(item, index) => item._id}
          renderItem={({item}) => (
            <View>
              <Text>{item.name} || {item.number}</Text>
            </View>
          )} />
      </View>
    );
  }

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...
  componentWillMount(){
    Meteor.connect('ws://localhost:3000/websocket')
  }

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

meteor logo

Introduction

Meteor has become the go-to Javascript framework for our team. We use it in combination with React on the front-end. I thought I would write a quick tutorial to get started with Meteor + React. In addition, I’ll also touch on FlowRouter for the routing. If you do not have Meteor installed yet, you can follow the instructions from this page
Continue reading Meteor, React and FlowRouter: Quick Setup

Read more