본문 바로가기

java

[java] 블록체인 구조 약식 구현

반응형

블록체인은 정보를 가지고 있는 블록을 해시 알고리즘을 통해 해시값으로 변경해 다음 블록이 저장하고 있는 구조입니다.

    static class Block{
        private String prevHash;
        private String data;
        private int nonce;
        private String hash;

        public Block(String prevHash, String data) {
            super();
            this.prevHash = prevHash;
            this.data = data;
        }

        public void genesisHash() {
            hash = encrypt(prevHash + data + nonce);
        }

        public void hash() {
            String tmp = "";
            while (true) {
                tmp = encrypt(prevHash + data + nonce);
                if(tmp.substring(0, 5).equals("00000")) {
                    hash = tmp;
                    break;
                }else {
                    nonce++;
                }
            }
        }

        @Override
        public String toString() {
            return "Block [prevHash=" + prevHash + ", data=" + data + ", nonce=" + nonce + ", hash=" + hash + "]";
        }

        public void print() {
            System.out.println("nonce: " + nonce);
            System.out.println("data: " + data);
            System.out.println("prevHash: " + prevHash);
            System.out.println("hash: " + hash);
        }
    }

최초의 블록을 제외한 블록의 경우는 nonce를 증가시키며 해시값의 시작이 00000일때까지 해시 알고리즘을 반복하도록 했습니다.

    private static Block genesisBlock(String data) {
        Block block = new Block("", data);
        block.genesisHash();
        block.print();

        return block;
    }

    private static Block addBlock(String prevHash, String data) {
        Block block = new Block(prevHash, data);
        block.hash();
        block.print();

        return block;
    }

블록을 생성하는 메소드입니다.

    public static String encrypt(String pwd) {
        StringBuffer hexString = new StringBuffer();

        try {

            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(pwd.getBytes("UTF-8"));

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

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        return hexString.toString();
    }

SHA-256로 해시 처리를 도와주는 메소드입니다.

    public static void main(String[] args) {
        Block genesis = genesisBlock("Genesis Block");
        Block two = addBlock(genesis.hash, "two");
        Block three = addBlock(two.hash, "three");
    }

main 메소드입니다.

nonce: 0
data: Genesis Block
prevHash: 
hash: 8500b59bb5271135cd9bcbf0afd693028d76df3b9c7da58d412b13fc8a8f9394
nonce: 1820724
data: two
prevHash: 8500b59bb5271135cd9bcbf0afd693028d76df3b9c7da58d412b13fc8a8f9394
hash: 00000ebb0cfc489ce0a82c407fd2f7350902161c6bdbb83d2650c76dec69a638
nonce: 2200790
data: three
prevHash: 00000ebb0cfc489ce0a82c407fd2f7350902161c6bdbb83d2650c76dec69a638
hash: 00000211150359847382fe263197a1bce40d6389d09b6fdcad4108921ba10df8

실행결과입니다.

반응형

'java' 카테고리의 다른 글

병렬 처리 - CountDownLatch  (0) 2020.11.16
[JAVA] 숫자로 된 char를 int로 변경하는 방법  (0) 2020.03.24