view src/main/java/christie/blockchain/Miner.java @ 198:dd3c0ba6a0a6

fix topology manager
author akahori
date Sat, 09 Mar 2019 21:53:37 +0900
parents cd2fab84cd8b
children
line wrap: on
line source

package christie.blockchain;

import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.BigIntegers;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.charset.Charset;


public class Miner {

    public void mineBlock(Block newBlock, int difficulty) {
        long nonce = 0;


        //byte[] target = new String(new char[difficulty]).replace('\0', '0').getBytes();
        String target = new String(new char[difficulty]).replace('\0', '0');
        byte[] hash = newBlock.getByteArrayWithoutNonce();

        String hashStr = new String(HashUtil.sha256(hash), Charset.forName("utf-8"));


        while(!hashStr.substring( 0, difficulty).equals(target)) {
            nonce ++;
            byte[] concat = Arrays.concatenate(hash, BigInteger.valueOf(nonce).toByteArray());
            hashStr = new String(HashUtil.sha256(concat), Charset.forName("utf-8"));
        }
        newBlock.setNonce(nonce);

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

    }

    public boolean increment(byte[] bytes) {
        final int startIndex = 0;
        int i;
        for (i = bytes.length - 1; i >= startIndex; i--) {
            bytes[i]++;
            if (bytes[i] != 0)
                break;
        }

        return (i >= startIndex || bytes[startIndex] != 0);
    }

    public int compareTo(byte[] buffer1, int offset1, int length1,
                         byte[] buffer2, int offset2, int length2) {
        // Short circuit equal case
        if (buffer1 == buffer2 &&
                offset1 == offset2 &&
                length1 == length2) {
            return 0;
        }
        int end1 = offset1 + length1;
        int end2 = offset2 + length2;
        for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {
            int a = (buffer1[i] & 0xff);
            int b = (buffer2[j] & 0xff);
            if (a != b) {
                return a - b;
            }
        }
        return length1 - length2;
    }
}