Demo:第一章:Java实现比特币系统

public void setIndex(int index) {

this.index = index;

}

public long getTimestamp() {

return timestamp;

}

public void setTimestamp(long timestamp) {

this.timestamp = timestamp;

}

public List getTransactions() {

return transactions;

}

public void setTransactions(List transactions) {

this.transactions = transactions;

}

public int getNonce() {

return nonce;

}

public void setNonce(int nonce) {

this.nonce = nonce;

}

public String getPreviousHash() {

return previousHash;

}

public void setPreviousHash(String previousHash) {

this.previousHash = previousHash;

}

public String getHash() {

return hash;

}

public void setHash(String hash) {

this.hash = hash;

}

/**

  • 挖矿

  • @param blockchain 整个区块链

  • @param txs 需记账交易记录

  • @param address 矿工钱包地址

  • @return

*/

public 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));

}

}

Transaction

packag

  • 19
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值