Implementing a Simple Bitcoin System in Java

Java blockchain development and communication group: 613121183

If you are interested, you can also add it. We have provided a lot of blockchain data, and we can meet and share the data in the future.

------------------------------------------------------------------------


In order to give you a better understanding of the underlying principles of blockchain, today I will show you how to implement a simple blockchain program in Java, including blockchain functions, mining to generate new bitcoins, transfer and transaction functions, and query balance function.

blockchain

Blockchain diagram


Bitcoin is an encrypted digital currency built on the blockchain technology. The blockchain, as its name suggests, is a chain composed of many blocks. The blockchain can be simply compared to a ledger, and a block to a ledger. Page records, each page of the ledger records a lot of bitcoin transfer transactions, so according to all the transaction records in this ledger, it should be able to calculate the balance of any trader, let's first construct a block structure

public class Block {
       /**
       * 区块索引号
       */

       private int index;
       /**
       * 当前区块的hash值,区块唯一标识
       */

       private String hash;
       /**
       * 生成区块的时间戳
       */

       private long timestamp;
       /**
       * 当前区块的交易集合
       */

       private List transactions;
       /**
       * 工作量证明,计算正确hash值的次数
       */

       /**
       * 前一个区块的hash值
       */

       private String previousHash;
}

transfer transaction

The transfer transaction is the mutual transfer between the owners of bitcoin. We temporarily assume that the owners of these bitcoins are bitcoin wallets, and the wallets have corresponding wallet addresses. Then these transfer transactions are actually between wallet addresses. (similar to the transfer between Alipay users, which is actually the transfer between Alipay user names), these transfer transactions need to be recorded in the ledger to be truly effective.

Since the design of Bitcoin's transfer transaction is relatively complex, we will not discuss it in depth today, so here I have designed a simple transaction model as follows:

public class Transaction {
      /**
      * 交易唯一标识
      */

      private String id;
      /**
      * 交易发送方钱包地址
      */

      private String sender;
      /**
      * 交易接收方钱包地址
      */

      private String recipient;
      /**
      * 交易金额
      */

      private int amount;
}

mining

What the hell is going on with mining?

Why are so many people clamoring to go mining and dreaming of getting rich overnight?

We can simply compare mining to the process of miners solving a mathematical problem. As long as the solution is correct, they can obtain a Bitcoin rewarded by the Bitcoin system, and at the same time obtain the transaction accounting right of the new block of the blockchain ledger. The trade union records the recent transfer transactions in the Bitcoin system on a new page of the ledger, and obtains the transaction fee. Once the transaction is recorded in the ledger, the transaction is completed, and the receiver can truly receive the bits transferred by the sender. currency.

So what does this math problem look like?

Let's look at the formula for this mathematical puzzle:

Hash = SHA-256 (Hash of the last block of the blockchain + transaction record information to be billed + random number)

This formula is very clear. SHA-256 is a hash encryption algorithm. The first two parts to be encrypted are fixed. We only rely on the constant change of random numbers to calculate different hash results. The system requires hash results. It must start with 10 0s. This probability is too small and too small. We can make the test easier.

For example: as long as the hash result starts with 4 0s, we consider that the problem is solved successfully, that is, the mining is successful. At this time, the miner can generate a new block and record all the transaction records that need to be recorded into the block. , and then construct a bitcoin transaction that the system rewards to itself (the initiator is the system, the receiver is the miner, and the bitcoin amount is assumed to be 10), and it is also recorded in the ledger, so that the transaction records in the ledger will be You will find that the miner's balance has increased by 10 bitcoins.

Let's look at the mining code:

/**
* 挖矿
* @param blockchain 整个区块链
* @param txs 需记账交易记录,包含
* @param address 矿工钱包地址
* @return
*/

private static void mineBlock(List blockchain, List txs, String address) {
   //加入系统奖励的交易
   Transaction sysTx = new Transaction(CryptoUtil.UUID(), "", address, 10);
   txs.add(sysTx);
   //获取当前区块链里的最后一个区块
   Block latestBlock = blockchain.get(blockchain.size() - 1);
   //随机数
   int nonce = 1;
   String hash = "";
   while(true){
       hash = CryptoUtil.SHA256(latestBlock.getHash() + JSON.toJSONString(txs) + nonce);
       if (hash.startsWith("0000")) {
           System.out.println("=====计算结果正确,计算次数为:" +nonce+ ",hash:" + hash);
           break;
       }
       nonce++;
       System.out.println("计算错误,hash:" + hash);
   }
   //解出难题,可以构造新区块并加入进区块链里
   Block newBlock = new Block(latestBlock.getIndex() + 1, System.currentTimeMillis(), txs, nonce, latestBlock.getHash(), hash);
   blockchain.add(newBlock);
   System.out.println("挖矿后的区块链:" + JSON.toJSONString(blockchain));
}

balance

Calculating the balance of a wallet address is actually to find out all the transaction records of the address as the recipient from the blockchain ledger, and add up the amount of these transaction records to get all the bitcoin amount received by the address, and then find All the transaction records of the address as the sender are accumulated again to get all the bitcoin amounts sent by the address. Subtract the sum of the received bitcoin amounts from the sum of the sent bitcoin amounts to get the real address of the address. Bitcoin balance.

Specifically, let's look at the code:

/**
* 查询余额
* @param blockchain
* @param address
* @return
*/

public static int getWalletBalance(Listblockchain, String address) {
   int balance = 0;
   for (Block block : blockchain) {
       Listtransactions = block.getTransactions();
       for (Transaction transaction : transactions) {
           if (address.equals(transaction.getRecipient())) {
               balance += transaction.getAmount();
           }
           if (address.equals(transaction.getSender())) {
               balance -= transaction.getAmount();
           }
       }
   }
   return balance;
}

So far, we have used java to implement a simple bitcoin system based on blockchain ledger technology, including blockchain functions, mining to generate new bitcoin functions, transfer transaction functions, balance query functions, and complete code to find a small assistant receive.

The running result is shown in the following figure:

Of course, the real Bitcoin system is far more than that simple. For example, it combines cryptography to ensure that transfer transactions are not tampered with, and combines P2P technology to achieve peer-to-peer distributed network functions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324429718&siteId=291194637