Skip to content

Commit

Permalink
Merge pull request #6979 from alvasw/FilterManagerMockedPrivilegeKeys…
Browse files Browse the repository at this point in the history
…Tests

Add FilterManagerMockedPrivilegeKeysTests
  • Loading branch information
alejandrogarcia83 authored Dec 31, 2023
2 parents 1f072bf + 78ac425 commit f12069a
Show file tree
Hide file tree
Showing 18 changed files with 210 additions and 29 deletions.
6 changes: 3 additions & 3 deletions apitest/src/main/java/bisq/apitest/Scaffold.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package bisq.apitest;

import bisq.common.app.DevEnv;
import bisq.common.config.BisqHelpFormatter;
import bisq.common.util.Utilities;

Expand Down Expand Up @@ -45,7 +46,6 @@
import static bisq.apitest.config.ApiTestConfig.MEDIATOR;
import static bisq.apitest.config.ApiTestConfig.REFUND_AGENT;
import static bisq.apitest.config.BisqAppConfig.*;
import static bisq.common.app.DevEnv.DEV_PRIVILEGE_PRIV_KEY;
import static java.lang.String.format;
import static java.lang.System.exit;
import static java.lang.System.out;
Expand Down Expand Up @@ -482,8 +482,8 @@ private void maybeRegisterDisputeAgents() {
GrpcClient arbClient = new GrpcClient(getLoopbackAddress().getHostAddress(),
arbdaemon.apiPort,
config.apiPassword);
arbClient.registerDisputeAgent(MEDIATOR, DEV_PRIVILEGE_PRIV_KEY);
arbClient.registerDisputeAgent(REFUND_AGENT, DEV_PRIVILEGE_PRIV_KEY);
arbClient.registerDisputeAgent(MEDIATOR, DevEnv.getDEV_PRIVILEGE_PRIV_KEY());
arbClient.registerDisputeAgent(REFUND_AGENT, DevEnv.getDEV_PRIVILEGE_PRIV_KEY());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package bisq.apitest.method;

import bisq.common.app.DevEnv;

import io.grpc.StatusRuntimeException;

import lombok.extern.slf4j.Slf4j;
Expand All @@ -34,7 +36,6 @@
import static bisq.apitest.config.ApiTestConfig.REFUND_AGENT;
import static bisq.apitest.config.BisqAppConfig.arbdaemon;
import static bisq.apitest.config.BisqAppConfig.seednode;
import static bisq.common.app.DevEnv.DEV_PRIVILEGE_PRIV_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
Expand All @@ -60,7 +61,7 @@ public static void setUp() {
@Order(1)
public void testRegisterArbitratorShouldThrowException() {
Throwable exception = assertThrows(StatusRuntimeException.class, () ->
arbClient.registerDisputeAgent(ARBITRATOR, DEV_PRIVILEGE_PRIV_KEY));
arbClient.registerDisputeAgent(ARBITRATOR, DevEnv.getDEV_PRIVILEGE_PRIV_KEY()));
assertEquals("UNIMPLEMENTED: arbitrators must be registered in a Bisq UI",
exception.getMessage());
}
Expand All @@ -69,7 +70,7 @@ public void testRegisterArbitratorShouldThrowException() {
@Order(2)
public void testInvalidDisputeAgentTypeArgShouldThrowException() {
Throwable exception = assertThrows(StatusRuntimeException.class, () ->
arbClient.registerDisputeAgent("badagent", DEV_PRIVILEGE_PRIV_KEY));
arbClient.registerDisputeAgent("badagent", DevEnv.getDEV_PRIVILEGE_PRIV_KEY()));
assertEquals("INVALID_ARGUMENT: unknown dispute agent type 'badagent'",
exception.getMessage());
}
Expand All @@ -78,21 +79,21 @@ public void testInvalidDisputeAgentTypeArgShouldThrowException() {
@Order(3)
public void testInvalidRegistrationKeyArgShouldThrowException() {
Throwable exception = assertThrows(StatusRuntimeException.class, () ->
arbClient.registerDisputeAgent(REFUND_AGENT, "invalid" + DEV_PRIVILEGE_PRIV_KEY));
arbClient.registerDisputeAgent(REFUND_AGENT, "invalid" + DevEnv.getDEV_PRIVILEGE_PRIV_KEY()));
assertEquals("INVALID_ARGUMENT: invalid registration key",
exception.getMessage());
}

@Test
@Order(4)
public void testRegisterMediator() {
arbClient.registerDisputeAgent(MEDIATOR, DEV_PRIVILEGE_PRIV_KEY);
arbClient.registerDisputeAgent(MEDIATOR, DevEnv.getDEV_PRIVILEGE_PRIV_KEY());
}

@Test
@Order(5)
public void testRegisterRefundAgent() {
arbClient.registerDisputeAgent(REFUND_AGENT, DEV_PRIVILEGE_PRIV_KEY);
arbClient.registerDisputeAgent(REFUND_AGENT, DevEnv.getDEV_PRIVILEGE_PRIV_KEY());
}

@AfterAll
Expand Down
14 changes: 12 additions & 2 deletions common/src/main/java/bisq/common/app/DevEnv.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@

import bisq.common.config.Config;

import java.util.Collections;
import java.util.List;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
Expand All @@ -29,8 +33,14 @@ public class DevEnv {
// peer (click user icon and alt+r), filter/block offers by various data like offer ID (cmd + f).
// The user can set a program argument to ignore all of those privileged network_messages. They are intended for
// emergency cases only (beside update message and arbitrator registration).
public static final String DEV_PRIVILEGE_PUB_KEY = "027a381b5333a56e1cc3d90d3a7d07f26509adf7029ed06fc997c656621f8da1ee";
public static final String DEV_PRIVILEGE_PRIV_KEY = "6ac43ea1df2a290c1c8391736aa42e4339c5cb4f110ff0257a13b63211977b7a";
@Getter
private static final String DEV_PRIVILEGE_PUB_KEY = "027a381b5333a56e1cc3d90d3a7d07f26509adf7029ed06fc997c656621f8da1ee";
@Getter
private static final String DEV_PRIVILEGE_PRIV_KEY = "6ac43ea1df2a290c1c8391736aa42e4339c5cb4f110ff0257a13b63211977b7a";

public static List<String> getDevPrivilegePubKeys() {
return Collections.singletonList(DEV_PRIVILEGE_PUB_KEY);
}

public static void setup(Config config) {
DevEnv.setDevMode(config.useDevMode);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/bisq/core/alert/AlertManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public void onRemoved(Collection<ProtectedStorageEntry> protectedStorageEntries)
});
}
pubKeyAsHex = useDevPrivilegeKeys ?
DevEnv.DEV_PRIVILEGE_PUB_KEY :
DevEnv.getDEV_PRIVILEGE_PUB_KEY() :
"036d8a1dfcb406886037d2381da006358722823e1940acc2598c844bbc0fd1026f";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public PrivateNotificationManager(P2PService p2PService,
this.mailboxMessageService.addDecryptedMailboxListener(this::handleMessage);
}
pubKeyAsHex = useDevPrivilegeKeys ?
DevEnv.DEV_PRIVILEGE_PUB_KEY :
DevEnv.getDEV_PRIVILEGE_PUB_KEY() :
"02ba7c5de295adfe57b60029f3637a2c6b1d0e969a8aaefb9e0ddc3a7963f26925";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.P2PService;

import bisq.common.app.DevEnv;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing;

Expand All @@ -42,7 +43,6 @@

import lombok.extern.slf4j.Slf4j;

import static bisq.common.app.DevEnv.DEV_PRIVILEGE_PRIV_KEY;
import static bisq.core.support.SupportType.ARBITRATION;
import static bisq.core.support.SupportType.MEDIATION;
import static bisq.core.support.SupportType.REFUND;
Expand Down Expand Up @@ -87,7 +87,7 @@ void registerDisputeAgent(String disputeAgentType, String registrationKey) {
|| !config.useLocalhostForP2P)
throw new UnsupportedOperationException("dispute agents must be registered in a Bisq UI");

if (!registrationKey.equals(DEV_PRIVILEGE_PRIV_KEY))
if (!registrationKey.equals(DevEnv.getDEV_PRIVILEGE_PRIV_KEY()))
throw new IllegalArgumentException("invalid registration key");

Optional<SupportType> supportType = getSupportType(disputeAgentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public static boolean isPermittedPubKey(boolean useDevPrivilegeKeys, String pubK
}

private static Set<String> getPermittedPubKeys(boolean useDevPrivilegeKeys) {
return useDevPrivilegeKeys ? Set.of(DevEnv.DEV_PRIVILEGE_PUB_KEY) : PERMITTED_PUB_KEYS;
return useDevPrivilegeKeys ? Set.of(DevEnv.getDEV_PRIVILEGE_PUB_KEY()) : PERMITTED_PUB_KEYS;
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ public AccountingFullNodeNetworkService(NetworkNode networkNode,
this.useDevPrivilegeKeys = useDevPrivilegeKeys;

if (useDevPrivilegeKeys) {
bmOracleNodePubKey = DevEnv.DEV_PRIVILEGE_PUB_KEY;
bmOracleNodePrivKey = DevEnv.DEV_PRIVILEGE_PRIV_KEY;
bmOracleNodePubKey = DevEnv.getDEV_PRIVILEGE_PUB_KEY();
bmOracleNodePrivKey = DevEnv.getDEV_PRIVILEGE_PRIV_KEY();
}
this.bmOracleNodePubKey = bmOracleNodePubKey.isEmpty() ? null : bmOracleNodePubKey;
this.bmOracleNodePrivKey = bmOracleNodePrivKey.isEmpty() ? null : toEcKey(bmOracleNodePrivKey);
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/bisq/core/filter/FilterManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public FilterManager(P2PService p2PService,
this.ignoreDevMsg = ignoreDevMsg;

publicKeys = useDevPrivilegeKeys ?
Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY) :
DevEnv.getDevPrivilegePubKeys() :
List.of("0358d47858acdc41910325fce266571540681ef83a0d6fedce312bef9810793a27",
"029340c3e7d4bb0f9e651b5f590b434fecb6175aeaa57145c7804ff05d210e534f",
"034dc7530bf66ffd9580aa98031ea9a18ac2d269f7c56c0e71eca06105b9ed69f9");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public DisputeAgentManager(KeyRing keyRing,
this.disputeAgentService = disputeAgentService;
this.user = user;
this.filterManager = filterManager;
publicKeys = useDevPrivilegeKeys ? Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY) : getPubKeyList();
publicKeys = useDevPrivilegeKeys ? Collections.singletonList(DevEnv.getDEV_PRIVILEGE_PUB_KEY()) : getPubKeyList();
}


Expand Down Expand Up @@ -193,7 +193,7 @@ public void updateMap() {
String pubKeyAsHex = Utils.HEX.encode(e.getRegistrationPubKey());
boolean isInPublicKeyInList = isPublicKeyInList(pubKeyAsHex);
if (!isInPublicKeyInList) {
if (DevEnv.DEV_PRIVILEGE_PUB_KEY.equals(pubKeyAsHex))
if (DevEnv.getDEV_PRIVILEGE_PUB_KEY().equals(pubKeyAsHex))
log.info("We got the DEV_PRIVILEGE_PUB_KEY in our list of publicKeys. RegistrationPubKey={}, nodeAddress={}",
Utilities.bytesAsHexString(e.getRegistrationPubKey()),
e.getNodeAddress().getFullAddress());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void addDisputeAgent(T disputeAgent,
ErrorMessageHandler errorMessageHandler) {
log.debug("addDisputeAgent disputeAgent.hashCode() " + disputeAgent.hashCode());
if (!Config.baseCurrencyNetwork().isMainnet() ||
!Utilities.encodeToHex(disputeAgent.getRegistrationPubKey()).equals(DevEnv.DEV_PRIVILEGE_PUB_KEY)) {
!Utilities.encodeToHex(disputeAgent.getRegistrationPubKey()).equals(DevEnv.getDEV_PRIVILEGE_PUB_KEY())) {
boolean result = p2PService.addProtectedStorageEntry(disputeAgent);
if (result) {
log.trace("Add disputeAgent to network was successful. DisputeAgent.hashCode() = {}", disputeAgent.hashCode());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public FilterManagerAddFilterToNetworkTests() throws NoSuchAlgorithmException, N
KeyPair ownerKeyPair = keyPairGenerator.generateKeyPair();
ownerPublicKey = ownerKeyPair.getPublic();

privilegedDevEcKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(DevEnv.DEV_PRIVILEGE_PRIV_KEY)));
privilegedDevEcKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(DevEnv.getDEV_PRIVILEGE_PRIV_KEY())));
privilegedDevPubKeyHex = HEX.encode(privilegedDevEcKey.getPubKey());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/*
* 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.core.filter;

import bisq.core.provider.ProvidersRepository;
import bisq.core.user.Preferences;
import bisq.core.user.User;

import bisq.network.p2p.P2PService;
import bisq.network.p2p.network.BanFilter;
import bisq.network.p2p.storage.P2PDataStorage;
import bisq.network.p2p.storage.payload.ProtectedStorageEntry;

import bisq.common.app.DevEnv;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing;
import bisq.common.crypto.Sig;

import org.bitcoinj.core.ECKey;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Security;

import java.nio.file.Path;

import java.io.File;

import java.math.BigInteger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;

import static org.bitcoinj.core.Utils.HEX;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

@ExtendWith(MockitoExtension.class)
public class FilterManagerMockedPrivilegeKeysTests {
static {
Security.addProvider(new BouncyCastleProvider());
}

private final PublicKey ownerPublicKey;
private final ECKey privilegedDevEcKey;
private final ECKey secondPrivilegedDevEcKey;

public FilterManagerMockedPrivilegeKeysTests() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(Sig.KEY_ALGO, "BC");
KeyPair ownerKeyPair = keyPairGenerator.generateKeyPair();
ownerPublicKey = ownerKeyPair.getPublic();

privilegedDevEcKey = ECKey.fromPrivate(new BigInteger(1, HEX.decode(DevEnv.getDEV_PRIVILEGE_PRIV_KEY())));
secondPrivilegedDevEcKey = new ECKey();
}

@Test
void testBannedPrivilegedDevKey(@TempDir Path tmpDir,
@Mock P2PService p2PService,
@Mock P2PDataStorage p2pDataStorage) {
try (MockedStatic<DevEnv> devEnv = Mockito.mockStatic(DevEnv.class)) {

String privilegedDevPubKeyHex = HEX.encode(privilegedDevEcKey.getPubKey());
String secondPrivilegedDevPubKeyHex = HEX.encode(secondPrivilegedDevEcKey.getPubKey());
devEnv.when(DevEnv::getDevPrivilegePubKeys)
.thenReturn(List.of(privilegedDevPubKeyHex, secondPrivilegedDevPubKeyHex));

Config config = mock(Config.class);
File configFile = tmpDir.resolve("configFile").toFile();
doReturn(configFile).when(config).getConfigFile();

FilterManager filterManager = new FilterManager(
p2PService,
mock(KeyRing.class),
mock(User.class),
mock(Preferences.class),
config,
mock(ProvidersRepository.class),
mock(BanFilter.class),
false,
true
);

doReturn(p2pDataStorage).when(p2PService).getP2PDataStorage();
Map<P2PDataStorage.ByteArray, ProtectedStorageEntry> p2pStorageMap = new HashMap<>();
doReturn(p2pStorageMap).when(p2pDataStorage).getMap();

// No filter before adding our filter
assertNull(filterManager.getFilter());

long creationTime = System.currentTimeMillis();

List<String> bannedPrivilegedDevKey = List.of(secondPrivilegedDevPubKeyHex);
Filter firstFilter = TestFilter.createFilter(ownerPublicKey, privilegedDevPubKeyHex,
creationTime, bannedPrivilegedDevKey);
Filter firstFilterWithSig = TestFilter.signFilter(firstFilter, privilegedDevEcKey);


Filter secondFilterWithSig = TestFilter.createSignedFilter(ownerPublicKey, secondPrivilegedDevEcKey,
creationTime + 100);

assertNotEquals(firstFilterWithSig, secondFilterWithSig);

p2pStorageMap.put(
new P2PDataStorage.ByteArray(new byte[100]),
TestFilter.createProtectedStorageEntryForFilter(firstFilterWithSig)
);

filterManager.onAllServicesInitialized();

// Our filter got set
Filter currentFilter = filterManager.getFilter();
assertNotNull(currentFilter);
assertEquals(firstFilterWithSig, currentFilter);

p2pStorageMap.clear();
p2pStorageMap.put(
new P2PDataStorage.ByteArray(new byte[100]),
TestFilter.createProtectedStorageEntryForFilter(secondFilterWithSig)
);

filterManager.onAllServicesInitialized();

// Our filter got set
currentFilter = filterManager.getFilter();
assertNotNull(currentFilter);
assertEquals(firstFilterWithSig, currentFilter);
}
}
}
Loading

0 comments on commit f12069a

Please sign in to comment.