<commit_before>/*
 * Copyright 2016 Hash Engineering Solutions
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.bitcoinj.core;

import org.bitcoinj.core.listeners.PeerConnectedEventListener;
import org.bitcoinj.core.listeners.SporkUpdatedEventListener;
import org.bitcoinj.utils.ListenerRegistration;
import org.bitcoinj.utils.Pair;
import org.bitcoinj.utils.Threading;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Created by <NAME> on 2/20/2016.
 *
 * Handles SporkMessages and their verification
 */
public class SporkManager {
    private static final Logger log = LoggerFactory.getLogger(SporkManager.class);
    ReentrantLock lock = Threading.lock("SporkManager");

    private static final HashMap<SporkId, SporkDefinition> mapSporkDefaults = new HashMap<>();
    private static void makeSporkDefinition(SporkId sporkId, long defaultValue) {
        mapSporkDefaults.put(sporkId, new SporkDefinition(sporkId, defaultValue));
    }
    static {
        makeSporkDefinition(SporkId.SPORK_2_INSTANTSEND_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_3_INSTANTSEND_BLOCK_FILTERING, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_9_SUPERBLOCKS_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_17_QUORUM_DKG_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_19_CHAINLOCKS_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_21_QUORUM_ALL_CONNECTED,4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_23_QUORUM_POSE, 4070908800L); // OFF
    }

    int minSporkKeys;

    @GuardedBy("lock") private final HashMap<Sha256Hash, SporkMessage> mapSporksByHash;
    @GuardedBy("lock") private final HashMap<SporkId, Map<KeyId, SporkMessage>> mapSporksActive;
    @GuardedBy("lock") private final HashMap<SporkId, Boolean> mapSporksCachedActive;
    @GuardedBy("lock") private final HashMap<SporkId, Long> mapSporksCachedValues;
    @GuardedBy("lock") private final HashSet<KeyId> setSporkPubKeyIds = new HashSet<>();

    private AbstractBlockChain blockChain;
    private final Context context;

    public SporkManager(Context context)
    {
        this.context = context;
        mapSporksByHash = new HashMap<>();
        mapSporksActive = new HashMap<>();
        mapSporksCachedActive = new HashMap<>();
        mapSporksCachedValues = new HashMap<>();
        setSporkAddress(context.getParams().getSporkAddress());
        eventListeners = new CopyOnWriteArrayList<>();
        setMinSporkKeys(context.getParams().getMinSporkKeys());
    }

    void setBlockChain(AbstractBlockChain blockChain, @Nullable PeerGroup peerGroup) {
        this.blockChain = blockChain;
        if (peerGroup != null) {
            peerGroup.addConnectedEventListener(peerConnectedEventListener);
        }
    }

    public void clear() {
        mapSporksActive.clear();
        mapSporksByHash.clear();
    }

    public void close(PeerGroup peerGroup) {
        peerGroup.removeConnectedEventListener(peerConnectedEventListener);
    }

    void processSpork(Peer from, SporkMessage spork) {
        if (context.isLiteMode() && !context.allowInstantXinLiteMode()) {
            return; //disable all darksend/masternode related functionality
        }

        Sha256Hash hash = spork.getHash();
        String logMessage = String.format("SPORK -- hash: %s id: %d (%s) value: %10d bestHeight: %d peer=%s:%d",
                hash, spork.getSporkId().value, String.format("%1$35s", spork.getSporkId().name()),
                spork.getValue(), blockChain.getBestChainHeight(), from.getAddress().getAddr().toString(),
                from.getAddress().getPort());

        if (spork.getTimeSigned() > Utils.currentTimeSeconds() + 2 * 60 * 60) {
            log.info("processSpork -- ERROR: too far into the future");
            // need to reject this peer
            //throw new ProtocolException("spork too far into the future");
            return;
        }

        KeyId keyIdSigner = spork.getSignerKeyId();
        if (keyIdSigner == null || !setSporkPubKeyIds.contains(keyIdSigner)) {
            log.info("processSpork -- ERROR: invalid signature");
            // TODO: need to reject this peer?  for now old peers will give us old sporks?
            // throw new ProtocolException("spork has invalid signature");
            return;
        }

        if (mapSporksActive.containsKey(spork.getSporkId())) {
            if (mapSporksActive.get(spork.getSporkId()).containsKey(keyIdSigner)) {
                if (mapSporksActive.get(spork.getSporkId()).get(keyIdSigner).getTimeSigned() >= spork.getTimeSigned()) {
                    log.info("{} seen ", logMessage);
                    return;
                } else {
                    log.info("{} updated", logMessage);<commit_msg>fix: do not log obsolete sporks<commit_after>/*
 * Copyright 2016 Hash Engineering Solutions
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.bitcoinj.core;

import org.bitcoinj.core.listeners.PeerConnectedEventListener;
import org.bitcoinj.core.listeners.SporkUpdatedEventListener;
import org.bitcoinj.utils.ListenerRegistration;
import org.bitcoinj.utils.Pair;
import org.bitcoinj.utils.Threading;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Created by <NAME> on 2/20/2016.
 *
 * Handles SporkMessages and their verification
 */
public class SporkManager {
    private static final Logger log = LoggerFactory.getLogger(SporkManager.class);
    ReentrantLock lock = Threading.lock("SporkManager");

    private static final HashMap<SporkId, SporkDefinition> mapSporkDefaults = new HashMap<>();
    private static void makeSporkDefinition(SporkId sporkId, long defaultValue) {
        mapSporkDefaults.put(sporkId, new SporkDefinition(sporkId, defaultValue));
    }
    static {
        makeSporkDefinition(SporkId.SPORK_2_INSTANTSEND_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_3_INSTANTSEND_BLOCK_FILTERING, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_9_SUPERBLOCKS_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_17_QUORUM_DKG_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_19_CHAINLOCKS_ENABLED, 4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_21_QUORUM_ALL_CONNECTED,4070908800L); // OFF
        makeSporkDefinition(SporkId.SPORK_23_QUORUM_POSE, 4070908800L); // OFF
    }

    int minSporkKeys;

    @GuardedBy("lock") private final HashMap<Sha256Hash, SporkMessage> mapSporksByHash;
    @GuardedBy("lock") private final HashMap<SporkId, Map<KeyId, SporkMessage>> mapSporksActive;
    @GuardedBy("lock") private final HashMap<SporkId, Boolean> mapSporksCachedActive;
    @GuardedBy("lock") private final HashMap<SporkId, Long> mapSporksCachedValues;
    @GuardedBy("lock") private final HashSet<KeyId> setSporkPubKeyIds = new HashSet<>();

    private AbstractBlockChain blockChain;
    private final Context context;

    public SporkManager(Context context)
    {
        this.context = context;
        mapSporksByHash = new HashMap<>();
        mapSporksActive = new HashMap<>();
        mapSporksCachedActive = new HashMap<>();
        mapSporksCachedValues = new HashMap<>();
        setSporkAddress(context.getParams().getSporkAddress());
        eventListeners = new CopyOnWriteArrayList<>();
        setMinSporkKeys(context.getParams().getMinSporkKeys());
    }

    void setBlockChain(AbstractBlockChain blockChain, @Nullable PeerGroup peerGroup) {
        this.blockChain = blockChain;
        if (peerGroup != null) {
            peerGroup.addConnectedEventListener(peerConnectedEventListener);
        }
    }

    public void clear() {
        mapSporksActive.clear();
        mapSporksByHash.clear();
    }

    public void close(PeerGroup peerGroup) {
        peerGroup.removeConnectedEventListener(peerConnectedEventListener);
    }

    void processSpork(Peer from, SporkMessage spork) {
        if (context.isLiteMode() && !context.allowInstantXinLiteMode()) {
            return; //disable all darksend/masternode related functionality
        }

        Sha256Hash hash = spork.getHash();
        String logMessage = String.format("SPORK -- hash: %s id: %d (%s) value: %10d bestHeight: %d peer=%s:%d",
                hash, spork.getSporkId().value, String.format("%1$35s", spork.getSporkId().name()),
                spork.getValue(), blockChain.getBestChainHeight(), from.getAddress().getAddr().toString(),
                from.getAddress().getPort());

        if (spork.getTimeSigned() > Utils.currentTimeSeconds() + 2 * 60 * 60) {
            log.info("processSpork -- ERROR: too far into the future");
            // need to reject this peer
            //throw new ProtocolException("spork too far into the future");
            return;
        }

        KeyId keyIdSigner = spork.getSignerKeyId();
        if (keyIdSigner == null || !setSporkPubKeyIds.contains(keyIdSigner)) {
            // TODO: need to reject this peer?  for now old peers will give us old sporks?
            // log.info("processSpork -- ERROR: invalid signature");
            // throw new ProtocolException("spork has invalid signature");
            return;
        }

        if (mapSporksActive.containsKey(spork.getSporkId())) {
            if (mapSporksActive.get(spork.getSporkId()).containsKey(keyIdSigner)) {
                if (mapSporksActive.get(spork.getSporkId()).get(keyIdSigner).getTimeSigned() >= spork.getTimeSigned()) {
                    log.info("{} seen ", logMessage);
                    return;
                } else {
                    log.info("{} updated", logMessage);
{'fraction_non_alphanumeric': 0.1036590690769365, 'fraction_numerical': 0.01991092481006026, 'mean_word_length': 3.4370399070127857, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5708785', 'n_tokens_mistral': 3489, 'n_tokens_neox': 3330, 'n_words': 768}