溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么用java實(shí)現(xiàn)簡(jiǎn)單比特幣功能

發(fā)布時(shí)間:2021-08-12 13:59:12 來(lái)源:億速云 閱讀:295 作者:chen 欄目:互聯(lián)網(wǎng)科技

這篇文章主要講解了“怎么用java實(shí)現(xiàn)簡(jiǎn)單比特幣功能”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“怎么用java實(shí)現(xiàn)簡(jiǎn)單比特幣功能”吧!

一、塊定義

/**
 * 區(qū)塊結(jié)構(gòu)
 * @author 
 */
public class Block {
    /**
     * 區(qū)塊索引號(hào)
     */
    private int index;
    /**
     * 當(dāng)前區(qū)塊的hash值,區(qū)塊唯一標(biāo)識(shí)
     */
    private String hash;
    /**
     * 生成區(qū)塊的時(shí)間戳
     */
    private long timestamp;
    /**
     * 當(dāng)前區(qū)塊的交易集合
     */
    private List<Transaction> transactions;
    /**
     * 工作量證明,計(jì)算正確hash值的次數(shù)
     */
    private int nonce;
    /**
     * 前一個(gè)區(qū)塊的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;
    }
}

二、交易定義

/**
 * 交易
 * @author 
 */
public class Transaction {
    /**
     * 交易唯一標(biāo)識(shí)
     */
    private String id;
    /**
     * 交易發(fā)送方錢包地址
     */
    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;
    }
}

三、挖礦方法

/**
 * 挖礦
 * @param blockchain 整個(gè)區(qū)塊鏈
 * @param txs 需記賬交易記錄
 * @param address 礦工錢包地址
 * @return
 */
private static void mineBlock(List<Block> blockchain, List<Transaction> txs, String address) {
    //加入系統(tǒng)獎(jiǎng)勵(lì)的交易,默認(rèn)挖礦獎(jiǎng)勵(lì)10個(gè)比特幣
    Transaction sysTx = new Transaction(CryptoUtil.UUID(), "", address, 10);
    txs.add(sysTx);
    //獲取當(dāng)前區(qū)塊鏈里的最后一個(gè)區(qū)塊
        Block latestBlock = blockchain.get(blockchain.size() - 1);
    //隨機(jī)數(shù)
    int nonce = 1;
    String hash = "";
    while(true){
        hash = CryptoUtil.SHA256(latestBlock.getHash() + JSON.toJSONString(txs) + nonce);
        if (hash.startsWith("0000000000")) {
            System.out.println("=====計(jì)算結(jié)果正確,計(jì)算次數(shù)為:" +nonce+ ",hash:" + hash);
            break;
        }
        nonce++;
        System.out.println("計(jì)算錯(cuò)誤,hash:" + hash); 
    }
    
    //解出難題,可以構(gòu)造新區(qū)塊并加入進(jìn)區(qū)塊鏈里
    Block newBlock = new Block(latestBlock.getIndex() + 1, System.currentTimeMillis(), txs, nonce, latestBlock.getHash(), hash);
    blockchain.add(newBlock);
    System.out.println("挖礦后的區(qū)塊鏈:" + JSON.toJSONString(blockchain));
}

四、余額計(jì)算
/**
 * 查詢余額
 * @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;
 

五、運(yùn)行范例

public static void main(String[] args) {
    //創(chuàng)建一個(gè)空的區(qū)塊鏈
    List<Block> blockchain = new ArrayList<>();
    //生成創(chuàng)世區(qū)塊
    Block block = new Block(1, System.currentTimeMillis(), new ArrayList<Transaction>(), 1, "1", "1");
    //加入創(chuàng)世區(qū)塊到區(qū)塊鏈里
    blockchain.add(block);
    System.out.println(JSON.toJSONString(blockchain));
    
    // 發(fā)送方錢包地址
    String sender = "sender_wallet";
    //接收方錢包地址
    String recipient = "recipient_wallet";
    
    //創(chuàng)建一個(gè)空的交易集合
    List<Transaction> txs = new ArrayList<>();
    //挖礦
    mineBlock(blockchain, txs, sender);
    System.out.println(sender + "錢包的余額為:" + getWalletBalance(blockchain, sender));
    
    //創(chuàng)建一個(gè)空的交易集合
    List<Transaction> txs1 = new ArrayList<>();
    //已發(fā)生但未記賬的交易記錄,發(fā)送者給接收者轉(zhuǎn)賬3個(gè)比特幣
    Transaction tx1 = new Transaction(CryptoUtil.UUID(), sender, recipient, 3);
    //已發(fā)生但未記賬的交易記錄,發(fā)送者給接收者轉(zhuǎn)賬1個(gè)比特幣
    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));
}

感謝各位的閱讀,以上就是“怎么用java實(shí)現(xiàn)簡(jiǎn)單比特幣功能”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)怎么用java實(shí)現(xiàn)簡(jiǎn)單比特幣功能這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI