DEV Community

Cover image for Double charge and Double Spending!
Areeba Farooq
Areeba Farooq

Posted on

Double charge and Double Spending!

How do we avoid ๐๐จ๐ฎ๐›๐ฅ๐ž ๐œ๐ก๐š๐ซ๐ ๐ž and ๐๐จ๐ฎ๐›๐ฅ๐ž ๐ฌ๐ฉ๐ž๐ง๐๐ข๐ง๐  when dealing with money?
.
.
.
.

๐Ÿ”น Double Charge in Paymentย Systems

A double charge is a common problem in payment systems. The client pays $100 to buy a product, but the money gets deducted twice from the digital wallet.ย 
It is usually caused by retrying the money deduction operation on errors.

We can solve this by assigning an idempotency key to the transaction, so when the server sees the same idempotency key, it knows this transaction has been processed and won't process it again. In this way, the client won't be charged twice.
.
.
.
.

๐Ÿ”น Double Spending in Blockchain Transfers

Double spending is a potential problem where the crypto money is spent twice. The client only has 1 BTC in the wallet, but he can spend it twice to buy two products from different providers.
It is caused by the blockchain consensus mechanism.ย 
.
.
.
๐Ÿ‘‰ Steps 1โ€“2: When 1 BTC is paid to Alice (transaction A), another transaction that pays 1 BTC to Bob can be initiated simultaneously (transaction B). The two transactions go into different unconfirmed transaction pools, waiting to be picked up and confirmed by validators.
.
.
.
๐Ÿ‘‰ Steps 3โ€“4: Validator A picks up transaction A, confirms it, and packages it in Block 2.1. Validator B picks up transaction B, confirms it, and packages it in Block 2.2.ย 
Now the blockchain has a fork. At this point, both transactions are confirmed, causing double-spending.

We need to wait for subsequent blocks to be generated so that we can decide which fork is chosen to be the main blockchain. For example, if Block 3 is appended to Block 2.1 first, then transaction A is still confirmed, but transaction B cannot be executed because the client's wallet doesn't have crypto money after transaction A is confirmed.

Normally we need to wait for 6+ blocks to confirm a transaction for safety.

๐Ÿ‘‰ Over to you: Have you met similar problems in distributed systems?
โ€Š-

Top comments (0)