package hsr.dsa.blockchain;

import java.math.BigInteger;

import org.ethereum.crypto.ECKey;
import org.spongycastle.util.encoders.Hex;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Sign;

public abstract class BlockChainUtils {
	/**
	 *
	 * @param privateKey Private key, in the format:
	 *                   ea8f71fc4690e0733f3478c3d8e53790988b9e51deabd10185364bc59c58fdba
	 * @return
	 */
	public static Credentials fromECPrivateKey(String privateKey) {
		return fromECKey(ECKey.fromPrivate(Hex.decode(privateKey)));
	}

	public static Credentials fromECKey(ECKey ecKey) {
		BigInteger privKey = ecKey.getPrivKey();
		ECKeyPair pair = new ECKeyPair(privKey, Sign.publicKeyFromPrivate(privKey));
		return Credentials.create(pair);
	}

	private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

	public static String bytesToHex(byte[] bytes) {
		char[] hexChars = new char[bytes.length * 2];
		for (int j = 0; j < bytes.length; j++) {
			int v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new String(hexChars);
	}
}
