Java implements a simple bitcoin system

Recently, the blockchain technology has suddenly exploded, and all the technical friends around them talk about blockchain or Bitcoin after dinner. Why is this happening? In fact, this is inseparable from the rapid rise in the price of bitcoin last year. The price of bitcoin has gone from less than 1,000 US dollars at the beginning of last year to as high as nearly 20,000 US dollars at the beginning of this year. The price of bitcoin has risen 20 times in a year, and everyone has enough money bags to try. However, if you ask these technical friends what bitcoin is, how is it constructed, and can you explain bitcoin from a technical point of view, there are really few who can answer it. As a technical background, I Today I will show you how to implement a simple Bitcoin system in Java. After learning, I believe that the above questions can be answered smoothly.

blockchain

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 possible to calculate the balance of any trader, let's construct a block structure first:

/**
 * 区块结构
 * @author aaron
 */
public class Block {
	/**
	 * 区块索引号
	 */
	private int index;
	/**
	 * 当前区块的hash值,区块唯一标识
	 */
	private String hash;
	/**
	 * 生成区块的时间戳
	 */
	private long timestamp;
	/**
	 * 当前区块的交易集合
	 */
	private List<Transaction> transactions;
	/**
	 * 工作量证明,计算正确hash值的次数
	 */
	private int nonce;
	/**
	 * 前一个区块的hash值
	 */
	private String previousHash;

	public Block() {
		super();
	}

	public Block(int index, long timestamp, List<Transaction> transactions, int nonce, String previousHash, String hash) {
		super();
		this.index = index;
		this.timestamp = timestamp;
		this.transactions = transactions;
		this.nonce = nonce;
		this.previousHash = previousHash;
		this.hash = hash;
	}
}

trade

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:

/**
 * 交易
 * @author aaron
 */
public class Transaction {
	/**
	 * 交易唯一标识
	 */
	private String id;
	/**
	 * 交易发送方钱包地址
	 */
	private String sender;
	/**
	 * 交易接收方钱包地址
	 */
	private String recipient;
	/**
	 * 交易金额
	 */
	private int amount;

	public Transaction() {
		super();
	}

	public Transaction(String id, String sender, String recipient, int amount) {
		super();
		this.id = id;
		this.sender = sender;
		this.recipient = recipient;
		this.amount = 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 this formula:

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 a little simpler. For example, as long as the hash result starts with 4 0s , we think that the problem is solved successfully, that is, the mining is successful. At this time The miner can generate a new block to record all the transaction records that need to be recorded into the block, and then construct a transaction that the system rewards to his own bitcoin (the initiator is the system, the receiver is the miner, the bitcoin The amount of coins is assumed to be 10), and it is also recorded in the ledger, so that through the transaction records in the ledger, it will be found 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<Block> blockchain, List<Transaction> txs, String address) {
	//加入系统奖励的交易,默认挖矿奖励10个比特币
	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 from the changed address, and the real address of the address is obtained by subtracting the sum of the received bitcoin amounts from the sum of the sent bitcoin amounts. The bitcoin balance of , let's look at the code:

/**
 * 查询余额
 * @param blockchain
 * @param address
 * @return
 */
public static int getWalletBalance(List<Block> blockchain, String address) {
	int balance = 0;
	for (Block block : blockchain) {
        	List<Transaction> transactions = block.getTransactions();
        	for (Transaction transaction : transactions) {
            		if (address.equals(transaction.getRecipient())) {
            			balance += transaction.getAmount();
            		}
            		if (address.equals(transaction.getSender())) {
            			balance -= transaction.getAmount();
            		}
        	}
   	 }
	return balance;
}

System entry

Finally, let's take a look at the operation effect of this small bitcoin system. The main function code is as follows:

public static void main(String[] args) {
	//创建一个空的区块链
	List<Block> blockchain = new ArrayList<>();
	//生成创世区块
	Block block = new Block(1, System.currentTimeMillis(), new ArrayList<Transaction>(), 1, "1", "1");
	//加入创世区块到区块链里
	blockchain.add(block);
	System.out.println(JSON.toJSONString(blockchain));
	
	// 发送方钱包地址
	String sender = "sender_wallet";
	//接收方钱包地址
	String recipient = "recipient_wallet";
	
	//创建一个空的交易集合
	List<Transaction> txs = new ArrayList<>();
	//挖矿
	mineBlock(blockchain, txs, sender);
	System.out.println(sender + "钱包的余额为:" + getWalletBalance(blockchain, sender));
	
	//创建一个空的交易集合
	List<Transaction> txs1 = new ArrayList<>();
	//已发生但未记账的交易记录,发送者给接收者转账3个比特币
	Transaction tx1 = new Transaction(CryptoUtil.UUID(), sender, recipient, 3);
	//已发生但未记账的交易记录,发送者给接收者转账1个比特币
	Transaction tx2 = new Transaction(CryptoUtil.UUID(), sender, recipient, 1);
	txs1.add(tx1);
	txs1.add(tx2);
	//挖矿
	mineBlock(blockchain, txs1, sender);
	System.out.println(sender + "钱包的余额为:" + getWalletBalance(blockchain, sender));
	System.out.println(recipient + "钱包的余额为:" + getWalletBalance(blockchain, recipient));
}

The running result is shown in the following figure:

So far, we have implemented a simple bitcoin system based on blockchain ledger technology in java language, including blockchain function, mining to generate new bitcoin function, transfer transaction function, balance query function, the complete code can follow WeChat The public account " Light Wind Micro Course " replies to ' Bitcoin ' to get

Of course, the real Bitcoin system is far more than that simple. For example, students use passwords to create Bitcoin wallets and ensure that transaction information is not tampered with, and use P2P communication technology to achieve peer-to-peer distributed network functions. Friends can continue to pay attention to the WeChat public account " Light Wind Micro Class "

Guess you like

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