Definition From Bitcoin Wiki :
A Hashed TimeLock Contract or HTLC is a class of payments that uses hashlocks and timelocks to require that the receiver of a payment either acknowledge receiving the payment prior to a deadline by generating cryptographic proof of payment or forfeit the ability to claim the payment, returning it to the payer.[1]
The cryptographic proof of payment the receiver generates can then be used to trigger other actions in other payments, making HTLCs a powerful technique for producing conditional payments in Bitcoin.
HTLCs allow payments to be securely routed across multiple payment channels which is super important because it is not optimal for a person to open a payment channel with everyone he/she is transacting with.
HTLCs are integral to the design of more advanced payment channels such as those used by the Lightning Network.
For example:If Alice has a channel open to Bob and Bob has a channel open to Charlie, Alice can use a HTLC to pay Charlie through Bob without any risk of Bob stealing the payment in transit.
Let’s understand step-by-step how the transaction would unfold (Note in this example we don’t talk about the timelock aspect of HTLCs):
1. Alice wants to buy something from Charlie for 1000 satoshis.
2. Alice opens a payment channel to Bob, and Bob opens a payment channel to Charlie
STEP 1
Charlie generates a random number(x) and generates its SHA256 hash — h(x).
STEP 2
Charlie gives the hash generated to Alice.
STEP 3
Alice uses her payment channel to Bob to pay him 1,000 satoshis, but she adds the hash Charlie gave her to the payment along with an extra condition: in order for Bob to claim the payment, he has to provide the data which was used to produce that hash.
STEP 4
Bob uses his payment channel to Charlie to pay Charlie 1,000 satoshis, and Bob adds a copy of the same condition that Alice put on the payment she gave Bob.
STEP 5
FINALLY:
B →C (Transaction in step 5 goes through)
Charlie has the original data that was used to produce the hash (called a pre-image), so Charlie can use it to finalise his payment and fully receive the payment from Bob. By doing so, Charlie necessarily makes the pre-image available to Bob.
A→B (Transaction in step 4 goes through)
Bob uses the pre-image to finalise his payment from Alice
In the example above we talked about a special case in which we had one intermediary (Bob) to hop through for our payment to reach the destination.This method can be extended so that we can hop through more than one intermediary which is essential for public/mass usage.
The ideal cryptographic hash function has five main properties: