java實現(xiàn)區(qū)塊鏈

區(qū)塊鏈?zhǔn)怯梢粋€個的區(qū)塊構(gòu)成,區(qū)塊主要包含前一個區(qū)塊的hash值庇谆,加密的數(shù)據(jù)data,當(dāng)前區(qū)塊的hash值凭疮。

package noobchain;

import java.util.Date;

public class Block {

public Stringhash;

public StringpreviousHash;

private Stringdata;//our data will be a simple message.

? private long timeStamp;//as number of milliseconds since 1/1/1970.

? private int nonce;

//Block Constructor.

? public Block(String data,String previousHash ) {

this.data = data;

this.previousHash = previousHash;

this.timeStamp =new Date().getTime();

this.hash = calculateHash();//Making sure we do this after we set the other values.

? }

//Calculate new hash based on blocks contents

? public String calculateHash() {

String calculatedhash = StringUtil.applySha256(

previousHash +

Long.toString(timeStamp) +

Integer.toString(nonce) +

data

? ? ? ? ? ? );

return calculatedhash;

}

//Increases nonce value until hash target is reached.

? public void mineBlock(int difficulty) {

String target = StringUtil.getDificultyString(difficulty);//Create a string with difficulty * "0"

? ? ? while(!hash.substring(0, difficulty).equals(target)) {

nonce ++;

hash = calculateHash();

}

System.out.println("Block Mined!!! : " +hash);

}

}


package noobchain;

import java.util.ArrayList;

public class NoobChain {

public static ArrayListblockchain =new ArrayList();

public static int difficulty =5;

public static void main(String[] args) {

//add our blocks to the blockchain ArrayList:

? ? ? System.out.println("Trying to Mine block 1... ");

addBlock(new Block("Hi im the first block","0"));

System.out.println("Trying to Mine block 2... ");

addBlock(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));

System.out.println("Trying to Mine block 3... ");

addBlock(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));

System.out.println("\nBlockchain is Valid: " +isChainValid());

String blockchainJson = StringUtil.getJson(blockchain);

System.out.println("\nThe block chain: ");

System.out.println(blockchainJson);

}

public static Boolean isChainValid() {

Block currentBlock;

Block previousBlock;

String hashTarget =new String(new char[difficulty]).replace('\0','0');

//loop through blockchain to check hashes:

? ? ? for(int i=1; i

currentBlock =blockchain.get(i);

previousBlock =blockchain.get(i-1);

//compare registered hash and calculated hash:

? ? ? ? if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){

System.out.println("Current Hashes not equal");

return false;

}

//compare previous hash and registered previous hash

? ? ? ? if(!previousBlock.hash.equals(currentBlock.previousHash) ) {

System.out.println("Previous Hashes not equal");

return false;

}

//check if hash is solved

? ? ? ? if(!currentBlock.hash.substring(0,difficulty).equals(hashTarget)) {

System.out.println("This block hasn't been mined");

return false;

}

}

return true;

}

public static void addBlock(Block newBlock) {

newBlock.mineBlock(difficulty);

blockchain.add(newBlock);

}

}


package noobchain;

import java.security.MessageDigest;

import com.google.gson.GsonBuilder;

public class StringUtil {

//Applies Sha256 to a string and returns the result.

? public static String applySha256(Stringinput){

try {

MessageDigest digest = MessageDigest.getInstance("SHA-256");

//Applies sha256 to our input,

? ? ? ? byte[] hash = digest.digest(input.getBytes("UTF-8"));

StringBuffer hexString =new StringBuffer();// This will contain hash as hexidecimal

? ? ? ? for (int i =0; i < hash.length; i++) {

String hex = Integer.toHexString(0xff & hash[i]);

if(hex.length() ==1) hexString.append('0');

hexString.append(hex);

}

return hexString.toString();

}

catch(Exception e) {

throw new RuntimeException(e);

}

}

//Short hand helper to turn Object into a json string

? public static String getJson(Object o) {

return new GsonBuilder().setPrettyPrinting().create().toJson(o);

}

//Returns difficulty string target, to compare to hash. eg difficulty of 5 will return "00000"

? public static String getDificultyString(int difficulty) {

return new String(new char[difficulty]).replace('\0','0');

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末饭耳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子执解,更是在濱河造成了極大的恐慌寞肖,老刑警劉巖纲酗,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異新蟆,居然都是意外死亡觅赊,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門琼稻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吮螺,“玉大人,你說我怎么就攤上這事帕翻○梗” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵嘀掸,是天一觀的道長紫岩。 經(jīng)常有香客問我,道長睬塌,這世上最難降的妖魔是什么泉蝌? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮揩晴,結(jié)果婚禮上勋陪,老公的妹妹穿的比我還像新娘。我一直安慰自己文狱,他們只是感情好粥鞋,可當(dāng)我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瞄崇,像睡著了一般呻粹。 火紅的嫁衣襯著肌膚如雪苏研。 梳的紋絲不亂的頭發(fā)上摹蘑,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天撒踪,我揣著相機與錄音制妄,去河邊找鬼耕捞。 笑死俺抽,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的振愿。 我是一名探鬼主播埃疫,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼胳蛮!你這毒婦竟也來了丛晌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤抚垄,失蹤者是張志新(化名)和其女友劉穎谋逻,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體浙滤,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年梅桩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片煮寡。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖坐儿,靈堂內(nèi)的尸體忽然破棺而出貌矿,到底是詐尸還是另有隱情罪佳,我是刑警寧澤赘艳,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布枷踏,位于F島的核電站旭蠕,受9級特大地震影響掏熬,放射性物質(zhì)發(fā)生泄漏孽江。R本人自食惡果不足惜岗屏,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望暇屋。 院中可真熱鬧咐刨,春花似錦定鸟、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽子刮。三九已至话告,卻和暖如春沙郭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背送挑。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工惕耕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像诈乒,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 區(qū)塊鏈?zhǔn)欠植际綌?shù)據(jù)存儲腐芍、點對點傳輸、共識機制泣刹、加密算法等計算機技術(shù)的新型應(yīng)用模式。所謂共識機制是區(qū)塊鏈系統(tǒng)中實現(xiàn)不...
    dtdh閱讀 552評論 0 0
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法员舵,類相關(guān)的語法马僻,內(nèi)部類的語法注服,繼承相關(guān)的語法韭邓,異常的語法,線程的語...
    子非魚_t_閱讀 31,625評論 18 399
  • 第一頁祠汇。 簡單難度仍秤。 復(fù)習(xí)著熟悉的旋律很開心地翻過去了?? 第二頁。 依然簡單可很。 第三頁诗力。 臥槽槽槽為什么這里有個休...
    c0d843f4cb28閱讀 223評論 0 0
  • 是否命里總會遇到一些動蕩和挑戰(zhàn),多次經(jīng)歷調(diào)整,再次遇見依然覺得惆悵苇本,那些一路順風(fēng)袜茧、安穩(wěn)康順的生活似乎重來都不...
    217cbd3a3d3a閱讀 236評論 0 0
  • 最近剛剛畢業(yè)笛厦,在洛陽找了個賣房子的工作,本來在大學(xué)學(xué)的是土木工程俺夕,但是實在對這一行提不起興趣裳凸,于是來到洛陽做置業(yè)顧...
    御前帶茶侍衛(wèi)閱讀 2,810評論 0 0