File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ import  java .util .Date ;
2+ 
3+ public  class  Block  {
4+ 
5+ public  String  hash ;
6+ public  String  previousHash ; 
7+ private  String  data ; //our data will be a simple message. 
8+ private  long  timeStamp ; //as number of milliseconds since 1/1/1970. 
9+ private  int  nonce ;
10+ 
11+ //Block Constructor.  
12+ public  Block (String  data ,String  previousHash  ) {
13+ this .data  = data ;
14+ this .previousHash  = previousHash ;
15+ this .timeStamp  = new  Date ().getTime ();
16+ 
17+ this .hash  = calculateHash (); //Making sure we do this after we set the other values. 
18+ }
19+ 
20+ //Calculate new hash based on blocks contents 
21+ public  String  calculateHash () {
22+ String  calculatedhash  = StringUtil .applySha256 ( 
23+ previousHash  +
24+ Long .toString (timeStamp ) +
25+ Integer .toString (nonce ) + 
26+ data  
27+ );
28+ return  calculatedhash ;
29+ }
30+ 
31+ public  void  mineBlock (int  difficulty ) {
32+ String  target  = new  String (new  char [difficulty ]).replace ('\0' , '0' ); //Create a string with difficulty * "0"  
33+ while (!hash .substring ( 0 , difficulty ).equals (target )) {
34+ nonce  ++;
35+ hash  = calculateHash ();
36+ }
37+ System .out .println ("Block Mined!!! : "  + hash );
38+ }
39+ }
Original file line number Diff line number Diff line change 1+ import  java .security .MessageDigest ;
2+ 
3+ public  class  StringUtil  {
4+ //Applies Sha256 to a string and returns the result.  
5+ public  static  String  applySha256 (String  input ){
6+ try  {
7+ MessageDigest  digest  = MessageDigest .getInstance ("SHA-256" ); 
8+ //Applies sha256 to our input,  
9+ byte [] hash  = digest .digest (input .getBytes ("UTF-8" )); 
10+ StringBuffer  hexString  = new  StringBuffer (); // This will contain hash as hexidecimal 
11+ for  (int  i  = 0 ; i  < hash .length ; i ++) {
12+ String  hex  = Integer .toHexString (0xff  & hash [i ]);
13+ if (hex .length () == 1 ) hexString .append ('0' );
14+ hexString .append (hex );
15+ }
16+ return  hexString .toString ();
17+ }
18+ catch (Exception  e ) {
19+ throw  new  RuntimeException (e );
20+ }
21+ }
22+ }
                                 You can’t perform that action at this time. 
               
                  
0 commit comments