Understanding Bitcoin

Companion Video:

Bitcoin is just another currency. Bitcoin refers to the entire currency system and BitCOINS are basic units (just like Dollar or Pound)

Like other currencies, you can save/ spend Bitcoins, or exchange with other currencies.

What is Digital currency?

Digital currency can be easily stored and used on a computer.

Dollar can be considered digital currency as such, we can use it to shop online.

However, dollar supply is controlled by a centralized bank.

What is Decentralized?

Gold coins are decentralized, means, there is no central authority controls the supply of gold.

Anyone can dig for gold and distribute gold, but it is not easy to exchange with exact change.

Also not possible to transfer over internet.

Bitcoin is the world’s first currency that is both Digital and Decentralized, somewhat like digital gold.

Bitcoins is a stateless currency, not associated with any nation, but it is not a private currency.

Private currencies are issued by person or company/organization, may collapse due to bankruptcy or other failure of the person or company.

Bitcoin is not a company, nor controlled by a person/organization, so there is no single point of failure. Nobody can inflate the supply or create hyperinflation.

Why Bitcoin?

Now-a-days people can send digital cash back and forth via a central mediator (like, Paypal).

These central mediator can track payments and record the money transfer in a privately held account ledger.

Let’s indulge the thought that if we can trust such central mediator, or if we can send cash without being tracked.

The challenge with decentralized money is, how two strangers can trust each other and accomplish a financial transaction? [Aka, Byzantine Generals’ problem]

Learning from history

Between 1921 and 1924, the value of the German mark fell by a factor of more than 10 trillion due to overprinting by the government.

In 2008, the government of Zimbabwe printed so much of its currency that in a single year, a loaf of bread increased from $1 to $100 billion.

In both cases, any savings that people had in the form of national currency were completely destroyed.

Hello Bitcoin!

In 2008, Satoshi Nakamoto, described an elegant solution of Byzantine Generals’ problem and the invention of Bitcoin in a paper, Bitcoin: A Peer-to-Peer Electronic Cash System.

First version of the software that demonstrated the concept was written by Satoshi, but now open source.

In January 2009, first bitcoins were distributed using the software.

Slowly but surely the use of Bitcoin increased and what began as an experiment, now a multibillion dollar economy and process hundreds of thousands transaction per day.

Benefits of Bitcoin

  • International currency, anyone can send bitcoins to anyone else, almost instantly.
  • Travel the world without exchanging to local currency.
  • No middle man involved, so the transaction fees are negligible.
  • No need to provide personal information like credit cards.
  • No risk of losing savings or runaway inflation, it is designed to have fixed supply.
  • Fundamentally impossible to counterfeit.
  • Merchants can accept bitcoins without any paperwork.
  • No governments can seize your money.

Why understanding bitcoin is complex

At times, it was not comfortable for people to use pieces of paper instead of precious metals (gold/ silver).

Additionally it uses modern cryptography, digital signatures, public/private key pairs and secure hashing.

To resist abusers to destroy the system, Bitcoin’s design uses game theory to align incentives to maintain network and who act in for selfish interest.

How Bitcoin works

As a decentralized currency, without any central authority, everyone cooperates to keep track of everyone else’s money.

Imagine only $21 million exists in the world and there is a list of all people who possess the money and in what amount and EVERYONE has a copy of this list.

When you give $2 to your friend, you must subtract $2 from your entry and add $2 to her entry. After informing her about the transaction, she updates her list as well.

Now everyone needs to update the list, otherwise their list would be inaccurate. So in addition to notify your friend, you need to publicly announce that you are updating the list.

Now if you try to cheat and send your friend $1000, that you do not possess, your cheating attempt would be easy to catch, cause everyone knows you don’t have $1000.

Imagine the whole transactions are carried out on computers, automated and through internet and replace $ with bitcoins.

Few questions,

  • How the unit should be valued? Should a haircut be worth of 5000 bitcoins or 0.005 bitcoins?
  • How do you obtain the copy of the list?
  • How bitcoins initially distributed?

We will come to these points later.

Bitcoin units

Total currency is capped at 21 million, but the smallest unit is a hundred millionth of a bitcoin (0.00000001 bitcoins), called satoshi, in honor of Satoshi Nakamoto.

Goods can be priced very precisely with exact change. Like a gallon of milk is 0.00152374 bitcoins or 152,374 satoshis.

Merchants uses short form BTC or XBT for bitcoins.

1 bitcoin = 1 BTC or 1 XBT
1 BTC = 1,000 mBTC
1 mBTC = 1,000 µBTC
1 µBTC = 100 satoshis

Standard of currency code (ISO 4217) wise, since Bitcoin is a nongovernmental currency, the name should start with X, as is the case with gold (XAU) or silver (XAG).

Bitcoin address

Bitcoin uses a public ledger that indicates the number of bitcoins and their owner. Instead of owner name, they use Bitcoin address to associate with a owner.

A sample Bitcoin address:

Pretty much like a bank account number, usually starts with 1.

To send someone bitcoin you need to know their Bitcoin address. Similarly, when you share your address, others can send you bitcoins.

People uses QR (Quick Response) code to represent their address. You can print your address or QR code in business card/ website/ storefront.

You need an internet connection to send bitcoins, but you don’t need to be connected to receive. So you can pass out your address and collect bitcoins while you sleep.

Other than QR code, you can use first bits scheme to send out first few characters of the address. Or, you can use address-shortening service (like URL shortening). From version 0.9+ Bitcoin supports human readable address (like, website address rather than IP)

Bitcoins ledger copies are distributed across millions of computers, so there is no central point of failure and impossible to erase records.

But Bitcoin ledger are public information, so how do you maintain privacy? Although there is no personal information in ledger but as you share your address, people will know your Bitcoin balance.

To maintain privacy you can use many Bitcoin address, but publicly share one or some of them.

In general, maintaining complete privacy while doing online transaction is very difficult with or without Bitcoin. Although Bitcoin provides far better protection than Credit card, however other privacy-protecting tool (TOR) might need to be used as well.

Private Key

To unlock (move or send) bitcoins, there is a private key associated with each Bitcoin address.

If Bitcoin address is similar to bank account number, then private key is like PIN.

When a transaction is broadcast, computer check whether the transaction has been digitally signed using a private key that can only be created by someone possessing the private key.

Similar to PIN, private key should be kept secret. If someone obtains your private key, he will be able to spend your bitcoins.

Private key can be used to produce digital signature, but the reverse is not possible, means, you can not obtain the private key using digital signature. A digital signature can not be reused.

This is fundamentally different from online payment with credit card. You provide your card number to someone to authorize the transaction and that number can be reused (maliciously)

Unlike PIN, only you know the private key, not any bank/others. But if you lose the private key the bitcoins will remain locked in that address forever.

Key association

Every private key is associated with a single Bitcoin address, but the reverse is not true. A Bitcoin address can require multiple private keys to unlock.

Most people use multiple Bitcoin address, each with it’s own private key and store them in a digital wallet.

Bitcoin wallet

A Bitcoin wallet is a collection of address and corresponding private keys owned by one person. It helps to organize money and maintain privacy.

Bitcoin wallet program is a tool for common Bitcoin tasks, like, creating new Bitcoin address, sending bitcoins, backing up private keys etc.


GreenAddress.it android (a bitcoin wallet program)

Several other Bitcoin wallet program can be found here

There are some sites that are giving away small amounts of free Bitcoin, mostly for the newbies to try out. Here are two of these, TryBTC.com and Bitcoin Street Faucet. [No guarantee that they are still providing free coins when you stumble this blog post.]

Some wallet (for example, Electrum) ask for a seed, consists of 12 random words from you to generate Bitcoin address and private key. In case you lost your private key, it can be regained using the seed.


Bitcoin ledger is called Blockchain. Transactions are added in pool and about every 10 minutes, the pool transactions are bundled into a block and added to the blockchain.

transaction ID: 10110
address 1bl35lndlkas32l33 -2.0 BTC
address 18scklshl13nnlk33 +2.0 BTC
transaction ID: 10232

The thousands of computer that collects transactions and add them to blockchain are called miners. Anybody can be a miner by running open source Bitcoin-mining software.

Why would anyone update the blockchain? You might not want to send/receive bitcoins for months, then why bother update?

For the Bitcoin system it is required to keep the blockchain up-to-date. Otherwise, if only person had the latest copy then she could manipulate the records.

If you add a blockchain you will be rewarded with all the transaction fees of that block.

Blockchain lottery

Based on some probability a miner is chosen to add a block to blockchain. What is the purpose of using a lottery system to run Bitcoin?

When we engage in a transaction in $, we put our trust on a bank to confirm the transaction. The banker’s job is to announce that both party can trust each other and to update the ledger correctly.

In Bitcoin anyone can be a banker (miner) and then he announces to the network that the transaction is valid. Picking a person randomly helps to accomplish this.

There is a small chance that miner knows a person involved in a the transaction. To avoid this personal conflict interest, each miner also needs to confirm the previous transaction along with her’s.

To eligible for the next lottery, a miner needs the latest copy of the blockchain. It motivates then to add as many blocks to blockchain and update the blockchain.

The process is done automatically by Bitcoin-mining software, run by the community; no central authority exists to choose a winner. Thousands of miners constantly helping the transaction process.

Blockchain forking

Lottery system works as expected most of the time. Occasionally two miner finds a block at the same time and blockchain become forked, resulting two different branches.

For example, A and B both miners add a block to blockchain. The contents are identical but added by different miners.

Now in next 10 minutes, whichever these two branches take the next block would be the winning branch and other branch will be discarded, called orphaned.

The process is automatic and most of the users do not notice this forking, ignoring orphaned blocks and thus no negative impact on the use of Bitcoin.

Transaction confirmation

The transaction that not yet added to blockchain has a depth 0, newly added block transactions have depth 1, immediate previous transactions have depth 2.

For low-value transactions it’s enough to forgo the transaction of depth 1. Merchants require higher depth confirmation before selling high-priced item. But how this confirms if the transaction is valid?

Suppose a super-villain try to double spend his bitcoins. He simultaneously sends same bitcoins to receiver address and another address owned by him.

This is called Double-Spending problem. To know more details follow the post.

When miners detect two transactions that spent same bitcoins, but sent to different address, they accept the first one they received and ignore the second.

It is impossible to add both transaction to the blockchain as one contradicts to the other.

The super-villain intent is for the merchant to delivery the product but transaction to be ignored and the other transaction to be added to blockchain.

This devious scheme is usually unsuccessful because many merchants use special monitoring software that can recognize two conflicting Bitcoin transactions.

Even simpler for the merchant to wait for 10 minutes until the transaction is added to blockchain. However, what if the super-villain has truly extra ordinary resources (many millions of $ of hardware) and orphaned the block!

To cope with this remote possibility, merchants who sell high value products typically wait until a transaction has depth 2 before delivering the product.

Mining Bitcoins

Total supply of bitcoin is capped at 21 million and it reached slowly over time. Miner reward is included small sum of newly minted bitcoins that increased the total supply.

Miners must find a certain winning number by generating numbers at random repeatedly to win (thus getting newly minted bitcoin). It creates incentive for the miners to use power computers.

Today, mining requires significant capital, expertise, inexpensive electricity. Similar to gold mining, at one time unearthing gold could be done by a person, now this is performed by large companies with expensive drills.

There are two parts of mining reward.

  1. First part is transaction fee. Transaction fees are typically few cents, but as each block contains hundreds or thousands of transactions, the reward is the sum of all transactions fees.
  2. Second part is newly minted bitcoins.

The second part is decreasing gradually over time.

  • The first 210,000 blocks – on a 10 mins spanning – took 4 years to mine. It provided every miner 50 newly minted bitcoins per block + transaction fees.
  • The next 210,000 blocks – (210,001 to 420,000) – reward miners 25 newly minted bitcoins per block.
  • Thereafter, the reward drops to 12.5, 6.725 and so on.

This mining process is only source of new bitcoins. It is the reason no more than 21 million bitcoins will ever be in circulation.

Every 4 years the newly minted bitcoins rewarded per block halves.

Question: How can you ensure that only 210,000 blocks will be added every 4 years, it could be more (or less) based on the number of transactions and users?

Answer: Blocks are constrained by time, not transactions. A block can have any number of transactions, but one block will be added at every 10 mins. Due to increasing number of transactions in each block it requires a performant machine to process.

Transaction fees will grow as the Bitcoin user base grows. Eventually, transaction fees will be greater than newly minted bitcoin value.

At that point, Bitcoin network will be sustained entirely through transaction fees.

Don’t do this

Bitcoin wallet is pretty foolproof. However don’t do this,

  1. You created your first bitcoin wallet.
  2. You wrote down your address and private key.
  3. Well, what if you computer gets a virus that steal all your money?
  4. You thought that let’s DELETE the wallet, as you have written down private key.
  5. You money will go into back hole!!

What went wrong?

  • A Bitcoin wallet is not just ONE address, instead it’s a LIST of Bitcoin addresses.
  • When you send money from one address, all the money is used up of that address.
  • Don’t worry yet!! your money is safe. Listen to the rest of the process.
  • After sending, rest of the money moved to another address of the same wallet.
  • But you won’t be able to recover the new address if you only have the private key of the old address.

Think in terms of ENTIRE Bitcoin Wallet, not individual Bitcoin address.

Some wallet apps have a feature called, Import private key – only experts should rely on this risky feature.

Storing Bitcoin safely

Storing Bitcoin safely means storing your private key(s) safely. Nothing can be protected with 100 percent certainty. Bitcoins can be stored extremely securely or loosely (due to technical failures)

Your bitcoins are stored in blockchain. Millions of copies of blockchain are distributed all over the world and no disaster can erase every copies, so you don’t need to worry about your Bitcoin address.

To access the bitcoins you require private key. And you need to store your private key with serious precautions. Bitcoin allows you to be your own bank. It comes with great responsibility.

Hot storage vs Cold storage

Hot storage refers to private keys are stored on a online device. Cold storage refers the storage not accessible via internet.

You can share your Bitcoin address with everyone, but storing the private key in cold storage provides better security. Remember, a hot storage can not become cold by going offline.

If a wallet company claims they store your private in cold storage but the fund can be moved to hot storage conveniently, it is a red flag. May be they are not using cold storage at all. Cold storage requires a person to access an offline computer physically.

Personal vs Hosted wallets

With a personal wallet, only you know the private keys.

With a hosted wallet, a third party knows your private keys and they do operations (send, receive, store) on your behalf, (unlike traditional bank who stores your cash in vault and won’t give you keys to open it)

With online personal wallet, they host the wallet software on their server but not the private keys.

The liability can be distributed using two private keys, one will be used by customer and other by online service. Both keys will be required for unlocking one address.

Safety, Security and Convenience

These 3 major factors are sometimes conflict with each other.

  1. Safety (preventing accidental loss of bitcoins)
  2. Security (preventing the theft of bitcoins)
  3. Convenience (ability to easily unlock bitcoins)

Most people use two storage methods: one for storing small amounts conveniently but less securely, another for large amounts less conveniently but very securely. Just like carrying small cash in pocket but most of the cash in bank account.

Storing small amounts

The following methods are for small amount that are convenient, easy to use and reasonably safe.

A sophisticated attacker can hack your traditional bank account. As remedy banks implement daily withdrawal limits and other measures.

Online hosted wallet services

Similar to online banking, no software installation is required. They manage all your transfers on your behalf.

But you do not have access to your private keys and you may loose your bitcoins if the service provider goes bankrupt.

You can access the service using username/password (so can a thief!). Make sure your provide require two-factor authentication.

Remember that, provider knows who you are, how much bitcoins you have and all transactions.

Online personal wallet services

Similar to Online hosted wallet services, but once the website loads locally on your device, no communication occur to server.

You can make transactions by using your private keys that never leave your device.

If the company goes bankrupt you will have a little bit of inconvenience but never loose your bitcoins.

Typically it’s a greater responsibility. If you loose your password to their service, they can not rescue it for you. Write down your password in a secure place.

Online personal wallet services provide better security but they may track usage patterns and other data other than private keys.

Personal hot wallet

Install the wallet software (open source) in your device and full responsibility is yours. It provides greater security but you are to protect your device from malware, viruses.


  • Do not keep large amount in your hot wallet.
  • Keep in mind that you computer can be stolen, destroyed, lost.
  • Avoid cloud storage to store your private keys.

Recommended personal hot wallet is Electrum or Multibit, both are open source and in use for many years.

Storing large amounts

Disclaimer: If you are storing a large Bitcoin fortune, consider having a security expert audit your storage method.

To try out the following methods you can use open source Bitcoin wallet generator, Bitaddress. You can download the entire website and run it on offline computer.

To use this website you need to cursor over a box of letters and numbers to provide a random seed to generate Bitcoin address. It’s a challenge of CS to generate truly random numbers.

Paper wallets

This is simplest and most popular cold storage method. Generate address and private in an offline computer and write down the keys in a paper and locked it away.

When you need to unlock, use import private key feature of any bitcoin wallet. Then immediately transfer the rest of the amount in another address and store the private key same way.

Paper wallets are one time use only. For each transaction you will create a new address and store a new private key.

Do not scan, take photo or any duplication method other than handwriting. Some photocopiers maintain records of every document they scan/copy.

Encrypted paper wallets

You write down an encrypted version of your private key in a paper. Most common encryption method used is BIP38 encryption.

To create BIP38 encrypted paper wallet, go to bitaddress site and shake your mouse until you generate enough random data for encryption.

Remember for encryption uses passphrases, not password. If you forget your passphrases you’ll permanently lose access of your bitcoins.

Store your paper wallet (written down encrypted private key) and passphrases into separate safe locations.

Offline transaction signing

In this process, you need two computers, one is online and other one is offline. Steps are follows

  1. Create an unsigned transaction from online computer.
  2. Copy the unsigned transaction to offline computer.
  3. Digitally sign the transaction in offline computer.
  4. Copy the signed transaction to online computer.
  5. Send signed transaction to the Bitcoin network.

To help out this process you can try a highly recommended wallet called Armony Bitcoin Client, which is open source and designed with maximum security in mind.

Fragmented private keys

A cryptographic trick named secret sharing, a Bitcoin private key can be divided into many fragments.

This is called m of n private key, where,

m = necessary fragments
n = available fragments.

For example, 3 of 5 private key means, a private key is split into 5 fragments and any 3 of them can be used to reconstruct it.

Several different cryptographic protocols are used for secret sharing, most popular is Shamir’s Secret Sharing method and several open source implementations of this method can be found on the Web.

Multi-signature addresses

This method uses multiple private keys rather fragments of single private key.

For example, 3 private keys are required to unlock an address, Or, any 2 of the 3 private keys can be used to unlock an address.

Multiple persons are required, not even CEO or President can solely able to unlock an address.

The Bitcoin hardware wallet

This is a small device that store your private keys in a way that no one can extract them from the device.

It works as a cold storage. Downside is, you need to purchase it and you may lose it.

Trezor received a lot of attention,

Trezor is like a paranoid chef who will never reveal his secret but cook for you anytime. You can use to any computers (good for traveler).

The bitcoin brain wallet

This method is recommended only for experts. Memorize your private key as passphrase. Then use the passphrase in an offline computer to retrieve your private key and address.

Buying bitcoins

To be continued


  1. Befuddled
  2. Introduction to Bitcoin and Decentralized Technology

Git and Github: Key points

Command line tutorial

File compare tool from OS

Windows :- FC (File compare)
Linux/Mac :- Diff (Difference)


Check git version
git --version

Git commit story

  • Each commit has an Id. For a medium sized repository, first 8 chars can be enough to uniquely identify the commit.
  • Details log command,
    git log --stat
  • Display the difference between two commits,
    git diff COMMIT_ID_1 COMMIT_ID_2
    First write source commit and then destination commit. Depending on the source and destination order, you will be displayed add/delete codes.
    Altering these two will show the same changes but in opposite order.
  • There is a difference between copy and clone. In Clone, history will be downloaded as well as content.
  • Activate colorful git bash:
    git config --global color.ui.auto
  • Checkout
  • git checkout COMMIT_ID (Checkout a commit)
    git checkout BRANCH_NAME (Checkout a branch)

Detached HEAD

Whenever you checkout a previous commit, you will be in detached HEAD state. However you can restore the head by
git checkout master (Go back to master)
git checkout BRANCH_NAME (Go back to a branch)

Essentially it means, you are looking at a commit that was not labeled with a branch name.

You can see where HEAD is points to by command,
cat .git/HEAD

Note that, git log works from current branch to the parent commit

if you checkout an earlier commit and make changes and create a new commit then the new commit is lost and will not be displayed in output, cause it’s not reachable from current branch.

You can create a branch though to retain the changes in that newly created commit,
git checkout -b new_branch_name

Git workspace

Download two files

  1. git-completion.bash
  2. git-prompt.sh

add these two files in your .bash_profile like this,

source git-completion.bash
source git-prompt.sh

Set default editor to write commit messages

If you would like to open up your favorite editor whenever you write, git commit then run the following command,
git config --global core.editor "SUBLIME_PATH -n -w"

Here we are assuming your favorite editor is Sublime and replace SUBLIME_PATH with Sublime executable file.

In general if you would like to create an alias, (i.e typing a shortcut to open up Sublime or any other editor) the follow the command in your .bash_profile file
alias subl = "SUBLIME_PATH"

Common git commands

git log
git status
git clone
git diff
git checkout
git init

Staging area

There are 3 spaces:

  1. Working directory
  2. Staging area
  3. Repository

Create a file,
Using echo "First change" > index.txt

Initialize a repo by,
Using git init

Now index.txt is in your working directory.

Using git add index.txt you can add this file to staging.
Using git add . will all files to staging.

When you commit, git takes the entire changes of staging area and make a commit to repo.

Commit message style


feat: a new feature
fix: a bug fix
docs: changes to documentation
style: formatting, missing semi colons, etc; no code change
refactor: refactoring production code
test: adding tests, refactoring test; no production code change
chore: updating build tasks, package manager configs, etc; no production code change

The Subject

Subjects should be no greater than 50 characters, should begin with a capital letter and do not end with a period.

Use an imperative tone to describe what a commit does, rather than what it did. For example, use change; not changed or changes.

The Body

Not all commits are complex enough to warrant a body, therefore it is optional and only used when a commit requires a bit of explanation and context. Use the body to explain the what and why of a commit, not the how.

When writing a body, the blank line between the title and the body is required and you should limit the length of each line to no more than 72 characters.

The Footer

The footer is optional and is used to reference issue tracker IDs.

Example commit msg

	feat: Summarize changes in around 50 characters or less

	More detailed explanatory text, if necessary. Wrap it to about 72
	characters or so. In some contexts, the first line is treated as the
	subject of the commit and the rest of the text as the body. The
	blank line separating the summary from the body is critical (unless
	you omit the body entirely); various tools like `log`, `shortlog`
	and `rebase` can get confused if you run the two together.

	Explain the problem that this commit is solving. Focus on why you
	are making this change as opposed to how (the code explains that).
	Are there side effects or other unintuitive consequenses of this
	change? Here's the place to explain them.

	Further paragraphs come after blank lines.

	- Bullet points are okay, too

	- Typically a hyphen or asterisk is used for the bullet, preceded
	by a single space, with blank lines in between, but conventions
	vary here

	If you use an issue tracker, put references to them at the bottom,
	like this:

	Resolves: #123
	See also: #456, #789

Commonly used git situations

  • You can compare two commits by git diff, but there is no Id in staging and working directory. So to compare working directory with staging area use no-arg git diff like this,
  • git diff

  • To compare staging with repo
  • git diff --staged

  • Discard changes in working directory
  • git checkout -- FILENAME

  • To discard any changes in working and staging area (be very careful, you can not revert this, codes in working and staging area have not been recorded )
  • git reset --hard

  • To go back to a particular commit, by discarding all the commits after it
  • git reset --hard DESIRED_COMMIT_ID

  • To go back to a commit but keeping your working directory as it is you can use reset soft. It will make code to move to that commit but your working directory will be same as of now. So the newly made changes will be there but code is commited upto that desired commit.
  • git reset --soft DESIRED_COMMIT_ID

  • To delete changes from staging area/li>
    git rm --cached FILE_NAME

Git branches

  • Display all branches as a list
  • git branch

  • Create a branch
  • git branch BRANCH_NAME

  • Checkout a branch
  • git checkout BRANCH_NAME

  • Graphical view of branches
  • git log --graph master BRANCH_NAME

  • Graphical view of branches (shorter)
  • git log --graph --oneline master BRANCH_NAME

  • Delete a branch
  • git branch -d BRANCH_NAME

  • Display the recent commit of all branches
  • git branch -v


How git merge works!

Suppose original file content is like below,

Now Tarif vai made some changes

Tarun vai also made some changes

Now if you ask git to merge the changes how will it manage to merge?

We are certain that,
B and
will present in final merged version, as these both are common in all 3 versions.

A will not present. Becasue, Tarif vai deliberately removed it and Tarun vai didn’t do anything. Of course you don’t want to see a line in final merged version that has been deleted explicitely.
C will be present as Tarun vai added it.
E will be present as Tarif vai added it

When you merge two branches, git essentially creates another commit, called merge commit. But you may have missed it before because of IDE or SCM GUI.

Suppose, your master branch has some new commits and you are merging a previously created branch with it. Now if you run git log, in what order the log file will be displayed?
– It will be displayed in chronological order. That means, commits log will be jumbled up as the commits have been created in different point of time.

How will it affect you?
– If you run git diff of two consecutive commits, you may experience a large number of changes. May be because they are from differnt branch and just happen to reside together because of their commit time.

How do you get the REAL changes of a commit is this situation?
– Run git show COMMIT_ID, this will display the diff of this commit to it’s immediate parent commit

Merge Conflict

Merge conflict ocurres when two persons make changes in a single line. For example,

Original file content was,

Tarif vai made changes in 2nd line,

Tarun vai also made this his changes in 2nd line,

Before proceed with Git, you need to resolve the conflict. Remember, merge and conflict resolution goes into a single commit.


Rebase is kind of an extension of merge. You still have to do the merging but the end result will be a bit differnt. Follow the concepts,

  • From a feature branch, if you rebase to master, git rebase master then the unique commits in feature branch will be applied to one by one on the top of present day master branch.
  • After the rebase you still need to do the merging. Checkout master branch and run,
  • git merge FEATURE_BRANCH

  • Now if you try git log --oneline --graph, you should see a cleaner commit history, as if there was no branching and you just applied the changes in master directly.


We learnd there are 3 spaces in local repository: Working, Staging and Repo.
In remote repository like Github there are two types of repository: Origin, Upstream (You can create more if you wish, but these two are most common)

  • You can add multiple remote repos, if there is only one repo then we usually refer it by name origin
  • Fetch and Pull could be different url. To check remote urls,
  • git remote -v

  • To push to origin follow the format git push TARGET_REPOSITORY LOCAL_REPOSITORY
  • git push origin master


Fork is a concept introduced by Github, it’s not part of Git. Gitlab might call it a different name.
Fork means to clone repository from a other’s github account to your github account

When you push to remote branch there are two branches in your local machine,

  1. origin/master
  2. master

What happens when you have changes in both local master and origin master?
– Let me introduce git fetch. Git fetch updates your local machine’s origin/master and does not touch your local master branch. So there is no chance of conflict. After that you can use git log and git diff to compare.

Now you can also merge manually or you can do the fetch and merge combined by this command
git pull origin master

For log and diff in origin/master follow the command,
git log origin/master
git diff origin/master master

You can update all yoru local copies of every branches in the origin repositry by,
git fetch origin

If git pull == git fetch + git merge, then why git pull doesn’t generate a new merge commit like we see before?
– It’s called fast-forward merges. When base commit is ancestor of the other commit then it happens and merge commit will be a redundant commit, don’t ou think?

Pull request

When creating pull request from github, make sure you are selecting correct parent and correct child and also make sure chind branch can be successfully merged with parent branch so that one can accept just by a single click. Otherwise github will disable the merge request button.

So whenever you are making a pull request you need to pull the parent branche’s latest code and resolve all conflicts and create the pull request. If you request gets rejected then,

  1. fix the issue
  2. pull again from parent branch (if there is some changes meanwhile
  3. resolve conflicts (if any)
  4. push again

if you would like to get updates from Grand parent repo (from which you made the fork) or would like to make a pull request to Grand parent repo then you need to add the Grand parent repo as upstream by convention. it will create an upstream/master in your local machine.

To add an upstream url,
git remote add upstream GIT_URL

Now the rest follows exactly same as origin, just make sure to use upstream/master instead of origin/master when you refer to upstream.

Thanks for reading!

Golang: First look

Features of Golang:

  1. Compiled language. So, you can measure performance and do memory profile. It generates machine code that will run on the processor.
  2. Garbage collected. Usually system level langauges are not garbage collected, but Go is. Also note that, Go garbage collector is latency free. So, garbage collector runs without any speed bumps.
  3. Language level support for concurrency strategy known as communicating sequential processes aka Actor model.
  4. It’s not a C derivative language. It’s a static language but with the ease of dynamic language

Interesting notes

  • Like Swift playground in Xcode, you can try out go code in https://play.golang.org/
  • Go doesn’t have method overloading.
  • Function name starts with Uppercase are going to be exported (public)
  • Go packages can be directly imported from URL inside code
  • You can’t write curly braces in separate line, like C#. Yey!


Install Go and make sure to define GOROOT and GOPATH

export GOROOT="/usr/local/go"
export GOPATH="/Users/USERNAME/GoWorkspace/"

First Program

package main

import (

func main() {
	fmt.Println("Hello, playground")

#1. package declaration is required and it is called module. “main” package denotes entry point
#7. You have to maintain the signature
func main() {

as it is the execution point

To run,
go run main.go
To build and make executable file,
go build main.go


package main

import "fmt"

func main() {
	// declare multiple variable
	var a, b int

	// initialize multiple variable
	var c, d int = 1, 2

	// omit data type
	var e, f = 4, 5

	// infer type
	var g, h = 6, false

	// declare and init together
	message := "Hello"

	// by default, un-initialized value is 0
	fmt.Println(a, b, c, d, e, f, g, h, message)

0 0 1 2 4 5 6 false Hello


package main

import (

const (

var (
	globalVar = 5

func main() {


Init function

If you write init function it will run the first time the module is referenced. It will run before the main function and after all the instance variable is initialized.

package main

import (

var (
	globalVar = 5

func init() {
	globalVar = 6

func main() {


Unused imports

Unused imports will give you error. For example, if you declare “fmt” package but do not use it, you will get error,

package main

import (

var (
	globalVar = 5

func main() {

// tmp/sandbox540429761/main.go:4: imported and not used: "fmt"


Download and install Go from here, https://golang.org/

Update your .bash_profile in MacOS or .bash_rc in Linux

export GOROOT="/usr/local/go/bin/go"
export GOPATH="/Users/<username>/GoWorkspace"

Install Sublime and then Sublime package control,

Install GoSublime

Verify installation

Create a file named main.go

package main

func main() {
	println("Hello Go")

Open terminal and go to the file directory and run

~$ go run main.go
Hello Go

Data types

package main

func main() {
	var anInt int = 5

	// witout the . (dot) value will be inferred as int
	var aFloat float32 = 3. 

	// shorthand to declare and initialize
	aString := "Hello there" 


Constants again

package main

const (
	first = iota // auto incrementing number

func main() {

package main

const (
	first = 1 << iota

func main() {


Collections: Array

package main

import (

func main() {
	anArray := [...]int{3, 6, 9, 12}


[3 6 9 12]

Collections: Slice

package main

import (

func main() {
	anArray := [...]int{3, 6, 9, 12}

	aSlice := anArray[:]        // all elements
	aSlice = anArray[1:]        // except first element
	aSlice = append(aSlice, 15) // appending 15


	newSlice := []float32{1., 2., 3.}

	anotherSlice := make([]int, 20)
	anotherSlice[0] = 5
	anotherSlice[1] = 10


[6 9 12 15]
[1 2 3]
[5 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]


package main

func main() {
	for i := 0; i < 5; i++ { 	} 	hello := 0 	for { 		hello++ 		if hello > 5 {

	list := []string{"hello", "world", "go"}

	for index, value := range list {
		println(index, value)


package main

func main() {
	param := "Hello there"

func helloGo(param *string) {
	*param = "Hello Go"

func helloGo2(params ...string) {
	// variable argument function aka variadic parameter

Multiple return values

package main

func main() {
	result := add(1, 2, 3, 4)
	a, b := andAndLen(1, 2, 3, 4)
	println(a, b)
	len, sum := andAndLen2(1, 2, 3, 4)
	println(len, sum)

func add(nums ...int) int {
	ret := 0
	for _, num := range nums {
		ret += num

	return ret

func andAndLen(nums ...int) (int, int) {
	ret := 0
	for _, num := range nums {
		ret += num

	return len(nums), ret

func andAndLen2(nums ...int) (length int, sum int) {
	for _, num := range nums {
		sum += num

	length = len(nums)



package main

import (

func main() {
	aVar := aStruct{}
	aVar.aField = "hello"

	anotherVar := aStruct{"hi"}

	// creates the object in heap
	yetAnotherVar := new(aStruct)
	yetAnotherVar.aField = "hola"


type aStruct struct {
	aField string



package main

import (

func main() {
	aVar := newAStruct()
	aVar.aMap["foo"] = "bar"



type aStruct struct {
	aMap map[string]string

func newAStruct() *aStruct {
	ret := aStruct{}
	ret.aMap = map[string]string{}

	return &ret


package main

func main() {
	mp := msgPrinter{"foo"}

type msgPrinter struct {
	msg string

func (mp *msgPrinter) printMsg() {

Go routine

package main

import (

func main() {

	go printMsg()
	println("after all print")
	time.Sleep(100 * time.Millisecond)

func printMsg() {
	for i := byte('a'); i <= byte('z'); i++ {
		go println(string(i))