package io.rudefox.cold; import com.bjdweck.bitcoin.mnemonic.Entropy; import com.bjdweck.math.UnsignedInt; class DiceEventBuffer { private final int diceBase; private final StringBuilder buffer; private final int targetBitsOfEntropy; DiceEventBuffer(int targetBitsOfEntropy, int diceBase) { this.diceBase = diceBase; this.targetBitsOfEntropy = targetBitsOfEntropy; this.buffer = new StringBuilder(getRequiredEvents()); } int getRequiredEvents() { return (int) Math.ceil(this.targetBitsOfEntropy * Math.log(2) / Math.log(diceBase)); } void appendEvents(String eventString) { for (char inChar : eventString.toCharArray()) if (inChar >= '1' && inChar <= '6' && events() < getRequiredEvents()) append((char) (inChar - 1)); } Entropy toEntropy() { UnsignedInt entropy = new UnsignedInt(toString(), diceBase); byte[] entropyBytes = entropy.getLowestOrderBits(this.targetBitsOfEntropy).toBigEndianByteArray(); return Entropy.fromRawEntropy(entropyBytes); } int events() { return buffer.length(); } private void append(char c) { buffer.append(c); } @Override public String toString() { return buffer.toString(); } }