<commit_before>/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

package bisq.common.crypto;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Longs;

import java.nio.charset.StandardCharsets;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;

import lombok.extern.slf4j.Slf4j;

/**
 * HashCash implementation for proof of work
 * It doubles required work by difficulty increase (adding one leading zero).
 *
 * See https://www.hashcash.org/papers/hashcash.pdf
 */
@Slf4j
public class HashCashService {
    // Default validations. Custom implementations might use tolerance.
    private static final BiFunction<byte[], byte[], Boolean> isChallengeValid = Arrays::equals;
    private static final BiFunction<Integer, Integer, Boolean> isDifficultyValid = Integer::equals;

    public static CompletableFuture<ProofOfWork> mint(byte[] payload,
                                                      byte[] challenge,
                                                      int difficulty) {
        return HashCashService.mint(payload,
                challenge,
                difficulty,
                HashCashService::testDifficulty);
    }

    public static boolean verify(ProofOfWork proofOfWork) {
        return verify(proofOfWork,
                proofOfWork.getChallenge(),
                proofOfWork.getNumLeadingZeros());
    }

    public static boolean verify(ProofOfWork proofOfWork,
                                 byte[] controlChallenge,
                                 int controlDifficulty) {
        return HashCashService.verify(proofOfWork,
                controlChallenge,
                controlDifficulty,
                HashCashService::testDifficulty);
    }

    public static boolean verify(ProofOfWork proofOfWork,
                                 byte[] controlChallenge,
                                 int controlDifficulty,
                                 BiFunction<byte[], byte[], Boolean> challengeValidation,
                                 BiFunction<Integer, Integer, Boolean> difficultyValidation) {
        return HashCashService.verify(proofOfWork,
                controlChallenge,
                controlDifficulty,
                challengeValidation,
                difficultyValidation,
                HashCashService::testDifficulty);
    }

    private static boolean testDifficulty(byte[] result, long difficulty) {
        return HashCashService.numberOfLeadingZeros(result) > difficulty;
    }


    ///////////////////////////////////////////////////////////////////////////////////////////
    // Generic
    ///////////////////////////////////////////////////////////////////////////////////////////

    static CompletableFuture<ProofOfWork> mint(byte[] payload,
                                               byte[] challenge,
                                               int difficulty,
                                               BiFunction<byte[], Integer, Boolean> testDifficulty) {
        return CompletableFuture.supplyAsync(() -> {
            long ts = System.currentTimeMillis();
            byte[] result;
            long counter = 0;
            do {
                result = toSha256Hash(payload, challenge, ++counter);
            }
            while (!testDifficulty.apply(result, difficulty));
            ProofOfWork proofOfWork = new ProofOfWork(payload, counter, challenge, difficulty, System.currentTimeMillis() - ts);
            // log.info("Completed minting proofOfWork: {}", proofOfWork);
            return proofOfWork;
        });
    }<commit_msg>Add log<commit_after>/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

package bisq.common.crypto;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Longs;

import java.nio.charset.StandardCharsets;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;

import lombok.extern.slf4j.Slf4j;

/**
 * HashCash implementation for proof of work
 * It doubles required work by difficulty increase (adding one leading zero).
 *
 * See https://www.hashcash.org/papers/hashcash.pdf
 */
@Slf4j
public class HashCashService {
    // Default validations. Custom implementations might use tolerance.
    private static final BiFunction<byte[], byte[], Boolean> isChallengeValid = Arrays::equals;
    private static final BiFunction<Integer, Integer, Boolean> isDifficultyValid = Integer::equals;

    public static CompletableFuture<ProofOfWork> mint(byte[] payload,
                                                      byte[] challenge,
                                                      int difficulty) {
        return HashCashService.mint(payload,
                challenge,
                difficulty,
                HashCashService::testDifficulty);
    }

    public static boolean verify(ProofOfWork proofOfWork) {
        return verify(proofOfWork,
                proofOfWork.getChallenge(),
                proofOfWork.getNumLeadingZeros());
    }

    public static boolean verify(ProofOfWork proofOfWork,
                                 byte[] controlChallenge,
                                 int controlDifficulty) {
        return HashCashService.verify(proofOfWork,
                controlChallenge,
                controlDifficulty,
                HashCashService::testDifficulty);
    }

    public static boolean verify(ProofOfWork proofOfWork,
                                 byte[] controlChallenge,
                                 int controlDifficulty,
                                 BiFunction<byte[], byte[], Boolean> challengeValidation,
                                 BiFunction<Integer, Integer, Boolean> difficultyValidation) {
        return HashCashService.verify(proofOfWork,
                controlChallenge,
                controlDifficulty,
                challengeValidation,
                difficultyValidation,
                HashCashService::testDifficulty);
    }

    private static boolean testDifficulty(byte[] result, long difficulty) {
        return HashCashService.numberOfLeadingZeros(result) > difficulty;
    }


    ///////////////////////////////////////////////////////////////////////////////////////////
    // Generic
    ///////////////////////////////////////////////////////////////////////////////////////////

    static CompletableFuture<ProofOfWork> mint(byte[] payload,
                                               byte[] challenge,
                                               int difficulty,
                                               BiFunction<byte[], Integer, Boolean> testDifficulty) {
        return CompletableFuture.supplyAsync(() -> {
            long ts = System.currentTimeMillis();
            byte[] result;
            long counter = 0;
            do {
                result = toSha256Hash(payload, challenge, ++counter);
            }
            while (!testDifficulty.apply(result, difficulty));
            ProofOfWork proofOfWork = new ProofOfWork(payload, counter, challenge, difficulty, System.currentTimeMillis() - ts);
            log.info("Completed minting proofOfWork: {}", proofOfWork);
            return proofOfWork;
        });
    }
{'fraction_non_alphanumeric': 0.11356466876971609, 'fraction_numerical': 0.0018693772636990303, 'mean_word_length': 1.7983000980712651, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 23, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6718543', 'n_tokens_mistral': 1975, 'n_tokens_neox': 1909, 'n_words': 571}