It with currency prices last year by leaps and bounds is inseparable, the currency price from less than $one thousand early last year to a high of nearly $twenty thousand earlier this year, the money is enough to win everybody eyeball, eat the melon masses 20 times a year on the currency prices already eyes stare dog stay, each note, itch to try.

The wise men, however, these friends what on earth is the currency, it is how to construct, return true not a few will have to answer, as a technical background we will come and take you today in the Java language to realize a simple currency system, in order to let everybody to block chain and the currency of the underlying implementation technology have a cognition of the entry. (Java Training of Shanghai Shang School)

First, blockchain

Bitcoin is a cryptocurrency built on blockchain technology. Blockchain, as its name implies, is a chain composed of many blocks. The blockchain can be simply likened to a ledger, and the block can be likened to a page of the ledger. So based on all the transactions in this ledger it should be possible to calculate the balance of any trader, so let’s first construct a block structure

public class Block {
/** * Block index number */
private int index;
/** * The hash value of the current block, which uniquely identifies the block */
private String hash;
/** * Generates a block timestamp */
private long timestamp;
/** * The set of transactions in the current block */
private List transactions;
/** * The number of times to compute the correct hash value */private int nonce;
/** * The hash value of the previous block */
private String previousHash;
}Copy the code


2. Transfer transactions

Transfer transactions that COINS have mutual transfer behavior between, we take these COINS have temporarily assuming purse for COINS, wallet have corresponding wallet address, that such transfer transaction is actually transfer between wallet address (similar to pay treasure to transfer between the user and is actually pay treasure to transfer between user name), These transfers need to be recorded in the books for them to be valid.

Due to the complex design of bitcoin transfer transaction, we will not discuss it in depth today, so I have designed a simple transaction model as follows:

Copy the code

Public class Transaction {/** * Transaction id */ private String ID; /** * private String sender; /** * private String Recipient; /** * private int amount; }Copy the code

Third, dig



What the hell is mining all about?

Why are so many people clamoring to dig mines, dreaming of getting rich overnight?

We can simply compared to dig into the process of solving a mathematical problem, as long as the solution to the reward can obtain the currency system of a currency, and obtain the chain new books the block trading account rights, mean the currency system of recent transfer transaction records to a new page in the book, and get the transaction fees, once the transaction is recorded into the book, Once the transaction is completed, the recipient can actually receive the bitcoin transferred by the sender.

So what does this math puzzle actually look like?

Let’s look at the formula for this math puzzle:

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

This formula is very understand, SHA – 256 is a hash encryption algorithm, be encrypted in the first two parts is fixed, we only relies on the changing of the random number to calculate different hash as a result, the system requires the hash result must begin with 10 0, the chance is so small is too small, we do the test can be a little bit more simple.

Such as: As long as the hash results meet with 4 0 at the beginning, we thought the problem solving success, namely mining is successful, then the miners can generate a new block all the transaction records in need to charge to an account record into the block, and to construct a system of rewards to their currency trading (sponsors for the system, the receiver for the miners, assuming that the currency amount to 10). Add it to the ledger, so that when you look at the transactions in the ledger, you’ll see that the miner’s balance is 10 bitcoins too high.

Let’s look at the mining code:

/** * mining *@paramBlockchain the entire blockchain *@paramTXS requires accounting transaction records, including *@paramAddress Miner's wallet *@return* /
private static void mineBlock(List blockchain, List txs, String address) {
// Add rewards to the system
Transaction sysTx = new Transaction(CryptoUtil.UUID(), "", address, 10);
txs.add(sysTx);
// Get the last block in the current blockchain
Block latestBlock = blockchain.get(blockchain.size() - 1);
/ / random number
int nonce = 1;
String hash = "";
while(true){
hash = CryptoUtil.SHA256(latestBlock.getHash() + JSON.toJSONString(txs) + nonce);
if (hash.startsWith("0000")) {
System.out.println("===== is correct and the calculation times are:" +nonce+ ",hash:" + hash);
break;
}
nonce++;
System.out.println("Calculation error, hash:" + hash);
}
// New blocks can be constructed and added to the blockchain by solving puzzles
Block newBlock = new Block(latestBlock.getIndex() + 1, System.currentTimeMillis(), txs, nonce, latestBlock.getHash(), hash);
blockchain.add(newBlock);
System.out.println("Blockchain after mining:" + JSON.toJSONString(blockchain));
}Copy the code


Fourth, the balance

Calculate the balance of a wallet address is actually from the chain block books to find out all the address as the recipient’s trading records, the transaction records the amount accumulative get the address to receive all the currency amount, and then find out all the address as the sender’s trading records accumulation was the address again to send out all the currency amount, Subtract the total amount of bitcoin sent from the sum received to get the actual bitcoin balance at the address.

Let’s look at the code: Shanghai Java training

Copy 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; }

At this point, we use Java based on blockchain ledger technology to achieve a simple bitcoin system, including blockchain function, mining to generate new bitcoin function, transfer transaction function, balance query function, complete code to find a small assistant.

The running results are as follows:



Thanks for reading, thanks for the help of Shanghai Java Training, welcome to leave a comment