Build a Simple Java Blockchain: Mining, Transactions, and Balance Queries
This tutorial walks through creating a basic Java blockchain that includes block structures, transaction modeling, a proof‑of‑work mining process with configurable difficulty, and functions to compute wallet balances, providing complete source code and explanatory diagrams.
To help readers grasp blockchain fundamentals, this article presents a step‑by‑step Java implementation of a simple blockchain system that supports block creation, mining new bitcoins, recording transactions, and querying wallet balances.
Block Structure
The Block class defines the essential fields of a blockchain block: an index, the block’s hash, a timestamp, a list of transactions, a nonce for proof‑of‑work, and the hash of the previous block.
public class Block {
/** 区块索引号 */
private int index;
/** 当前区块的hash值,区块唯一标识 */
private String hash;
/** 生成区块的时间戳 */
private long timestamp;
/** 当前区块的交易集合 */
private List transactions;
/** 工作量证明,计算正确hash值的次数 */
private int nonce;
/** 前一个区块的hash值 */
private String previousHash;
}Transaction Model
A simplified transaction model treats Bitcoin owners as wallets identified by addresses. Each Transaction records a unique ID, sender address, recipient address, and amount.
public class Transaction {
/** 交易唯一标识 */
private String id;
/** 交易发送方钱包地址 */
private String sender;
/** 交易接收方钱包地址 */
private String recipient;
/** 交易金额 */
private int amount;
}Mining Process
Mining is modeled as a miner solving a hash puzzle: Hash = SHA‑256(lastBlockHash + transactionData + nonce). The hash must start with a configurable number of zeros (e.g., four zeros) to be accepted. When a solution is found, the miner receives a reward transaction (10 bitcoins) and the new block is appended to the chain.
/**
* 挖矿
* @param blockchain 整个区块链
* @param txs 需记账交易记录,包含
* @param address 矿工钱包地址
*/
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 Query
To compute a wallet’s balance, the program scans all blocks, sums amounts where the address appears as a recipient, and subtracts amounts where it appears as a sender.
/**
* 查询余额
*/
public static int getWalletBalance(List blockchain, String address) {
int balance = 0;
for (Block block : blockchain) {
List 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;
}Result Illustration
The following diagram shows the blockchain structure, and the screenshot below displays a sample run output after mining, performing a transaction, and querying a balance.
While this implementation captures the core ideas of Bitcoin—block linking, proof‑of‑work mining, transaction recording, and balance calculation—real‑world systems add cryptographic signatures, peer‑to‑peer networking, and many other security and scalability features.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
