Introduce Config as replacement for BisqEnvironment

Prior to this commit, BisqExecutable has been responsible for parsing
command line and config file options and BisqEnvironment has been
responsible for assigning default values to those options and providing
access to option values to callers throughout the codebase.

This approach has worked, but at considerable costs in complexity,
verbosity, and lack of any type-safety in option values. BisqEnvironment
is based on the Spring Framework's Environment abstraction, which
provides a great deal of flexibility in handling command line options,
environment variables, and more, but also operates on the assumption
that such inputs have String-based values.

After having this infrastructure in place for years now, it has become
evident that using Spring's Environment abstraction was both overkill
for what we needed and limited us from getting the kind of concision and
type saftey that we want. The Environment abstraction is by default
actually too flexible. For example, Bisq does not want or need to have
environment variables potentially overriding configuration file values,
as this increases our attack surface and makes our threat model more
complex. This is why we explicitly removed support for handling
environment variables quite some time ago.

The BisqEnvironment class has also organically evolved toward becoming a
kind of "God object", responsible for more than just option handling. It
is also, for example, responsible for tracking the status of the user's
local Bitcoin node, if any. It is also responsible for writing values to
the bisq.properties config file when certain ban filters arrive via the
p2p network. In the commits that follow, these unrelated functions will
be factored out appropriately in order to separate concerns.

As a solution to these problems, this commit begins the process of
eliminating BisqEnvironment in favor of a new, bespoke Config class
custom-tailored to Bisq's needs. Config removes the responsibility for
option parsing from BisqExecutable, and in the end provides "one-stop
shopping" for all option parsing and access needs.

The changes included in this commit represent a proof of concept for the
Config class, where handling of a number of options has been moved from
BisqEnvironment and BisqExecutable over to Config. Because the migration
is only partial, both Config and BisqEnvironment are injected
side-by-side into calling code that needs access to options. As the
migration is completed, BisqEnvironment will be removed entirely, and
only the Config object will remain.

An additional benefit of the elimination of BisqEnvironment is that it
will allow us to remove our dependency on the Spring Framework (with the
exception of the standalone pricenode application, which is Spring-based
by design).

Note that while this change and those that follow it are principally a
refactoring effort, certain functional changes have been introduced. For
example, Bisq now supports a `--configFile` argument at the command line
that functions very similarly to Bitcoin Core's `-conf` option.
This commit is contained in:
Chris Beams 2019-12-06 23:54:58 +01:00
parent 92466f96eb
commit b34d59c0a9
No known key found for this signature in database
GPG key ID: 3D214F8F5BC5ED73
126 changed files with 1541 additions and 719 deletions

View file

@ -161,7 +161,7 @@
<emptyLine /> <emptyLine />
<package name="org.powermock" withSubpackages="true" static="false" /> <package name="org.powermock" withSubpackages="true" static="false" />
<emptyLine /> <emptyLine />
<package name="mockit" withSubpackages="true" static="false" /> <package name="org.mockito" withSubpackages="true" static="false" />
<emptyLine /> <emptyLine />
<package name="org.junit" withSubpackages="true" static="false" /> <package name="org.junit" withSubpackages="true" static="false" />
<emptyLine /> <emptyLine />

View file

@ -181,6 +181,7 @@ configure(project(':common')) {
compile "com.google.protobuf:protobuf-java:$protobufVersion" compile "com.google.protobuf:protobuf-java:$protobufVersion"
compile 'com.google.code.gson:gson:2.8.5' compile 'com.google.code.gson:gson:2.8.5'
compile "org.springframework:spring-core:$springVersion" compile "org.springframework:spring-core:$springVersion"
compile "net.sf.jopt-simple:jopt-simple:$joptVersion"
compile "org.slf4j:slf4j-api:$slf4jVersion" compile "org.slf4j:slf4j-api:$slf4jVersion"
compile "ch.qos.logback:logback-core:$logbackVersion" compile "ch.qos.logback:logback-core:$logbackVersion"
compile "ch.qos.logback:logback-classic:$logbackVersion" compile "ch.qos.logback:logback-classic:$logbackVersion"
@ -201,6 +202,7 @@ configure(project(':common')) {
compile "org.apache.commons:commons-lang3:$langVersion" compile "org.apache.commons:commons-lang3:$langVersion"
compileOnly "org.projectlombok:lombok:$lombokVersion" compileOnly "org.projectlombok:lombok:$lombokVersion"
annotationProcessor "org.projectlombok:lombok:$lombokVersion" annotationProcessor "org.projectlombok:lombok:$lombokVersion"
testCompile "org.hamcrest:hamcrest-all:$hamcrestVersion"
} }
} }
@ -217,7 +219,6 @@ configure(project(':p2p')) {
compile("org.apache.httpcomponents:httpclient:$httpclientVersion") { compile("org.apache.httpcomponents:httpclient:$httpclientVersion") {
exclude(module: 'commons-logging') exclude(module: 'commons-logging')
} }
compile "net.sf.jopt-simple:jopt-simple:$joptVersion"
compile "org.fxmisc.easybind:easybind:$easybindVersion" compile "org.fxmisc.easybind:easybind:$easybindVersion"
compileOnly "org.projectlombok:lombok:$lombokVersion" compileOnly "org.projectlombok:lombok:$lombokVersion"
annotationProcessor "org.projectlombok:lombok:$lombokVersion" annotationProcessor "org.projectlombok:lombok:$lombokVersion"
@ -234,7 +235,6 @@ configure(project(':core')) {
dependencies { dependencies {
compile project(':assets') compile project(':assets')
compile project(':p2p') compile project(':p2p')
compile "net.sf.jopt-simple:jopt-simple:$joptVersion"
compile("network.bisq.btcd-cli4j:btcd-cli4j-core:$btcdCli4jVersion") { compile("network.bisq.btcd-cli4j:btcd-cli4j-core:$btcdCli4jVersion") {
exclude(module: 'slf4j-api') exclude(module: 'slf4j-api')
exclude(module: 'httpclient') exclude(module: 'httpclient')
@ -273,10 +273,10 @@ configure(project(':core')) {
compileOnly "org.projectlombok:lombok:$lombokVersion" compileOnly "org.projectlombok:lombok:$lombokVersion"
annotationProcessor "org.projectlombok:lombok:$lombokVersion" annotationProcessor "org.projectlombok:lombok:$lombokVersion"
testCompile "org.hamcrest:hamcrest-all:$hamcrestVersion"
testCompile "org.mockito:mockito-core:$mockitoVersion" testCompile "org.mockito:mockito-core:$mockitoVersion"
testCompile "org.springframework:spring-test:$springVersion" testCompile "org.springframework:spring-test:$springVersion"
testCompile "com.natpryce:make-it-easy:$easyVersion" testCompile "com.natpryce:make-it-easy:$easyVersion"
testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: "$hamcrestVersion"
testCompileOnly "org.projectlombok:lombok:$lombokVersion" testCompileOnly "org.projectlombok:lombok:$lombokVersion"
testAnnotationProcessor "org.projectlombok:lombok:$lombokVersion" testAnnotationProcessor "org.projectlombok:lombok:$lombokVersion"
} }
@ -444,6 +444,7 @@ configure(project(':seednode')) {
compileOnly "org.projectlombok:lombok:$lombokVersion" compileOnly "org.projectlombok:lombok:$lombokVersion"
annotationProcessor "org.projectlombok:lombok:$lombokVersion" annotationProcessor "org.projectlombok:lombok:$lombokVersion"
testCompile "org.springframework:spring-test:$springVersion" testCompile "org.springframework:spring-test:$springVersion"
testCompile "org.mockito:mockito-core:$mockitoVersion"
} }
} }

View file

@ -15,7 +15,7 @@
* along with Bisq. If not, see <http://www.gnu.org/licenses/>. * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/ */
package bisq.core.exceptions; package bisq.common;
public class BisqException extends RuntimeException { public class BisqException extends RuntimeException {
public BisqException(Throwable cause) { public BisqException(Throwable cause) {

View file

@ -17,6 +17,8 @@
package bisq.common.app; package bisq.common.app;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
@ -28,13 +30,16 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public abstract class AppModule extends AbstractModule { public abstract class AppModule extends AbstractModule {
protected final Environment environment; protected final Environment environment;
protected final Config config;
private final List<AppModule> modules = new ArrayList<>(); private final List<AppModule> modules = new ArrayList<>();
protected AppModule(Environment environment) { protected AppModule(Environment environment, Config config) {
Preconditions.checkNotNull(environment, "Environment must not be null"); Preconditions.checkNotNull(environment, "Environment must not be null");
this.environment = environment; this.environment = environment;
this.config = config;
} }
protected void install(AppModule module) { protected void install(AppModule module) {

View file

@ -15,7 +15,7 @@
* along with Bisq. If not, see <http://www.gnu.org/licenses/>. * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/ */
package bisq.core.btc; package bisq.common.config;
import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.MainNetParams;
@ -32,6 +32,9 @@ public enum BaseCurrencyNetwork {
BTC_DAO_BETANET(MainNetParams.get(), "BTC", "MAINNET", "Bitcoin"), // mainnet test genesis BTC_DAO_BETANET(MainNetParams.get(), "BTC", "MAINNET", "Bitcoin"), // mainnet test genesis
BTC_DAO_REGTEST(RegTestParams.get(), "BTC", "REGTEST", "Bitcoin"); // server side regtest after v0.9.5, had breaking code changes so we started over again BTC_DAO_REGTEST(RegTestParams.get(), "BTC", "REGTEST", "Bitcoin"); // server side regtest after v0.9.5, had breaking code changes so we started over again
public static BaseCurrencyNetwork CURRENT_NETWORK = BTC_MAINNET;
public static NetworkParameters CURRENT_PARAMETERS = CURRENT_NETWORK.getParameters();
@Getter @Getter
private final NetworkParameters parameters; private final NetworkParameters parameters;
@Getter @Getter

View file

@ -15,7 +15,7 @@
* along with Bisq. If not, see <http://www.gnu.org/licenses/>. * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/ */
package bisq.core.app; package bisq.common.config;
import joptsimple.HelpFormatter; import joptsimple.HelpFormatter;
import joptsimple.OptionDescriptor; import joptsimple.OptionDescriptor;

View file

@ -0,0 +1,45 @@
package bisq.common.config;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import java.util.ArrayList;
import java.util.List;
class CompositeOptionSet {
private final List<OptionSet> optionSets = new ArrayList<>();
public void addOptionSet(OptionSet optionSet) {
optionSets.add(optionSet);
}
public boolean has(OptionSpec<?> option) {
for (OptionSet optionSet : optionSets)
if (optionSet.has(option))
return true;
return false;
}
public <V> V valueOf(OptionSpec<V> option) {
for (OptionSet optionSet : optionSets)
if (optionSet.has(option))
return optionSet.valueOf(option);
// None of the provided option sets specified the given option so fall back to
// the default value (if any) provided by the first specified OptionSet
return optionSets.get(0).valueOf(option);
}
public List<String> valuesOf(ArgumentAcceptingOptionSpec<String> option) {
for (OptionSet optionSet : optionSets)
if (optionSet.has(option))
return optionSet.valuesOf(option);
// None of the provided option sets specified the given option so fall back to
// the default value (if any) provided by the first specified OptionSet
return optionSets.get(0).valuesOf(option);
}
}

View file

@ -0,0 +1,344 @@
package bisq.common.config;
import bisq.common.util.Utilities;
import joptsimple.AbstractOptionSpec;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.util.PathConverter;
import joptsimple.util.PathProperties;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.util.List;
import java.util.Optional;
import ch.qos.logback.classic.Level;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
public class Config {
static final String DEFAULT_CONFIG_FILE_NAME = "bisq.properties";
static final int DEFAULT_NODE_PORT = 9999;
public static File CURRENT_APP_DATA_DIR;
private final String defaultAppName;
private final File defaultUserDataDir;
private final File defaultAppDataDir;
private final File defaultConfigFile;
private final File configFile;
private final String appName;
private final File userDataDir;
private final File appDataDir;
private final int nodePort;
private final List<String> bannedBtcNodes;
private final List<String> bannedPriceRelayNodes;
private final List<String> bannedSeedNodes;
private final BaseCurrencyNetwork baseCurrencyNetwork;
private final boolean ignoreLocalBtcNode;
private final String bitcoinRegtestHost;
private final boolean daoActivated;
private final boolean fullDaoNode;
private final String logLevel;
private final Path torrcFile;
// FIXME: Carryover from legacy BisqEnvironment; there should be no mutable state here
private boolean localBitcoinNodeIsRunning = false;
public Config(String defaultAppName) throws HelpRequested {
this(defaultAppName, new String[]{});
}
public Config(String defaultAppName, String[] args) throws HelpRequested {
this.defaultAppName = defaultAppName;
this.defaultUserDataDir = getDefaultUserDataDir();
this.defaultAppDataDir = new File(defaultUserDataDir, this.defaultAppName);
this.defaultConfigFile = new File(defaultAppDataDir, DEFAULT_CONFIG_FILE_NAME);
OptionParser parser = new OptionParser();
parser.allowsUnrecognizedOptions();
AbstractOptionSpec<Void> helpOpt =
parser.accepts("help", "Print this help text")
.forHelp();
ArgumentAcceptingOptionSpec<String> configFileOpt =
parser.accepts("configFile", "Specify configuration file. " +
"Relative paths will be prefixed by appDataDir location.")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(DEFAULT_CONFIG_FILE_NAME);
ArgumentAcceptingOptionSpec<File> userDataDirOpt =
parser.accepts("userDataDir", "User data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultUserDataDir);
ArgumentAcceptingOptionSpec<String> appNameOpt =
parser.accepts("appName", "Application name")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(this.defaultAppName);
ArgumentAcceptingOptionSpec<File> appDataDirOpt =
parser.accepts("appDataDir", "Application data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultAppDataDir);
ArgumentAcceptingOptionSpec<Integer> nodePortOpt =
parser.accepts("nodePort", "Port to listen on")
.withRequiredArg()
.ofType(Integer.class)
.defaultsTo(DEFAULT_NODE_PORT);
ArgumentAcceptingOptionSpec<String> bannedBtcNodesOpt =
parser.accepts("bannedBtcNodes", "List Bitcoin nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedPriceRelayNodesOpt =
parser.accepts("bannedPriceRelayNodes", "List Bisq price nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedSeedNodesOpt =
parser.accepts("bannedSeedNodes", "List Bisq seed nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<Enum> baseCurrencyNetworkOpt =
parser.accepts("baseCurrencyNetwork", "Base currency network")
.withRequiredArg()
.ofType(BaseCurrencyNetwork.class)
.withValuesConvertedBy(new EnumValueConverter(BaseCurrencyNetwork.class))
.defaultsTo(BaseCurrencyNetwork.BTC_MAINNET);
ArgumentAcceptingOptionSpec<Boolean> ignoreLocalBtcNodeOpt =
parser.accepts("ignoreLocalBtcNode", "If set to true a Bitcoin Core node running locally will be ignored")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> bitcoinRegtestHostOpt =
parser.accepts("bitcoinRegtestHost", "Bitcoin Core node when using BTC_REGTEST network")
.withRequiredArg()
.ofType(String.class)
.describedAs("host[:port]")
.defaultsTo("localhost");
ArgumentAcceptingOptionSpec<Boolean> daoActivatedOpt =
parser.accepts("daoActivated", "Developer flag. If true it enables dao phase 2 features.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(true);
ArgumentAcceptingOptionSpec<Boolean> fullDaoNodeOpt =
parser.accepts("fullDaoNode", "If set to true the node requests the blockchain data via RPC requests " +
"from Bitcoin Core and provide the validated BSQ txs to the network. It requires that the " +
"other RPC properties are set as well.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> logLevelOpt =
parser.accepts("logLevel", "Set logging level")
.withRequiredArg()
.ofType(String.class)
.describedAs("OFF|ALL|ERROR|WARN|INFO|DEBUG|TRACE")
.defaultsTo(Level.INFO.levelStr);
ArgumentAcceptingOptionSpec<Path> torrcFileOpt =
parser.accepts("torrcFile", "An existing torrc-file to be sourced for Tor. Note that torrc-entries, " +
"which are critical to Bisq's correct operation, cannot be overwritten.")
.withRequiredArg()
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
try {
OptionSet cliOpts = parser.parse(args);
if (cliOpts.has(helpOpt))
throw new HelpRequested(parser);
CompositeOptionSet options = new CompositeOptionSet();
options.addOptionSet(cliOpts);
File configFile = null;
final boolean cliHasConfigFileOpt = cliOpts.has(configFileOpt);
boolean configFileHasBeenProcessed = false;
if (cliHasConfigFileOpt) {
configFile = new File(cliOpts.valueOf(configFileOpt));
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
if (configFileOpts.isPresent()) {
options.addOptionSet(configFileOpts.get());
configFileHasBeenProcessed = true;
}
}
this.appName = options.valueOf(appNameOpt);
this.userDataDir = options.valueOf(userDataDirOpt);
this.appDataDir = options.has(appDataDirOpt) ?
options.valueOf(appDataDirOpt) :
new File(this.userDataDir, this.appName);
CURRENT_APP_DATA_DIR = appDataDir;
if (!configFileHasBeenProcessed) {
configFile = cliHasConfigFileOpt && !configFile.isAbsolute() ?
new File(this.appDataDir, configFile.getPath()) : // TODO: test
new File(this.appDataDir, DEFAULT_CONFIG_FILE_NAME);
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
configFileOpts.ifPresent(options::addOptionSet);
}
this.configFile = configFile;
this.nodePort = options.valueOf(nodePortOpt);
this.bannedBtcNodes = options.valuesOf(bannedBtcNodesOpt);
this.bannedPriceRelayNodes = options.valuesOf(bannedPriceRelayNodesOpt);
this.bannedSeedNodes = options.valuesOf(bannedSeedNodesOpt);
this.baseCurrencyNetwork = (BaseCurrencyNetwork) options.valueOf(baseCurrencyNetworkOpt);
BaseCurrencyNetwork.CURRENT_NETWORK = baseCurrencyNetwork;
BaseCurrencyNetwork.CURRENT_PARAMETERS = baseCurrencyNetwork.getParameters();
this.ignoreLocalBtcNode = options.valueOf(ignoreLocalBtcNodeOpt);
this.bitcoinRegtestHost = options.valueOf(bitcoinRegtestHostOpt);
this.daoActivated = options.valueOf(daoActivatedOpt) || !baseCurrencyNetwork.isMainnet();
this.fullDaoNode = options.valueOf(fullDaoNodeOpt);
this.logLevel = options.valueOf(logLevelOpt);
this.torrcFile = options.valueOf(torrcFileOpt);
} catch (OptionException ex) {
throw new ConfigException(format("problem parsing option '%s': %s",
ex.options().get(0),
ex.getCause() != null ?
ex.getCause().getMessage() :
ex.getMessage()));
}
}
private Optional<OptionSet> parseOptionsFrom(File file, OptionParser parser, OptionSpec<?>... disallowedOpts) {
if (!file.isAbsolute() || !file.exists())
return Optional.empty();
ConfigFileReader configFileReader = new ConfigFileReader(file);
String[] optionLines = configFileReader.getOptionLines().stream()
.map(o -> "--" + o) // prepend dashes expected by jopt parser below
.collect(toList())
.toArray(new String[]{});
OptionSet configFileOpts = parser.parse(optionLines);
for (OptionSpec<?> disallowedOpt : disallowedOpts)
if (configFileOpts.has(disallowedOpt))
throw new IllegalArgumentException(
format("The '%s' option is disallowed in config files", disallowedOpt.options().get(0)));
return Optional.of(configFileOpts);
}
public String getDefaultAppName() {
return defaultAppName;
}
public File getDefaultUserDataDir() {
if (Utilities.isWindows())
return new File(System.getenv("APPDATA"));
if (Utilities.isOSX())
return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toFile();
// *nix
return Paths.get(System.getProperty("user.home"), ".local", "share").toFile();
}
public File getDefaultAppDataDir() {
return defaultAppDataDir;
}
public File getDefaultConfigFile() {
return defaultConfigFile;
}
public File getConfigFile() {
return configFile;
}
public String getAppName() {
return appName;
}
public File getUserDataDir() {
return userDataDir;
}
public File getAppDataDir() {
return appDataDir;
}
public int getNodePort() {
return nodePort;
}
public List<String> getBannedBtcNodes() {
return bannedBtcNodes;
}
public List<String> getBannedPriceRelayNodes() {
return bannedPriceRelayNodes;
}
public List<String> getBannedSeedNodes() {
return bannedSeedNodes;
}
public BaseCurrencyNetwork getBaseCurrencyNetwork() {
return baseCurrencyNetwork;
}
public boolean isIgnoreLocalBtcNode() {
return ignoreLocalBtcNode;
}
public String getBitcoinRegtestHost() {
return bitcoinRegtestHost;
}
public boolean isDaoActivated() {
return daoActivated;
}
public boolean isFullDaoNode() {
return fullDaoNode;
}
public String getLogLevel() {
return logLevel;
}
public boolean isLocalBitcoinNodeIsRunning() {
return localBitcoinNodeIsRunning;
}
public void setLocalBitcoinNodeIsRunning(boolean value) {
this.localBitcoinNodeIsRunning = value;
}
public Path getTorrcFile() {
return torrcFile;
}
}

View file

@ -0,0 +1,8 @@
package bisq.common.config;
public class ConfigException extends RuntimeException {
public ConfigException(String message) {
super(message);
}
}

View file

@ -0,0 +1,87 @@
package bisq.common.config;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.util.List;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
public class ConfigFileEditor {
private static final Logger log = (Logger) LoggerFactory.getLogger(ConfigFileEditor.class);
private final File file;
private final ConfigFileReader reader;
public ConfigFileEditor(File file) {
this.file = file;
this.reader = new ConfigFileReader(file);
}
public void setOption(String name) {
setOption(name, null);
}
public void setOption(String name, String arg) {
tryCreate(file);
List<String> lines = reader.getLines();
try (PrintWriter writer = new PrintWriter(file)) {
boolean fileAlreadyContainsTargetOption = false;
for (String line : lines) {
if (ConfigFileOption.isOption(line)) {
ConfigFileOption existingOption = ConfigFileOption.parse(line);
if (existingOption.name.equals(name)) {
fileAlreadyContainsTargetOption = true;
if (!existingOption.arg.equals(arg)) {
ConfigFileOption newOption = new ConfigFileOption(name, arg);
writer.println(newOption);
log.warn("Overwrote existing config file option '{}' as '{}'", existingOption, newOption);
continue;
}
}
}
writer.println(line);
}
if (!fileAlreadyContainsTargetOption)
writer.println(new ConfigFileOption(name, arg));
} catch (FileNotFoundException ex) {
throw new UncheckedIOException(ex);
}
}
public void clearOption(String name) {
if (!file.exists())
return;
List<String> lines = reader.getLines();
try (PrintWriter writer = new PrintWriter(file)) {
for (String line : lines) {
if (ConfigFileOption.isOption(line)) {
ConfigFileOption option = ConfigFileOption.parse(line);
if (option.name.equals(name)) {
log.warn("Cleared existing config file option '{}'", option);
continue;
}
}
writer.println(line);
}
} catch (FileNotFoundException ex) {
throw new UncheckedIOException(ex);
}
}
private void tryCreate(File file) {
try {
if (file.createNewFile())
log.info("Created config file '{}'", file);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}

View file

@ -0,0 +1,36 @@
package bisq.common.config;
class ConfigFileOption {
public final String name;
public final String arg;
public ConfigFileOption(String name, String arg) {
this.name = name;
this.arg = arg;
}
public static boolean isOption(String line) {
return !line.isEmpty() && !line.startsWith("#");
}
public static ConfigFileOption parse(String option) {
if (!option.contains("="))
return new ConfigFileOption(option, null);
String[] tokens = clean(option).split("=");
String name = tokens[0].trim();
String arg = tokens[1].trim();
return new ConfigFileOption(name, arg);
}
public String toString() {
return String.format("%s%s", name, arg != null ? ('=' + arg) : "");
}
public static String clean(String option) {
return option
.trim()
.replace("\\:", ":");
}
}

View file

@ -0,0 +1,47 @@
package bisq.common.config;
import java.nio.file.Files;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
class ConfigFileReader {
private final File file;
public ConfigFileReader(File file) {
this.file = file;
}
public List<String> getLines() {
if (!file.exists())
throw new IllegalArgumentException(format("Config file %s does not exist", file));
if (!file.canRead())
throw new IllegalArgumentException(format("Config file %s is not readable", file));
try {
return Files.readAllLines(file.toPath()).stream()
.map(ConfigFileReader::cleanLine)
.collect(toList());
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public List<String> getOptionLines() {
return getLines().stream()
.filter(ConfigFileOption::isOption)
.collect(toList());
}
private static String cleanLine(String line) {
return ConfigFileOption.isOption(line) ? ConfigFileOption.clean(line) : line;
}
}

View file

@ -15,7 +15,7 @@
* along with Bisq. If not, see <http://www.gnu.org/licenses/>. * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/ */
package bisq.core.util.joptsimple; package bisq.common.config;
import joptsimple.ValueConverter; import joptsimple.ValueConverter;
@ -29,10 +29,11 @@ import static org.springframework.util.StringUtils.collectionToDelimitedString;
/** /**
* A {@link joptsimple.ValueConverter} that supports case-insensitive conversion from * A {@link joptsimple.ValueConverter} that supports case-insensitive conversion from
* String to an enum label. Useful in conjunction with {@link joptsimple.ArgumentAcceptingOptionSpec#ofType(Class)} * String to an enum label. Useful in conjunction with
* when the type in question is an enum. * {@link joptsimple.ArgumentAcceptingOptionSpec#ofType(Class)} when the type in question
* is an enum.
*/ */
public class EnumValueConverter implements ValueConverter<Enum> { class EnumValueConverter implements ValueConverter<Enum> {
private final Class<? extends Enum> enumType; private final Class<? extends Enum> enumType;

View file

@ -0,0 +1,26 @@
package bisq.common.config;
import joptsimple.HelpFormatter;
import joptsimple.OptionParser;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
public class HelpRequested extends RuntimeException {
private final OptionParser parser;
public HelpRequested(OptionParser parser) {
this.parser = parser;
}
public void printHelp(OutputStream sink, HelpFormatter formatter) {
try {
parser.formatHelpWith(formatter);
parser.printHelpOn(sink);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}

View file

@ -0,0 +1,26 @@
package bisq.common.config;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
public class TestConfig extends Config {
public TestConfig() throws HelpRequested {
super(generateTestAppName());
}
public TestConfig(String... args) {
super(generateTestAppName(), args);
}
private static String generateTestAppName() {
try {
File file = File.createTempFile("Bisq", "Test");
file.delete();
return file.toPath().getFileName().toString();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}

View file

@ -17,6 +17,11 @@
package bisq.common.crypto; package bisq.common.crypto;
import bisq.common.util.Utilities;
import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
@ -37,4 +42,11 @@ public class CryptoUtils {
new SecureRandom().nextBytes(bytes); new SecureRandom().nextBytes(bytes);
return bytes; return bytes;
} }
public static void checkCryptoPolicySetup() throws NoSuchAlgorithmException, LimitedKeyStrengthException {
if (Cipher.getMaxAllowedKeyLength("AES") > 128)
log.debug("Congratulations, you have unlimited key length support!");
else
throw new LimitedKeyStrengthException();
}
} }

View file

@ -18,6 +18,7 @@
package bisq.common.setup; package bisq.common.setup;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.crypto.CryptoUtils;
import bisq.common.crypto.LimitedKeyStrengthException; import bisq.common.crypto.LimitedKeyStrengthException;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -61,7 +62,7 @@ public class CommonSetup {
Thread.currentThread().setUncaughtExceptionHandler(handler); Thread.currentThread().setUncaughtExceptionHandler(handler);
try { try {
Utilities.checkCryptoPolicySetup(); CryptoUtils.checkCryptoPolicySetup();
} catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) { } catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) {
e.printStackTrace(); e.printStackTrace();
UserThread.execute(() -> uncaughtExceptionHandler.handleUncaughtException(e, true)); UserThread.execute(() -> uncaughtExceptionHandler.handleUncaughtException(e, true));

View file

@ -373,13 +373,6 @@ public class Utilities {
} }
} }
public static void checkCryptoPolicySetup() throws NoSuchAlgorithmException, LimitedKeyStrengthException {
if (Cipher.getMaxAllowedKeyLength("AES") > 128)
log.debug("Congratulations, you have unlimited key length support!");
else
throw new LimitedKeyStrengthException();
}
public static String toTruncatedString(Object message) { public static String toTruncatedString(Object message) {
return toTruncatedString(message, 200, true); return toTruncatedString(message, 200, true);
} }

View file

@ -0,0 +1,118 @@
package bisq.common.config;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class ConfigFileEditorTests {
private File file;
private PrintWriter writer;
private ConfigFileReader reader;
private ConfigFileEditor editor;
@Before
public void setUp() throws IOException {
file = File.createTempFile("bisq", "properties");
reader = new ConfigFileReader(file);
editor = new ConfigFileEditor(file);
writer = new PrintWriter(file);
}
@Test
public void whenFileDoesNotExist_thenSetOptionCreatesItAndAppendsOneLine() {
assertTrue(file.delete());
editor.setOption("opt1", "val1");
assertThat(reader.getLines(), contains("opt1=val1"));
}
@Test
public void whenFileContainsOptionBeingSet_thenSetOptionOverwritesIt() {
writer.println("opt1=val1");
writer.println("opt2=val2");
writer.println("opt3=val3");
writer.flush();
editor.setOption("opt2", "newval2");
assertThat(reader.getLines(), contains(
"opt1=val1",
"opt2=newval2",
"opt3=val3"));
}
@Test
public void whenOptionBeingSetHasNoArg_thenSetOptionWritesItWithNoEqualsSign() {
writer.println("opt1=val1");
writer.println("opt2=val2");
writer.flush();
editor.setOption("opt3");
assertThat(reader.getLines(), contains(
"opt1=val1",
"opt2=val2",
"opt3"));
}
@Test
public void whenFileHasBlankOrCommentLines_thenTheyArePreserved() {
writer.println("# Comment 1");
writer.println("opt1=val1");
writer.println();
writer.println("# Comment 2");
writer.println("opt2=val2");
writer.flush();
editor.setOption("opt3=val3");
assertThat(reader.getLines(), contains(
"# Comment 1",
"opt1=val1",
"",
"# Comment 2",
"opt2=val2",
"opt3=val3"));
}
@Test
public void whenFileContainsOptionBeingCleared_thenClearOptionRemovesIt() {
writer.println("opt1=val1");
writer.println("opt2=val2");
writer.flush();
editor.clearOption("opt2");
assertThat(reader.getLines(), contains("opt1=val1"));
}
@Test
public void whenFileDoesNotContainOptionBeingCleared_thenClearOptionIsNoOp() {
writer.println("opt1=val1");
writer.println("opt2=val2");
writer.flush();
editor.clearOption("opt3");
assertThat(reader.getLines(), contains(
"opt1=val1",
"opt2=val2"));
}
@Test
public void whenFileDoesNotExist_thenClearOptionIsNoOp() {
assertTrue(file.delete());
editor.clearOption("opt1");
assertFalse(file.exists());
}
}

View file

@ -0,0 +1,38 @@
package bisq.common.config;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
public class ConfigFileOptionTests {
@Test
public void whenOptionHasWhitespaceAroundEqualsSign_thenItGetsTrimmed() {
String value = "name1 = arg1";
ConfigFileOption option = ConfigFileOption.parse(value);
assertThat(option.name, equalTo("name1"));
assertThat(option.arg, equalTo("arg1"));
assertThat(option.toString(), equalTo("name1=arg1"));
}
@Test
public void whenOptionHasLeadingOrTrailingWhitespace_thenItGetsTrimmed() {
String value = " name1=arg1 ";
ConfigFileOption option = ConfigFileOption.parse(value);
assertThat(option.name, equalTo("name1"));
assertThat(option.arg, equalTo("arg1"));
assertThat(option.toString(), equalTo("name1=arg1"));
}
@Test
public void whenOptionHasEscapedColons_thenTheyGetUnescaped() {
String value = "host1=example.com\\:8080";
ConfigFileOption option = ConfigFileOption.parse(value);
assertThat(option.name, equalTo("host1"));
assertThat(option.arg, equalTo("example.com:8080"));
assertThat(option.toString(), equalTo("host1=example.com:8080"));
}
}

View file

@ -0,0 +1,78 @@
package bisq.common.config;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class ConfigFileReaderTests {
private File file;
private PrintWriter writer;
private ConfigFileReader reader;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws IOException {
file = File.createTempFile("bisq", "properties");
reader = new ConfigFileReader(file);
writer = new PrintWriter(file);
}
@Test
public void whenFileDoesNotExist_thenGetLinesThrows() {
assertTrue(file.delete());
exception.expect(IllegalArgumentException.class);
exception.expectMessage(containsString("Config file"));
exception.expectMessage(containsString("does not exist"));
reader.getLines();
}
@Test
public void whenOptionHasWhitespaceAroundEqualsSign_thenGetLinesPreservesIt() {
writer.println("name1 =arg1");
writer.println("name2= arg2");
writer.println("name3 = arg3");
writer.flush();
assertThat(reader.getLines(), contains(
"name1 =arg1",
"name2= arg2",
"name3 = arg3"));
}
@Test
public void whenOptionHasEscapedColons_thenTheyGetUnescaped() {
writer.println("host1=example.com\\:8080");
writer.println("host2=example.org:8080");
writer.flush();
assertThat(reader.getLines(), contains(
"host1=example.com:8080",
"host2=example.org:8080"));
}
@Test
public void whenFileContainsNonOptionLines_getOptionLinesReturnsOnlyOptionLines() {
writer.println("# Comment");
writer.println("");
writer.println("name1=arg1");
writer.println("noArgOpt");
writer.flush();
assertThat(reader.getOptionLines(), contains("name1=arg1", "noArgOpt"));
}
}

View file

@ -0,0 +1,160 @@
package bisq.common.config;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static bisq.common.config.Config.DEFAULT_CONFIG_FILE_NAME;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class ConfigTests {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
// Note: "DataDirProperties" in the test method names below represent the group of
// configuration options that influence the location of a Bisq node's data directory.
// These options include appName, userDataDir, appDataDir, and configFile
@Test
public void whenTestConfigNoArgCtorIsCalled_thenDefaultAppNameIsSetToRandomValue() {
Config config = new TestConfig();
String defaultAppName = config.getDefaultAppName();
String regex = "Bisq\\d{2,}Test";
assertTrue(format("Test app name '%s' failed to match '%s'", defaultAppName, regex),
defaultAppName.matches(regex));
}
@Test
public void whenStringConstructorIsCalled_thenDefaultAppNamePropertyIsAssignedToItsValue() {
Config config = new Config("Custom-Bisq");
assertThat(config.getDefaultAppName(), equalTo("Custom-Bisq"));
}
@Test
public void whenAppNameOptionIsSet_thenAppNamePropertyDiffersFromDefaultAppNameProperty() {
Config config = new TestConfig("--appName=My-Bisq");
assertThat(config.getAppName(), equalTo("My-Bisq"));
assertThat(config.getAppName(), not(equalTo(config.getDefaultAppName())));
}
@Test
public void whenNoOptionsAreSet_thenDataDirPropertiesEqualDefaultValues() {
Config config = new TestConfig();
assertThat(config.getAppName(), equalTo(config.getDefaultAppName()));
assertThat(config.getUserDataDir(), equalTo(config.getDefaultUserDataDir()));
assertThat(config.getAppDataDir(), equalTo(config.getDefaultAppDataDir()));
assertThat(config.getConfigFile(), equalTo(config.getDefaultConfigFile()));
}
@Test
public void whenAppNameOptionIsSet_thenDataDirPropertiesReflectItsValue() {
Config config = new TestConfig("--appName=My-Bisq");
assertThat(config.getAppName(), equalTo("My-Bisq"));
assertThat(config.getUserDataDir(), equalTo(config.getDefaultUserDataDir()));
assertThat(config.getAppDataDir(), equalTo(new File(config.getUserDataDir(), "My-Bisq")));
assertThat(config.getConfigFile(), equalTo(new File(config.getAppDataDir(), DEFAULT_CONFIG_FILE_NAME)));
}
@Test
public void whenAppDataDirOptionIsSet_thenDataDirPropertiesReflectItsValue() {
Config config = new TestConfig("--appDataDir=/mydata/myapp");
assertThat(config.getAppName(), equalTo(config.getDefaultAppName()));
assertThat(config.getUserDataDir(), equalTo(config.getDefaultUserDataDir()));
assertThat(config.getAppDataDir(), equalTo(new File("/mydata/myapp")));
assertThat(config.getConfigFile(), equalTo(new File(config.getAppDataDir(), DEFAULT_CONFIG_FILE_NAME)));
}
@Test
public void whenUserDataDirOptionIsSet_thenDataDirPropertiesReflectItsValue() {
Config config = new TestConfig("--userDataDir=/mydata");
assertThat(config.getAppName(), equalTo(config.getDefaultAppName()));
assertThat(config.getUserDataDir(), equalTo(new File("/mydata")));
assertThat(config.getAppDataDir(), equalTo(new File("/mydata", config.getDefaultAppName())));
assertThat(config.getConfigFile(), equalTo(new File(config.getAppDataDir(), DEFAULT_CONFIG_FILE_NAME)));
}
@Test
public void whenAppNameAndAppDataDirOptionsAreSet_thenDataDirPropertiesReflectTheirValues() {
Config config = new TestConfig("--appName=My-Bisq", "--appDataDir=/mydata/myapp");
assertThat(config.getAppName(), equalTo("My-Bisq"));
assertThat(config.getUserDataDir(), equalTo(config.getDefaultUserDataDir()));
assertThat(config.getAppDataDir(), equalTo(new File("/mydata/myapp")));
assertThat(config.getConfigFile(), equalTo(new File(config.getAppDataDir(), DEFAULT_CONFIG_FILE_NAME)));
}
@Test
public void whenConfFileOptionIsSetToNonExistentFile_thenConfFilePropertyFallsBackToDefaultValue() {
Config config = new TestConfig("--configFile=/tmp/bogus.properties");
assertThat(config.getConfigFile(), equalTo(new File(config.getAppDataDir(), DEFAULT_CONFIG_FILE_NAME)));
}
@Test
public void whenOptionIsSetAtCommandLineAndInConfigFile_thenCommandLineValueTakesPrecedence() throws IOException {
File configFile = File.createTempFile("bisq", "properties");
try (PrintWriter writer = new PrintWriter(configFile)) {
writer.println("appName=Bisq-configFileValue");
}
Config config = new TestConfig("--appName=Bisq-commandLineValue");
assertThat(config.getAppName(), equalTo("Bisq-commandLineValue"));
}
@Test
public void whenOptionFileArgumentDoesNotExist_thenThrowConfigException() {
exceptionRule.expect(ConfigException.class);
exceptionRule.expectMessage("problem parsing option 'torrcFile': File [/does/not/exist] does not exist");
new TestConfig("--torrcFile=/does/not/exist");
}
@Test
public void whenConfigFileOptionIsSetInConfigFile_thenDisallowedOptionExceptionisThrown() throws IOException {
File configFile = File.createTempFile("bisq", "properties");
try (PrintWriter writer = new PrintWriter(configFile)) {
writer.println("configFile=/tmp/other.bisq.properties");
}
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("The 'configFile' option is disallowed in config files");
new TestConfig("--configFile=" + configFile.getAbsolutePath());
}
@Test
public void whenConfigFileOptionIsSetToExistingFile_thenConfigFilePropertyReflectsItsValue() throws IOException {
File configFile = File.createTempFile("bisq", "properties");
Config config = new TestConfig("--configFile=" + configFile.getAbsolutePath());
assertThat(config.getConfigFile(), equalTo(configFile));
}
@Test
public void whenAppNameIsSetInConfigFile_thenDataDirPropertiesReflectItsValue() throws IOException {
File configFile = File.createTempFile("bisq", "properties");
try (PrintWriter writer = new PrintWriter(configFile)) {
writer.println("appName=My-Bisq");
}
Config config = new TestConfig("--configFile=" + configFile.getAbsolutePath());
assertThat(config.getAppName(), equalTo("My-Bisq"));
assertThat(config.getUserDataDir(), equalTo(config.getDefaultUserDataDir()));
assertThat(config.getAppDataDir(), equalTo(new File(config.getUserDataDir(), config.getAppName())));
assertThat(config.getConfigFile(), equalTo(configFile));
}
@Test
public void whenBannedBtcNodesOptionIsSet_thenBannedBtcNodesPropertyReturnsItsValue() {
Config config = new TestConfig("--bannedBtcNodes=foo.onion:8333,bar.onion:8333");
assertThat(config.getBannedBtcNodes(), contains("foo.onion:8333", "bar.onion:8333"));
}
@Test
public void whenHelpOptionIsSet_thenHelpRequestedIsThrown() {
exceptionRule.expect(HelpRequested.class);
new TestConfig("--help");
}
}

View file

@ -20,6 +20,7 @@ package bisq.core.alert;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -28,8 +29,9 @@ import com.google.inject.Singleton;
import static com.google.inject.name.Names.named; import static com.google.inject.name.Names.named;
public class AlertModule extends AppModule { public class AlertModule extends AppModule {
public AlertModule(Environment environment) {
super(environment); public AlertModule(Environment environment, Config config) {
super(environment, config);
} }
@Override @Override

View file

@ -19,6 +19,8 @@ package bisq.core.app;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.common.config.Config;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -43,12 +45,16 @@ import javax.sound.sampled.SourceDataLine;
@Slf4j @Slf4j
@Singleton @Singleton
public class AvoidStandbyModeService { public class AvoidStandbyModeService {
private final Preferences preferences; private final Preferences preferences;
private final Config config;
private volatile boolean isStopped; private volatile boolean isStopped;
@Inject @Inject
public AvoidStandbyModeService(Preferences preferences) { public AvoidStandbyModeService(Preferences preferences, Config config) {
this.preferences = preferences; this.preferences = preferences;
this.config = config;
preferences.getUseStandbyModeProperty().addListener((observable, oldValue, newValue) -> { preferences.getUseStandbyModeProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) { if (newValue) {
@ -80,7 +86,7 @@ public class AvoidStandbyModeService {
InputStream inputStream = null; InputStream inputStream = null;
try { try {
inputStream = getClass().getClassLoader().getResourceAsStream("prevent-app-nap-silent-sound.aiff"); inputStream = getClass().getClassLoader().getResourceAsStream("prevent-app-nap-silent-sound.aiff");
File soundFile = new File(BisqEnvironment.getStaticAppDataDir(), "prevent-app-nap-silent-sound.aiff"); File soundFile = new File(config.getAppDataDir(), "prevent-app-nap-silent-sound.aiff");
if (!soundFile.exists()) { if (!soundFile.exists()) {
outputStream = new FileOutputStream(soundFile); outputStream = new FileOutputStream(soundFile);
IOUtils.copy(inputStream, outputStream); IOUtils.copy(inputStream, outputStream);

View file

@ -17,25 +17,21 @@
package bisq.core.app; package bisq.core.app;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.btc.BtcOptionKeys; import bisq.core.btc.BtcOptionKeys;
import bisq.core.btc.UserAgent; import bisq.core.btc.UserAgent;
import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.DaoOptionKeys;
import bisq.core.exceptions.BisqException;
import bisq.core.filter.FilterManager;
import bisq.network.NetworkOptionKeys; import bisq.network.NetworkOptionKeys;
import bisq.network.p2p.network.ConnectionConfig; import bisq.network.p2p.network.ConnectionConfig;
import bisq.common.BisqException;
import bisq.common.CommonOptionKeys; import bisq.common.CommonOptionKeys;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.crypto.KeyStorage; import bisq.common.crypto.KeyStorage;
import bisq.common.storage.Storage; import bisq.common.storage.Storage;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
import org.bitcoinj.core.NetworkParameters;
import org.springframework.core.env.Environment;
import org.springframework.core.env.JOptCommandLinePropertySource; import org.springframework.core.env.JOptCommandLinePropertySource;
import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertiesPropertySource;
@ -48,19 +44,13 @@ import org.springframework.core.io.support.ResourcePropertySource;
import joptsimple.OptionSet; import joptsimple.OptionSet;
import org.apache.commons.lang3.StringUtils;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties; import java.util.Properties;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
@ -69,8 +59,6 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j @Slf4j
@ -80,11 +68,7 @@ public class BisqEnvironment extends StandardEnvironment {
// Static // Static
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static void setDefaultAppName(String defaultAppName) { static final String DEFAULT_APP_NAME = "Bisq";
DEFAULT_APP_NAME = defaultAppName;
}
public static String DEFAULT_APP_NAME = "Bisq";
public static final String DEFAULT_USER_DATA_DIR = defaultUserDataDir(); public static final String DEFAULT_USER_DATA_DIR = defaultUserDataDir();
public static final String DEFAULT_APP_DATA_DIR = appDataDir(DEFAULT_USER_DATA_DIR, DEFAULT_APP_NAME); public static final String DEFAULT_APP_DATA_DIR = appDataDir(DEFAULT_USER_DATA_DIR, DEFAULT_APP_NAME);
@ -95,27 +79,6 @@ public class BisqEnvironment extends StandardEnvironment {
public static final String BISQ_APP_DIR_PROPERTY_SOURCE_NAME = "bisqAppDirProperties"; public static final String BISQ_APP_DIR_PROPERTY_SOURCE_NAME = "bisqAppDirProperties";
public static final String BISQ_DEFAULT_PROPERTY_SOURCE_NAME = "bisqDefaultProperties"; public static final String BISQ_DEFAULT_PROPERTY_SOURCE_NAME = "bisqDefaultProperties";
private static String staticAppDataDir;
public static String getStaticAppDataDir() {
return staticAppDataDir;
}
@SuppressWarnings("SameReturnValue")
public static BaseCurrencyNetwork getDefaultBaseCurrencyNetwork() {
return BaseCurrencyNetwork.BTC_MAINNET;
}
protected static BaseCurrencyNetwork baseCurrencyNetwork = getDefaultBaseCurrencyNetwork();
public static NetworkParameters getParameters() {
return getBaseCurrencyNetwork().getParameters();
}
public static BaseCurrencyNetwork getBaseCurrencyNetwork() {
return baseCurrencyNetwork;
}
private static String defaultUserDataDir() { private static String defaultUserDataDir() {
if (Utilities.isWindows()) if (Utilities.isWindows())
return System.getenv("APPDATA"); return System.getenv("APPDATA");
@ -161,14 +124,6 @@ public class BisqEnvironment extends StandardEnvironment {
return Paths.get(userDataDir, appName).toString(); return Paths.get(userDataDir, appName).toString();
} }
// Util to set isDaoActivated to true if either set as program argument or we run testnet or regtest.
// Can be removed once DAO is live.
public static boolean isDaoActivated(Environment environment) {
Boolean daoActivatedFromOptions = environment.getProperty(DaoOptionKeys.DAO_ACTIVATED, Boolean.class, true);
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork();
return daoActivatedFromOptions || !baseCurrencyNetwork.isMainnet();
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields // Instance fields
@ -185,8 +140,6 @@ public class BisqEnvironment extends StandardEnvironment {
@Getter @Getter
@Setter @Setter
protected boolean isBitcoinLocalhostNodeRunning; protected boolean isBitcoinLocalhostNodeRunning;
@Getter
protected List<String> bannedSeedNodes, bannedBtcNodes, bannedPriceRelayNodes;
protected final String btcNodes, seedNodes, ignoreDevMsg, useDevPrivilegeKeys, useDevMode, useTorForBtc, rpcUser, rpcPassword, protected final String btcNodes, seedNodes, ignoreDevMsg, useDevPrivilegeKeys, useDevMode, useTorForBtc, rpcUser, rpcPassword,
rpcHost, rpcPort, rpcBlockNotificationPort, rpcBlockNotificationHost, dumpBlockchainData, fullDaoNode, rpcHost, rpcPort, rpcBlockNotificationPort, rpcBlockNotificationHost, dumpBlockchainData, fullDaoNode,
@ -215,7 +168,6 @@ public class BisqEnvironment extends StandardEnvironment {
userDataDir = getProperty(commandLineProperties, AppOptionKeys.USER_DATA_DIR_KEY, DEFAULT_USER_DATA_DIR); userDataDir = getProperty(commandLineProperties, AppOptionKeys.USER_DATA_DIR_KEY, DEFAULT_USER_DATA_DIR);
appName = getProperty(commandLineProperties, AppOptionKeys.APP_NAME_KEY, DEFAULT_APP_NAME); appName = getProperty(commandLineProperties, AppOptionKeys.APP_NAME_KEY, DEFAULT_APP_NAME);
appDataDir = getProperty(commandLineProperties, AppOptionKeys.APP_DATA_DIR_KEY, appDataDir(userDataDir, appName)); appDataDir = getProperty(commandLineProperties, AppOptionKeys.APP_DATA_DIR_KEY, appDataDir(userDataDir, appName));
staticAppDataDir = appDataDir;
ignoreDevMsg = getProperty(commandLineProperties, AppOptionKeys.IGNORE_DEV_MSG_KEY, ""); ignoreDevMsg = getProperty(commandLineProperties, AppOptionKeys.IGNORE_DEV_MSG_KEY, "");
useDevPrivilegeKeys = getProperty(commandLineProperties, AppOptionKeys.USE_DEV_PRIVILEGE_KEYS, ""); useDevPrivilegeKeys = getProperty(commandLineProperties, AppOptionKeys.USE_DEV_PRIVILEGE_KEYS, "");
@ -271,14 +223,11 @@ public class BisqEnvironment extends StandardEnvironment {
try { try {
propertySources.addLast(getAppDirProperties()); propertySources.addLast(getAppDirProperties());
bannedPriceRelayNodes = getListProperty(FilterManager.BANNED_PRICE_RELAY_NODES, null); BaseCurrencyNetwork.CURRENT_NETWORK = BaseCurrencyNetwork.valueOf(getProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK,
bannedSeedNodes = getListProperty(FilterManager.BANNED_SEED_NODES, new ArrayList<>()); BaseCurrencyNetwork.BTC_MAINNET.name()).toUpperCase());
bannedBtcNodes = getListProperty(FilterManager.BANNED_BTC_NODES, null); BaseCurrencyNetwork.CURRENT_PARAMETERS = BaseCurrencyNetwork.CURRENT_NETWORK.getParameters();
baseCurrencyNetwork = BaseCurrencyNetwork.valueOf(getProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK, btcNetworkDir = Paths.get(appDataDir, BaseCurrencyNetwork.CURRENT_NETWORK.name().toLowerCase()).toString();
getDefaultBaseCurrencyNetwork().name()).toUpperCase());
btcNetworkDir = Paths.get(appDataDir, baseCurrencyNetwork.name().toLowerCase()).toString();
File btcNetworkDirFile = new File(btcNetworkDir); File btcNetworkDirFile = new File(btcNetworkDir);
if (!btcNetworkDirFile.exists()) if (!btcNetworkDirFile.exists())
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
@ -291,58 +240,6 @@ public class BisqEnvironment extends StandardEnvironment {
} }
} }
public void saveBaseCryptoNetwork(BaseCurrencyNetwork baseCurrencyNetwork) {
BisqEnvironment.baseCurrencyNetwork = baseCurrencyNetwork;
setProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK, baseCurrencyNetwork.name());
}
public void saveBannedSeedNodes(@Nullable List<String> bannedNodes) {
setProperty(FilterManager.BANNED_SEED_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes));
}
public void saveBannedBtcNodes(@Nullable List<String> bannedNodes) {
setProperty(FilterManager.BANNED_BTC_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes));
}
public void saveBannedPriceRelayNodes(@Nullable List<String> bannedNodes) {
setProperty(FilterManager.BANNED_PRICE_RELAY_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes));
}
protected void setProperty(String key, String value) {
try {
Resource resource = getAppDirPropertiesResource();
File file = resource.getFile();
Properties properties = new Properties();
if (file.exists()) {
Object propertiesObject = getAppDirProperties().getSource();
if (propertiesObject instanceof Properties) {
properties = (Properties) propertiesObject;
} else {
log.warn("propertiesObject not instance of Properties");
}
}
if (!value.isEmpty())
properties.setProperty(key, value);
else
properties.remove(key);
log.debug("properties=" + properties);
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
properties.store(fileOutputStream, null);
} catch (IOException e1) {
log.error(e1.toString());
e1.printStackTrace();
throw new RuntimeException(e1);
}
} catch (Exception e2) {
log.error(e2.toString());
e2.printStackTrace();
throw new RuntimeException(e2);
}
}
private Resource getAppDirPropertiesResource() { private Resource getAppDirPropertiesResource() {
String location = String.format("file:%s/bisq.properties", appDataDir); String location = String.format("file:%s/bisq.properties", appDataDir);
return resourceLoader.getResource(location); return resourceLoader.getResource(location);
@ -361,11 +258,6 @@ public class BisqEnvironment extends StandardEnvironment {
return properties.containsProperty(propertyKey) ? (String) properties.getProperty(propertyKey) : defaultValue; return properties.containsProperty(propertyKey) ? (String) properties.getProperty(propertyKey) : defaultValue;
} }
private List<String> getListProperty(String key, List<String> defaultValue) {
final String value = getProperty(key, "");
return value.isEmpty() ? defaultValue : Arrays.asList(StringUtils.deleteWhitespace(value).split(","));
}
private PropertySource<?> defaultProperties() { private PropertySource<?> defaultProperties() {
return new PropertiesPropertySource(BISQ_DEFAULT_PROPERTY_SOURCE_NAME, new Properties() { return new PropertiesPropertySource(BISQ_DEFAULT_PROPERTY_SOURCE_NAME, new Properties() {
{ {
@ -375,7 +267,7 @@ public class BisqEnvironment extends StandardEnvironment {
setProperty(NetworkOptionKeys.SEED_NODES_KEY, seedNodes); setProperty(NetworkOptionKeys.SEED_NODES_KEY, seedNodes);
setProperty(NetworkOptionKeys.BAN_LIST, banList); setProperty(NetworkOptionKeys.BAN_LIST, banList);
setProperty(NetworkOptionKeys.TOR_DIR, Paths.get(btcNetworkDir, "tor").toString()); setProperty(NetworkOptionKeys.TOR_DIR, Paths.get(btcNetworkDir, "tor").toString());
setProperty(NetworkOptionKeys.NETWORK_ID, String.valueOf(baseCurrencyNetwork.ordinal())); setProperty(NetworkOptionKeys.NETWORK_ID, String.valueOf(BaseCurrencyNetwork.CURRENT_NETWORK.ordinal()));
setProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS, socks5ProxyBtcAddress); setProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS, socks5ProxyBtcAddress);
setProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS, socks5ProxyHttpAddress); setProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS, socks5ProxyHttpAddress);
setProperty(NetworkOptionKeys.TORRC_FILE, torRcFile); setProperty(NetworkOptionKeys.TORRC_FILE, torRcFile);

View file

@ -24,7 +24,6 @@ import bisq.core.btc.wallet.BsqWalletService;
import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.DaoOptionKeys;
import bisq.core.dao.DaoSetup; import bisq.core.dao.DaoSetup;
import bisq.core.exceptions.BisqException;
import bisq.core.offer.OpenOfferManager; import bisq.core.offer.OpenOfferManager;
import bisq.core.setup.CorePersistedDataHost; import bisq.core.setup.CorePersistedDataHost;
import bisq.core.setup.CoreSetup; import bisq.core.setup.CoreSetup;
@ -35,10 +34,16 @@ import bisq.network.NetworkOptionKeys;
import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PService;
import bisq.network.p2p.network.ConnectionConfig; import bisq.network.p2p.network.ConnectionConfig;
import bisq.common.BisqException;
import bisq.common.CommonOptionKeys; import bisq.common.CommonOptionKeys;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.BisqHelpFormatter;
import bisq.common.config.Config;
import bisq.common.config.ConfigException;
import bisq.common.config.HelpRequested;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.PersistedDataHost;
import bisq.common.setup.GracefulShutDownHandler; import bisq.common.setup.GracefulShutDownHandler;
@ -59,70 +64,55 @@ import com.google.inject.name.Names;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import static bisq.core.app.BisqEnvironment.DEFAULT_APP_NAME; import static bisq.common.config.BaseCurrencyNetwork.*;
import static bisq.core.app.BisqEnvironment.DEFAULT_USER_DATA_DIR; import static bisq.core.app.BisqEnvironment.BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME;
import static bisq.core.btc.BaseCurrencyNetwork.*;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; import static java.lang.String.format;
@Slf4j @Slf4j
public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSetup.BisqSetupListener { public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSetup.BisqSetupListener {
private static final int EXIT_SUCCESS = 0;
private static final int EXIT_FAILURE = 1;
private static final String HELP_KEY = "help";
private final String fullName; private final String fullName;
private final String scriptName; private final String scriptName;
private final String appName;
private final String version; private final String version;
protected Injector injector; protected Injector injector;
protected AppModule module; protected AppModule module;
protected BisqEnvironment bisqEnvironment; protected BisqEnvironment bisqEnvironment;
protected Config config;
public BisqExecutable(String fullName, String scriptName, String version) { public BisqExecutable(String fullName, String scriptName, String appName, String version) {
this.fullName = fullName; this.fullName = fullName;
this.scriptName = scriptName; this.scriptName = scriptName;
this.appName = appName;
this.version = version; this.version = version;
} }
public static boolean setupInitialOptionParser(String[] args) throws IOException { public void execute(String[] args) throws Exception {
// We don't want to do the full argument parsing here as that might easily change in update versions
// So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
OptionParser parser = new OptionParser();
parser.allowsUnrecognizedOptions();
parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY,
format("User data directory (default: %s)", DEFAULT_USER_DATA_DIR))
.withRequiredArg();
parser.accepts(AppOptionKeys.APP_NAME_KEY,
format("Application name (default: %s)", DEFAULT_APP_NAME))
.withRequiredArg();
OptionSet options;
try { try {
options = parser.parse(args); config = new Config(appName, args);
} catch (OptionException ex) { } catch (HelpRequested helpRequested) {
helpRequested.printHelp(System.out, new BisqHelpFormatter(fullName, scriptName, version));
System.exit(EXIT_SUCCESS);
} catch (ConfigException ex) {
System.err.println("error: " + ex.getMessage()); System.err.println("error: " + ex.getMessage());
System.exit(EXIT_FAILURE); System.exit(EXIT_FAILURE);
return false;
}
BisqEnvironment bisqEnvironment = getBisqEnvironment(options);
// need to call that before BisqAppMain().execute(args)
BisqExecutable.initAppDir(bisqEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));
return true;
} }
initAppDir(config.getAppDataDir());
private static final int EXIT_SUCCESS = 0;
public static final int EXIT_FAILURE = 1;
private static final String HELP_KEY = "help";
public void execute(String[] args) throws Exception {
OptionParser parser = new OptionParser(); OptionParser parser = new OptionParser();
parser.formatHelpWith(new BisqHelpFormatter(fullName, scriptName, version)); parser.formatHelpWith(new BisqHelpFormatter(fullName, scriptName, version));
parser.accepts(HELP_KEY, "This help text").forHelp(); parser.accepts(HELP_KEY, "This help text").forHelp();
@ -151,9 +141,10 @@ public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSet
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
protected void doExecute(OptionSet options) { protected void doExecute(OptionSet options) {
setupEnvironment(options); bisqEnvironment = new BisqEnvironment(
new JOptCommandLinePropertySource(BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull(options)));
configUserThread(); configUserThread();
configCoreSetup(options); CoreSetup.setup(config);
addCapabilities(); addCapabilities();
// If application is JavaFX application we need to wait until it is initialized // If application is JavaFX application we need to wait until it is initialized
@ -162,36 +153,6 @@ public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSet
protected abstract void configUserThread(); protected abstract void configUserThread();
protected void setupEnvironment(OptionSet options) {
/*
* JOptSimple does support input parsing. However, doing only options = parser.parse(args) isn't enough to trigger the parsing.
* The parsing is done when the actual value is going to be retrieved, i.e. options.valueOf(attributename).
*
* In order to keep usability high, we work around the aforementioned characteristics by catching the exception below
* (valueOf is called somewhere in getBisqEnvironment), thus, neatly inform the user of an ill-formed parameter and stop execution.
*
* Might be changed when the project features more user parameters meant for the user.
*/
try {
bisqEnvironment = getBisqEnvironment(options);
} catch (OptionException e) {
// unfortunately, the OptionArgumentConversionException is not visible so we cannot catch only those.
// hence, workaround
if (e.getCause() != null)
// get something like "Error while parsing application parameter '--torrcFile': File [/path/to/file] does not exist"
System.err.println("Error while parsing application parameter '--" + e.options().get(0) + "': " + e.getCause().getMessage());
else
System.err.println("Error while parsing application parameter '--" + e.options().get(0));
// we only tried to load some config until now, so no graceful shutdown is required
System.exit(1);
}
}
protected void configCoreSetup(OptionSet options) {
CoreSetup.setup(getBisqEnvironment(options));
}
protected void addCapabilities() { protected void addCapabilities() {
} }
@ -235,7 +196,7 @@ public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSet
protected void setupDevEnv() { protected void setupDevEnv() {
DevEnv.setDevMode(injector.getInstance(Key.get(Boolean.class, Names.named(CommonOptionKeys.USE_DEV_MODE)))); DevEnv.setDevMode(injector.getInstance(Key.get(Boolean.class, Names.named(CommonOptionKeys.USE_DEV_MODE))));
DevEnv.setDaoActivated(BisqEnvironment.isDaoActivated(bisqEnvironment)); DevEnv.setDaoActivated(config.isDaoActivated());
} }
protected void setupPersistedDataHosts(Injector injector) { protected void setupPersistedDataHosts(Injector injector) {
@ -474,7 +435,7 @@ public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSet
//BtcOptionKeys //BtcOptionKeys
parser.accepts(BtcOptionKeys.BASE_CURRENCY_NETWORK, parser.accepts(BtcOptionKeys.BASE_CURRENCY_NETWORK,
format("Base currency network (default: %s)", BisqEnvironment.getDefaultBaseCurrencyNetwork().name())) format("Base currency network (default: %s)", BTC_MAINNET.name()))
.withRequiredArg() .withRequiredArg()
.ofType(String.class) .ofType(String.class)
.describedAs(format("%s|%s|%s|%s", BTC_MAINNET, BTC_TESTNET, BTC_REGTEST, BTC_DAO_TESTNET, BTC_DAO_BETANET, BTC_DAO_REGTEST)); .describedAs(format("%s|%s|%s|%s", BTC_MAINNET, BTC_TESTNET, BTC_REGTEST, BTC_DAO_TESTNET, BTC_DAO_BETANET, BTC_DAO_REGTEST));
@ -570,12 +531,8 @@ public abstract class BisqExecutable implements GracefulShutDownHandler, BisqSet
.ofType(boolean.class); .ofType(boolean.class);
} }
public static BisqEnvironment getBisqEnvironment(OptionSet options) { private void initAppDir(File appDataDir) {
return new BisqEnvironment(new JOptCommandLinePropertySource(BisqEnvironment.BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull(options))); Path dir = appDataDir.toPath();
}
public static void initAppDir(String appDir) {
Path dir = Paths.get(appDir);
if (Files.exists(dir)) { if (Files.exists(dir)) {
if (!Files.isWritable(dir)) if (!Files.isWritable(dir))
throw new BisqException("Application data directory '%s' is not writeable", dir); throw new BisqException("Application data directory '%s' is not writeable", dir);

View file

@ -36,18 +36,18 @@ public class BisqHeadlessAppMain extends BisqExecutable {
protected HeadlessApp headlessApp; protected HeadlessApp headlessApp;
public BisqHeadlessAppMain() { public BisqHeadlessAppMain() {
super("Bisq Daemon", "bisqd", Version.VERSION); super("Bisq Daemon", "bisqd", "Bisq", Version.VERSION);
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (BisqExecutable.setupInitialOptionParser(args)) { // For some reason the JavaFX launch process results in us losing the thread
// For some reason the JavaFX launch process results in us losing the thread context class loader: reset it. // context class loader: reset it. In order to work around a bug in JavaFX 8u25
// In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method: // and below, you must include the following code as the first line of your
// realMain method:
Thread.currentThread().setContextClassLoader(BisqHeadlessAppMain.class.getClassLoader()); Thread.currentThread().setContextClassLoader(BisqHeadlessAppMain.class.getClassLoader());
new BisqHeadlessAppMain().execute(args); new BisqHeadlessAppMain().execute(args);
} }
}
@Override @Override
protected void doExecute(OptionSet options) { protected void doExecute(OptionSet options) {
@ -95,7 +95,7 @@ public class BisqHeadlessAppMain extends BisqExecutable {
@Override @Override
protected AppModule getModule() { protected AppModule getModule() {
return new CoreModule(bisqEnvironment); return new CoreModule(bisqEnvironment, config);
} }
@Override @Override

View file

@ -75,6 +75,8 @@ import bisq.common.Timer;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.app.Log; import bisq.common.app.Log;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.common.crypto.CryptoException; import bisq.common.crypto.CryptoException;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import bisq.common.crypto.SealedAndSigned; import bisq.common.crypto.SealedAndSigned;
@ -175,7 +177,7 @@ public class BisqSetup {
private final UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService; private final UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService;
private final EncryptionService encryptionService; private final EncryptionService encryptionService;
private final KeyRing keyRing; private final KeyRing keyRing;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final AccountAgeWitnessService accountAgeWitnessService; private final AccountAgeWitnessService accountAgeWitnessService;
private final SignedWitnessService signedWitnessService; private final SignedWitnessService signedWitnessService;
private final MobileNotificationService mobileNotificationService; private final MobileNotificationService mobileNotificationService;
@ -265,7 +267,7 @@ public class BisqSetup {
UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService, UnconfirmedBsqChangeOutputListService unconfirmedBsqChangeOutputListService,
EncryptionService encryptionService, EncryptionService encryptionService,
KeyRing keyRing, KeyRing keyRing,
BisqEnvironment bisqEnvironment, Config config,
AccountAgeWitnessService accountAgeWitnessService, AccountAgeWitnessService accountAgeWitnessService,
SignedWitnessService signedWitnessService, SignedWitnessService signedWitnessService,
MobileNotificationService mobileNotificationService, MobileNotificationService mobileNotificationService,
@ -312,7 +314,7 @@ public class BisqSetup {
this.unconfirmedBsqChangeOutputListService = unconfirmedBsqChangeOutputListService; this.unconfirmedBsqChangeOutputListService = unconfirmedBsqChangeOutputListService;
this.encryptionService = encryptionService; this.encryptionService = encryptionService;
this.keyRing = keyRing; this.keyRing = keyRing;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.accountAgeWitnessService = accountAgeWitnessService; this.accountAgeWitnessService = accountAgeWitnessService;
this.signedWitnessService = signedWitnessService; this.signedWitnessService = signedWitnessService;
this.mobileNotificationService = mobileNotificationService; this.mobileNotificationService = mobileNotificationService;
@ -481,19 +483,19 @@ public class BisqSetup {
} }
private void checkIfLocalHostNodeIsRunning() { private void checkIfLocalHostNodeIsRunning() {
BaseCurrencyNetwork baseCurrencyNetwork = config.getBaseCurrencyNetwork();
// For DAO testnet we ignore local btc node // For DAO testnet we ignore local btc node
if (BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() || if (baseCurrencyNetwork.isDaoRegTest() || baseCurrencyNetwork.isDaoTestNet() ||
BisqEnvironment.getBaseCurrencyNetwork().isDaoTestNet() || config.isIgnoreLocalBtcNode()) {
bisqEnvironment.isIgnoreLocalBtcNode()) {
step3(); step3();
} else { } else {
new Thread(() -> { new Thread(() -> {
try (Socket socket = new Socket()) { try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000); baseCurrencyNetwork.getParameters().getPort()), 5000);
log.info("Localhost Bitcoin node detected."); log.info("Localhost Bitcoin node detected.");
UserThread.execute(() -> { UserThread.execute(() -> {
bisqEnvironment.setBitcoinLocalhostNodeRunning(true); config.setLocalBitcoinNodeIsRunning(true);
step3(); step3();
}); });
} catch (Throwable e) { } catch (Throwable e) {
@ -504,7 +506,7 @@ public class BisqSetup {
} }
private void readMapsFromResources() { private void readMapsFromResources() {
SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> { SetupUtils.readFromResources(p2PService.getP2PDataStorage(), config).addListener((observable, oldValue, newValue) -> {
if (newValue) if (newValue)
step4(); step4();
}); });
@ -570,7 +572,7 @@ public class BisqSetup {
// We only init wallet service here if not using Tor for bitcoinj. // We only init wallet service here if not using Tor for bitcoinj.
// When using Tor, wallet init must be deferred until Tor is ready. // When using Tor, wallet init must be deferred until Tor is ready.
if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) { if (!preferences.getUseTorForBitcoinJ() || config.isLocalBitcoinNodeIsRunning()) {
initWallet(); initWallet();
} }
@ -873,7 +875,7 @@ public class BisqSetup {
} }
private void maybeShowLocalhostRunningInfo() { private void maybeShowLocalhostRunningInfo() {
maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler, bisqEnvironment.isBitcoinLocalhostNodeRunning()); maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler, config.isLocalBitcoinNodeIsRunning());
} }
private void maybeShowAccountSigningStateInfo() { private void maybeShowAccountSigningStateInfo() {

View file

@ -19,6 +19,9 @@ package bisq.core.app;
import bisq.core.alert.AlertModule; import bisq.core.alert.AlertModule;
import bisq.core.btc.BitcoinModule; import bisq.core.btc.BitcoinModule;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.core.dao.DaoModule; import bisq.core.dao.DaoModule;
import bisq.core.filter.FilterModule; import bisq.core.filter.FilterModule;
import bisq.core.network.p2p.seed.DefaultSeedNodeRepository; import bisq.core.network.p2p.seed.DefaultSeedNodeRepository;
@ -56,13 +59,14 @@ import static com.google.inject.name.Names.named;
public class CoreModule extends AppModule { public class CoreModule extends AppModule {
public CoreModule(Environment environment) { public CoreModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override
protected void configure() { protected void configure() {
bind(BisqEnvironment.class).toInstance((BisqEnvironment) environment); bind(BisqEnvironment.class).toInstance((BisqEnvironment) environment);
bind(Config.class).toInstance(config);
bind(BridgeAddressProvider.class).to(Preferences.class); bind(BridgeAddressProvider.class).to(Preferences.class);
@ -71,7 +75,7 @@ public class CoreModule extends AppModule {
File storageDir = new File(environment.getRequiredProperty(Storage.STORAGE_DIR)); File storageDir = new File(environment.getRequiredProperty(Storage.STORAGE_DIR));
bind(File.class).annotatedWith(named(Storage.STORAGE_DIR)).toInstance(storageDir); bind(File.class).annotatedWith(named(Storage.STORAGE_DIR)).toInstance(storageDir);
CoinFormatter btcFormatter = new ImmutableCoinFormatter(BisqEnvironment.getParameters().getMonetaryFormat()); CoinFormatter btcFormatter = new ImmutableCoinFormatter(BaseCurrencyNetwork.CURRENT_PARAMETERS.getMonetaryFormat());
bind(CoinFormatter.class).annotatedWith(named(FormattingUtils.BTC_FORMATTER_KEY)).toInstance(btcFormatter); bind(CoinFormatter.class).annotatedWith(named(FormattingUtils.BTC_FORMATTER_KEY)).toInstance(btcFormatter);
File keyStorageDir = new File(environment.getRequiredProperty(KeyStorage.KEY_STORAGE_DIR)); File keyStorageDir = new File(environment.getRequiredProperty(KeyStorage.KEY_STORAGE_DIR));
@ -91,51 +95,15 @@ public class CoreModule extends AppModule {
// ordering is used for shut down sequence // ordering is used for shut down sequence
install(tradeModule()); install(new TradeModule(environment, config));
install(encryptionServiceModule()); install(new EncryptionServiceModule(environment, config));
install(offerModule()); install(new OfferModule(environment, config));
install(p2pModule()); install(new P2PModule(environment, config));
install(bitcoinModule()); install(new BitcoinModule(environment, config));
install(daoModule()); install(new DaoModule(environment, config));
install(alertModule()); install(new AlertModule(environment, config));
install(filterModule()); install(new FilterModule(environment, config));
install(corePresentationModule()); install(new CorePresentationModule(environment, config));
bind(PubKeyRing.class).toProvider(PubKeyRingProvider.class); bind(PubKeyRing.class).toProvider(PubKeyRingProvider.class);
} }
private TradeModule tradeModule() {
return new TradeModule(environment);
}
private EncryptionServiceModule encryptionServiceModule() {
return new EncryptionServiceModule(environment);
}
private AlertModule alertModule() {
return new AlertModule(environment);
}
private FilterModule filterModule() {
return new FilterModule(environment);
}
private OfferModule offerModule() {
return new OfferModule(environment);
}
private P2PModule p2pModule() {
return new P2PModule(environment);
}
private BitcoinModule bitcoinModule() {
return new BitcoinModule(environment);
}
private DaoModule daoModule() {
return new DaoModule(environment);
}
private CorePresentationModule corePresentationModule() {
return new CorePresentationModule(environment);
}
} }

View file

@ -17,7 +17,7 @@
package bisq.core.app; package bisq.core.app;
import bisq.core.btc.BaseCurrencyNetwork; import bisq.common.config.BaseCurrencyNetwork;
import bisq.network.crypto.DecryptedDataTuple; import bisq.network.crypto.DecryptedDataTuple;
import bisq.network.crypto.EncryptionService; import bisq.network.crypto.EncryptionService;
@ -25,6 +25,7 @@ import bisq.network.p2p.peers.keepalive.messages.Ping;
import bisq.network.p2p.storage.P2PDataStorage; import bisq.network.p2p.storage.P2PDataStorage;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.Config;
import bisq.common.crypto.CryptoException; import bisq.common.crypto.CryptoException;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import bisq.common.crypto.SealedAndSigned; import bisq.common.crypto.SealedAndSigned;
@ -75,11 +76,11 @@ public class SetupUtils {
checkCryptoThread.start(); checkCryptoThread.start();
} }
public static BooleanProperty readFromResources(P2PDataStorage p2PDataStorage) { public static BooleanProperty readFromResources(P2PDataStorage p2PDataStorage, Config config) {
BooleanProperty result = new SimpleBooleanProperty(); BooleanProperty result = new SimpleBooleanProperty();
new Thread(() -> { new Thread(() -> {
// Used to load different files per base currency (EntryMap_BTC_MAINNET, EntryMap_LTC,...) // Used to load different files per base currency (EntryMap_BTC_MAINNET, EntryMap_LTC,...)
final BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); final BaseCurrencyNetwork baseCurrencyNetwork = config.getBaseCurrencyNetwork();
final String postFix = "_" + baseCurrencyNetwork.name(); final String postFix = "_" + baseCurrencyNetwork.name();
long ts = new Date().getTime(); long ts = new Date().getTime();
p2PDataStorage.readFromResources(postFix); p2PDataStorage.readFromResources(postFix);

View file

@ -25,6 +25,8 @@ import bisq.core.locale.Res;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.core.util.FormattingUtils; import bisq.core.util.FormattingUtils;
import bisq.common.config.Config;
import org.bitcoinj.core.VersionMessage; import org.bitcoinj.core.VersionMessage;
import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.ChainFileLockedException; import org.bitcoinj.store.ChainFileLockedException;
@ -55,9 +57,10 @@ import javax.annotation.Nullable;
@Slf4j @Slf4j
@Singleton @Singleton
public class WalletAppSetup { public class WalletAppSetup {
private final WalletsManager walletsManager; private final WalletsManager walletsManager;
private final WalletsSetup walletsSetup; private final WalletsSetup walletsSetup;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final Preferences preferences; private final Preferences preferences;
@SuppressWarnings("FieldCanBeLocal") @SuppressWarnings("FieldCanBeLocal")
@ -81,11 +84,11 @@ public class WalletAppSetup {
@Inject @Inject
public WalletAppSetup(WalletsManager walletsManager, public WalletAppSetup(WalletsManager walletsManager,
WalletsSetup walletsSetup, WalletsSetup walletsSetup,
BisqEnvironment bisqEnvironment, Config config,
Preferences preferences) { Preferences preferences) {
this.walletsManager = walletsManager; this.walletsManager = walletsManager;
this.walletsSetup = walletsSetup; this.walletsSetup = walletsSetup;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.preferences = preferences; this.preferences = preferences;
this.useTorForBTC.set(preferences.getUseTorForBitcoinJ()); this.useTorForBTC.set(preferences.getUseTorForBitcoinJ());
} }
@ -182,12 +185,12 @@ public class WalletAppSetup {
private String getBtcNetworkAsString() { private String getBtcNetworkAsString() {
String postFix; String postFix;
if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) if (config.isIgnoreLocalBtcNode())
postFix = " " + Res.get("mainView.footer.localhostBitcoinNode"); postFix = " " + Res.get("mainView.footer.localhostBitcoinNode");
else if (preferences.getUseTorForBitcoinJ()) else if (preferences.getUseTorForBitcoinJ())
postFix = " " + Res.get("mainView.footer.usingTor"); postFix = " " + Res.get("mainView.footer.usingTor");
else else
postFix = ""; postFix = "";
return Res.get(BisqEnvironment.getBaseCurrencyNetwork().name()) + postFix; return Res.get(config.getBaseCurrencyNetwork().name()) + postFix;
} }
} }

View file

@ -17,12 +17,12 @@
package bisq.core.app.misc; package bisq.core.app.misc;
import bisq.core.app.BisqEnvironment;
import bisq.core.app.SetupUtils; import bisq.core.app.SetupUtils;
import bisq.network.crypto.EncryptionService; import bisq.network.crypto.EncryptionService;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import javax.inject.Inject; import javax.inject.Inject;
@ -33,15 +33,18 @@ import lombok.extern.slf4j.Slf4j;
public abstract class AppSetup { public abstract class AppSetup {
protected final EncryptionService encryptionService; protected final EncryptionService encryptionService;
protected final KeyRing keyRing; protected final KeyRing keyRing;
protected final Config config;
@Inject @Inject
public AppSetup(EncryptionService encryptionService, public AppSetup(EncryptionService encryptionService,
KeyRing keyRing) { KeyRing keyRing,
Config config) {
// we need to reference it so the seed node stores tradeStatistics // we need to reference it so the seed node stores tradeStatistics
this.encryptionService = encryptionService; this.encryptionService = encryptionService;
this.keyRing = keyRing; this.keyRing = keyRing;
this.config = config;
Version.setBaseCryptoNetworkId(BisqEnvironment.getBaseCurrencyNetwork().ordinal()); Version.setBaseCryptoNetworkId(this.config.getBaseCurrencyNetwork().ordinal());
Version.printVersion(); Version.printVersion();
} }

View file

@ -31,6 +31,7 @@ import bisq.network.p2p.network.CloseConnectionReason;
import bisq.network.p2p.network.Connection; import bisq.network.p2p.network.Connection;
import bisq.network.p2p.network.ConnectionListener; import bisq.network.p2p.network.ConnectionListener;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.PersistedDataHost;
@ -62,8 +63,9 @@ public class AppSetupWithP2P extends AppSetup {
AccountAgeWitnessService accountAgeWitnessService, AccountAgeWitnessService accountAgeWitnessService,
SignedWitnessService signedWitnessService, SignedWitnessService signedWitnessService,
FilterManager filterManager, FilterManager filterManager,
TorSetup torSetup) { TorSetup torSetup,
super(encryptionService, keyRing); Config config) {
super(encryptionService, keyRing, config);
this.p2PService = p2PService; this.p2PService = p2PService;
this.tradeStatisticsManager = tradeStatisticsManager; this.tradeStatisticsManager = tradeStatisticsManager;
this.accountAgeWitnessService = accountAgeWitnessService; this.accountAgeWitnessService = accountAgeWitnessService;
@ -90,7 +92,7 @@ public class AppSetupWithP2P extends AppSetup {
@Override @Override
protected void initBasicServices() { protected void initBasicServices() {
SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> { SetupUtils.readFromResources(p2PService.getP2PDataStorage(), config).addListener((observable, oldValue, newValue) -> {
if (newValue) if (newValue)
startInitP2PNetwork(); startInitP2PNetwork();
}); });

View file

@ -20,7 +20,6 @@ package bisq.core.app.misc;
import bisq.core.account.sign.SignedWitnessService; import bisq.core.account.sign.SignedWitnessService;
import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.app.TorSetup; import bisq.core.app.TorSetup;
import bisq.core.dao.DaoOptionKeys;
import bisq.core.dao.DaoSetup; import bisq.core.dao.DaoSetup;
import bisq.core.dao.governance.ballot.BallotListService; import bisq.core.dao.governance.ballot.BallotListService;
import bisq.core.dao.governance.blindvote.MyBlindVoteListService; import bisq.core.dao.governance.blindvote.MyBlindVoteListService;
@ -34,10 +33,10 @@ import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.network.crypto.EncryptionService; import bisq.network.crypto.EncryptionService;
import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PService;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -61,7 +60,7 @@ public class AppSetupWithP2PAndDAO extends AppSetupWithP2P {
MyReputationListService myReputationListService, MyReputationListService myReputationListService,
MyProofOfBurnListService myProofOfBurnListService, MyProofOfBurnListService myProofOfBurnListService,
TorSetup torSetup, TorSetup torSetup,
@Named(DaoOptionKeys.DAO_ACTIVATED) boolean daoActivated) { Config config) {
super(encryptionService, super(encryptionService,
keyRing, keyRing,
p2PService, p2PService,
@ -69,12 +68,13 @@ public class AppSetupWithP2PAndDAO extends AppSetupWithP2P {
accountAgeWitnessService, accountAgeWitnessService,
signedWitnessService, signedWitnessService,
filterManager, filterManager,
torSetup); torSetup,
config);
this.daoSetup = daoSetup; this.daoSetup = daoSetup;
// TODO Should be refactored/removed. In the meantime keep in sync with CorePersistedDataHost // TODO Should be refactored/removed. In the meantime keep in sync with CorePersistedDataHost
if (daoActivated) { if (config.isDaoActivated()) {
persistedDataHosts.add(myVoteListService); persistedDataHosts.add(myVoteListService);
persistedDataHosts.add(ballotListService); persistedDataHosts.add(ballotListService);
persistedDataHosts.add(myBlindVoteListService); persistedDataHosts.add(myBlindVoteListService);

View file

@ -29,6 +29,7 @@ import bisq.core.support.dispute.arbitration.arbitrator.ArbitratorManager;
import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PService;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.Config;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
import bisq.common.setup.GracefulShutDownHandler; import bisq.common.setup.GracefulShutDownHandler;
import bisq.common.setup.UncaughtExceptionHandler; import bisq.common.setup.UncaughtExceptionHandler;
@ -55,8 +56,8 @@ public abstract class ExecutableForAppWithP2p extends BisqExecutable implements
private final long startTime = System.currentTimeMillis(); private final long startTime = System.currentTimeMillis();
private static long maxMemory = MAX_MEMORY_MB_DEFAULT; private static long maxMemory = MAX_MEMORY_MB_DEFAULT;
public ExecutableForAppWithP2p(String fullName, String scriptName, String version) { public ExecutableForAppWithP2p(String fullName, String scriptName, String appName, String version) {
super(fullName, scriptName, version); super(fullName, scriptName, appName, version);
} }
@Override @Override
@ -189,12 +190,12 @@ public abstract class ExecutableForAppWithP2p extends BisqExecutable implements
}); });
} }
protected void restart(BisqEnvironment bisqEnvironment, GracefulShutDownHandler gracefulShutDownHandler) { protected void restart(Config config, GracefulShutDownHandler gracefulShutDownHandler) {
stopped = true; stopped = true;
gracefulShutDownHandler.gracefulShutDown(() -> { gracefulShutDownHandler.gracefulShutDown(() -> {
//noinspection finally //noinspection finally
try { try {
final String[] tokens = bisqEnvironment.getAppDataDir().split("_"); final String[] tokens = config.getAppDataDir().getPath().split("_");
String logPath = "error_" + (tokens.length > 1 ? tokens[tokens.length - 2] : "") + ".log"; String logPath = "error_" + (tokens.length > 1 ? tokens[tokens.length - 2] : "") + ".log";
RestartUtil.restartApplication(logPath); RestartUtil.restartApplication(logPath);
} catch (IOException e) { } catch (IOException e) {

View file

@ -40,6 +40,7 @@ import bisq.network.p2p.seed.SeedNodeRepository;
import bisq.common.ClockWatcher; import bisq.common.ClockWatcher;
import bisq.common.CommonOptionKeys; import bisq.common.CommonOptionKeys;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import bisq.common.crypto.KeyStorage; import bisq.common.crypto.KeyStorage;
import bisq.common.crypto.PubKeyRing; import bisq.common.crypto.PubKeyRing;
@ -59,13 +60,14 @@ import static com.google.inject.name.Names.named;
public class ModuleForAppWithP2p extends AppModule { public class ModuleForAppWithP2p extends AppModule {
public ModuleForAppWithP2p(Environment environment) { public ModuleForAppWithP2p(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override
protected void configure() { protected void configure() {
configEnvironment(); bind(BisqEnvironment.class).toInstance((BisqEnvironment) environment);
bind(Config.class).toInstance(config);
bind(KeyStorage.class).in(Singleton.class); bind(KeyStorage.class).in(Singleton.class);
bind(KeyRing.class).in(Singleton.class); bind(KeyRing.class).in(Singleton.class);
@ -95,51 +97,14 @@ public class ModuleForAppWithP2p extends AppModule {
bind(String.class).annotatedWith(Names.named(AppOptionKeys.REFERRAL_ID)).toInstance(referralId); bind(String.class).annotatedWith(Names.named(AppOptionKeys.REFERRAL_ID)).toInstance(referralId);
// ordering is used for shut down sequence // ordering is used for shut down sequence
install(tradeModule()); install(new TradeModule(environment, config));
install(encryptionServiceModule()); install(new EncryptionServiceModule(environment, config));
install(offerModule()); install(new OfferModule(environment, config));
install(p2pModule()); install(new P2PModule(environment, config));
install(bitcoinModule()); install(new BitcoinModule(environment, config));
install(daoModule()); install(new DaoModule(environment, config));
install(alertModule()); install(new AlertModule(environment, config));
install(filterModule()); install(new FilterModule(environment, config));
bind(PubKeyRing.class).toProvider(PubKeyRingProvider.class); bind(PubKeyRing.class).toProvider(PubKeyRingProvider.class);
}
protected void configEnvironment() {
bind(BisqEnvironment.class).toInstance((BisqEnvironment) environment);
}
protected TradeModule tradeModule() {
return new TradeModule(environment);
}
protected EncryptionServiceModule encryptionServiceModule() {
return new EncryptionServiceModule(environment);
}
protected AlertModule alertModule() {
return new AlertModule(environment);
}
protected FilterModule filterModule() {
return new FilterModule(environment);
}
protected OfferModule offerModule() {
return new OfferModule(environment);
}
protected P2PModule p2pModule() {
return new P2PModule(environment);
}
protected BitcoinModule bitcoinModule() {
return new BitcoinModule(environment);
}
protected DaoModule daoModule() {
return new DaoModule(environment);
} }
} }

View file

@ -18,7 +18,6 @@
package bisq.core.btc; package bisq.core.btc;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.model.AddressEntryList; import bisq.core.btc.model.AddressEntryList;
import bisq.core.btc.nodes.BtcNodes; import bisq.core.btc.nodes.BtcNodes;
import bisq.core.btc.setup.RegTestHost; import bisq.core.btc.setup.RegTestHost;
@ -35,6 +34,7 @@ import bisq.core.provider.fee.FeeService;
import bisq.core.provider.price.PriceFeedService; import bisq.core.provider.price.PriceFeedService;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -48,19 +48,20 @@ import java.util.Arrays;
import static com.google.inject.name.Names.named; import static com.google.inject.name.Names.named;
public class BitcoinModule extends AppModule { public class BitcoinModule extends AppModule {
public BitcoinModule(Environment environment) {
super(environment); public BitcoinModule(Environment environment, Config config) {
super(environment, config);
} }
@Override @Override
protected void configure() { protected void configure() {
// If we have selected BTC_DAO_REGTEST or BTC_DAO_TESTNET we use our master regtest node, // If we have selected BTC_DAO_REGTEST or BTC_DAO_TESTNET we use our master regtest node,
// otherwise the specified host or default (localhost) // otherwise the specified host or default (localhost)
String regTestHost = environment.getProperty(BtcOptionKeys.REG_TEST_HOST, String.class, ""); String regTestHost = config.getBitcoinRegtestHost();
if (regTestHost.isEmpty()) { if (regTestHost.isEmpty()) {
regTestHost = BisqEnvironment.getBaseCurrencyNetwork().isDaoTestNet() ? regTestHost = config.getBaseCurrencyNetwork().isDaoTestNet() ?
"104.248.31.39" : "104.248.31.39" :
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? config.getBaseCurrencyNetwork().isDaoRegTest() ?
"134.209.242.206" : "134.209.242.206" :
RegTestHost.DEFAULT_HOST; RegTestHost.DEFAULT_HOST;
} }

View file

@ -17,8 +17,7 @@
package bisq.core.btc.model; package bisq.core.btc.model;
import bisq.core.app.BisqEnvironment; import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.proto.ProtoUtil; import bisq.common.proto.ProtoUtil;
import bisq.common.proto.persistable.PersistablePayload; import bisq.common.proto.persistable.PersistablePayload;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -175,7 +174,7 @@ public final class AddressEntry implements PersistablePayload {
@Nullable @Nullable
public Address getAddress() { public Address getAddress() {
if (address == null && keyPair != null) if (address == null && keyPair != null)
address = keyPair.toAddress(BisqEnvironment.getParameters()); address = keyPair.toAddress(BaseCurrencyNetwork.CURRENT_PARAMETERS);
return address; return address;
} }

View file

@ -17,11 +17,12 @@
package bisq.core.btc.nodes; package bisq.core.btc.nodes;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.setup.WalletConfig; import bisq.core.btc.setup.WalletConfig;
import bisq.network.Socks5MultiDiscovery; import bisq.network.Socks5MultiDiscovery;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerAddress;
import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.MainNetParams;
@ -68,7 +69,7 @@ public class BtcNetworkConfig {
} }
// SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time. // SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
delegate.setDiscovery(new Socks5MultiDiscovery(proxy, parameters, socks5DiscoverMode)); delegate.setDiscovery(new Socks5MultiDiscovery(proxy, parameters, socks5DiscoverMode));
} else if (BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) { } else if (BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet()) {
log.warn("You don't use tor and use the public Bitcoin network and are exposed to privacy issues " + log.warn("You don't use tor and use the public Bitcoin network and are exposed to privacy issues " +
"caused by the broken bloom filters. See https://bisq.network/blog/privacy-in-bitsquare/ " + "caused by the broken bloom filters. See https://bisq.network/blog/privacy-in-bitsquare/ " +
"for more info. It is recommended to use Tor and the provided nodes."); "for more info. It is recommended to use Tor and the provided nodes.");

View file

@ -17,7 +17,7 @@
package bisq.core.btc.nodes; package bisq.core.btc.nodes;
import bisq.core.app.BisqEnvironment; import bisq.common.config.BaseCurrencyNetwork;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -87,7 +87,7 @@ public class BtcNodes {
} }
public boolean useProvidedBtcNodes() { public boolean useProvidedBtcNodes() {
return BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); return BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet();
} }
public static List<BtcNodes.BtcNode> toBtcNodesList(Collection<String> nodes) { public static List<BtcNodes.BtcNode> toBtcNodesList(Collection<String> nodes) {
@ -100,7 +100,7 @@ public class BtcNodes {
@EqualsAndHashCode @EqualsAndHashCode
@Getter @Getter
public static class BtcNode { public static class BtcNode {
private static final int DEFAULT_PORT = BisqEnvironment.getParameters().getPort(); //8333 private static final int DEFAULT_PORT = BaseCurrencyNetwork.CURRENT_PARAMETERS.getPort(); //8333
@Nullable @Nullable
private final String onionAddress; private final String onionAddress;

View file

@ -17,11 +17,12 @@
package bisq.core.btc.setup; package bisq.core.btc.setup;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.nodes.ProxySocketFactory; import bisq.core.btc.nodes.ProxySocketFactory;
import bisq.core.btc.wallet.BisqRiskAnalysis; import bisq.core.btc.wallet.BisqRiskAnalysis;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.CheckpointManager; import org.bitcoinj.core.CheckpointManager;
@ -113,7 +114,7 @@ public class WalletConfig extends AbstractIdleService {
private final String spvChainFileName; private final String spvChainFileName;
private final Socks5Proxy socks5Proxy; private final Socks5Proxy socks5Proxy;
private final BisqWalletFactory walletFactory; private final BisqWalletFactory walletFactory;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final String userAgent; private final String userAgent;
private int numConnectionForBtc; private int numConnectionForBtc;
@ -150,13 +151,13 @@ public class WalletConfig extends AbstractIdleService {
public WalletConfig(NetworkParameters params, public WalletConfig(NetworkParameters params,
Socks5Proxy socks5Proxy, Socks5Proxy socks5Proxy,
File directory, File directory,
BisqEnvironment bisqEnvironment, Config config,
String userAgent, String userAgent,
int numConnectionForBtc, int numConnectionForBtc,
@SuppressWarnings("SameParameterValue") String btcWalletFileName, @SuppressWarnings("SameParameterValue") String btcWalletFileName,
@SuppressWarnings("SameParameterValue") String bsqWalletFileName, @SuppressWarnings("SameParameterValue") String bsqWalletFileName,
@SuppressWarnings("SameParameterValue") String spvChainFileName) { @SuppressWarnings("SameParameterValue") String spvChainFileName) {
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.userAgent = userAgent; this.userAgent = userAgent;
this.numConnectionForBtc = numConnectionForBtc; this.numConnectionForBtc = numConnectionForBtc;
this.context = new Context(params); this.context = new Context(params);
@ -224,7 +225,7 @@ public class WalletConfig extends AbstractIdleService {
ProxySocketFactory proxySocketFactory = new ProxySocketFactory(proxy); ProxySocketFactory proxySocketFactory = new ProxySocketFactory(proxy);
// We don't use tor mode if we have a local node running // We don't use tor mode if we have a local node running
BlockingClientManager blockingClientManager = bisqEnvironment.isBitcoinLocalhostNodeRunning() ? BlockingClientManager blockingClientManager = config.isIgnoreLocalBtcNode() ?
new BlockingClientManager() : new BlockingClientManager() :
new BlockingClientManager(proxySocketFactory); new BlockingClientManager(proxySocketFactory);
@ -236,9 +237,9 @@ public class WalletConfig extends AbstractIdleService {
// For dao testnet (server side regtest) we prevent to connect to a localhost node to avoid confusion // For dao testnet (server side regtest) we prevent to connect to a localhost node to avoid confusion
// if local btc node is not synced with our dao testnet master node. // if local btc node is not synced with our dao testnet master node.
if (BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() || if (BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ||
BisqEnvironment.getBaseCurrencyNetwork().isDaoTestNet() || BaseCurrencyNetwork.CURRENT_NETWORK.isDaoTestNet() ||
!bisqEnvironment.isBitcoinLocalhostNodeRunning()) !config.isLocalBitcoinNodeIsRunning())
peerGroup.setUseLocalhostPeerWhenPossible(false); peerGroup.setUseLocalhostPeerWhenPossible(false);
return peerGroup; return peerGroup;

View file

@ -17,7 +17,6 @@
package bisq.core.btc.setup; package bisq.core.btc.setup;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BtcOptionKeys; import bisq.core.btc.BtcOptionKeys;
import bisq.core.btc.exceptions.InvalidHostException; import bisq.core.btc.exceptions.InvalidHostException;
import bisq.core.btc.exceptions.RejectedTxException; import bisq.core.btc.exceptions.RejectedTxException;
@ -35,6 +34,8 @@ import bisq.network.Socks5ProxyProvider;
import bisq.common.Timer; import bisq.common.Timer;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.common.handlers.ExceptionHandler; import bisq.common.handlers.ExceptionHandler;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
import bisq.common.storage.FileUtil; import bisq.common.storage.FileUtil;
@ -120,7 +121,7 @@ public class WalletsSetup {
private final AddressEntryList addressEntryList; private final AddressEntryList addressEntryList;
private final Preferences preferences; private final Preferences preferences;
private final Socks5ProxyProvider socks5ProxyProvider; private final Socks5ProxyProvider socks5ProxyProvider;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final BtcNodes btcNodes; private final BtcNodes btcNodes;
private final String btcWalletFileName; private final String btcWalletFileName;
private final int numConnectionForBtc; private final int numConnectionForBtc;
@ -147,7 +148,7 @@ public class WalletsSetup {
AddressEntryList addressEntryList, AddressEntryList addressEntryList,
Preferences preferences, Preferences preferences,
Socks5ProxyProvider socks5ProxyProvider, Socks5ProxyProvider socks5ProxyProvider,
BisqEnvironment bisqEnvironment, Config config,
BtcNodes btcNodes, BtcNodes btcNodes,
@Named(BtcOptionKeys.USER_AGENT) String userAgent, @Named(BtcOptionKeys.USER_AGENT) String userAgent,
@Named(BtcOptionKeys.WALLET_DIR) File appDir, @Named(BtcOptionKeys.WALLET_DIR) File appDir,
@ -158,7 +159,7 @@ public class WalletsSetup {
this.addressEntryList = addressEntryList; this.addressEntryList = addressEntryList;
this.preferences = preferences; this.preferences = preferences;
this.socks5ProxyProvider = socks5ProxyProvider; this.socks5ProxyProvider = socks5ProxyProvider;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.btcNodes = btcNodes; this.btcNodes = btcNodes;
this.numConnectionForBtc = numConnectionForBtc != null ? Integer.parseInt(numConnectionForBtc) : DEFAULT_CONNECTIONS; this.numConnectionForBtc = numConnectionForBtc != null ? Integer.parseInt(numConnectionForBtc) : DEFAULT_CONNECTIONS;
this.useAllProvidedNodes = "true".equals(useAllProvidedNodes); this.useAllProvidedNodes = "true".equals(useAllProvidedNodes);
@ -166,8 +167,8 @@ public class WalletsSetup {
this.socks5DiscoverMode = evaluateMode(socks5DiscoverModeString); this.socks5DiscoverMode = evaluateMode(socks5DiscoverModeString);
btcWalletFileName = "bisq_" + BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode() + ".wallet"; btcWalletFileName = "bisq_" + config.getBaseCurrencyNetwork().getCurrencyCode() + ".wallet";
params = BisqEnvironment.getParameters(); params = BaseCurrencyNetwork.CURRENT_PARAMETERS;
walletDir = new File(appDir, "wallet"); walletDir = new File(appDir, "wallet");
PeerGroup.setIgnoreHttpSeeds(true); PeerGroup.setIgnoreHttpSeeds(true);
} }
@ -199,7 +200,7 @@ public class WalletsSetup {
walletConfig = new WalletConfig(params, walletConfig = new WalletConfig(params,
socks5Proxy, socks5Proxy,
walletDir, walletDir,
bisqEnvironment, config,
userAgent, userAgent,
numConnectionForBtc, numConnectionForBtc,
btcWalletFileName, btcWalletFileName,
@ -277,7 +278,7 @@ public class WalletsSetup {
return; return;
} }
} }
} else if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) { } else if (config.isLocalBitcoinNodeIsRunning()) {
walletConfig.setMinBroadcastConnections(1); walletConfig.setMinBroadcastConnections(1);
walletConfig.setPeerNodesForLocalHost(); walletConfig.setPeerNodesForLocalHost();
} else { } else {
@ -494,10 +495,6 @@ public class WalletsSetup {
return downloadPercentageProperty().get() == 1d; return downloadPercentageProperty().get() == 1d;
} }
public boolean isBitcoinLocalhostNodeRunning() {
return bisqEnvironment.isBitcoinLocalhostNodeRunning();
}
public Set<Address> getAddressesByContext(@SuppressWarnings("SameParameterValue") AddressEntry.Context context) { public Set<Address> getAddressesByContext(@SuppressWarnings("SameParameterValue") AddressEntry.Context context) {
return ImmutableList.copyOf(addressEntryList.getList()).stream() return ImmutableList.copyOf(addressEntryList.getList()).stream()
.filter(addressEntry -> addressEntry.getContext() == context) .filter(addressEntry -> addressEntry.getContext() == context)

View file

@ -17,7 +17,7 @@
package bisq.core.btc.wallet; package bisq.core.btc.wallet;
import bisq.core.app.BisqEnvironment; import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
@ -33,7 +33,7 @@ public class Restrictions {
public static Coin getMinNonDustOutput() { public static Coin getMinNonDustOutput() {
if (minNonDustOutput == null) if (minNonDustOutput == null)
minNonDustOutput = BisqEnvironment.getBaseCurrencyNetwork().getParameters().getMinNonDustOutput(); minNonDustOutput = BaseCurrencyNetwork.CURRENT_NETWORK.getParameters().getMinNonDustOutput();
return minNonDustOutput; return minNonDustOutput;
} }

View file

@ -17,7 +17,6 @@
package bisq.core.btc.wallet; package bisq.core.btc.wallet;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.exceptions.SigningException; import bisq.core.btc.exceptions.SigningException;
import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.TransactionVerificationException;
import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.exceptions.WalletException;
@ -30,6 +29,8 @@ import bisq.core.btc.setup.WalletsSetup;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Address; import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
@ -92,7 +93,7 @@ public class TradeWalletService {
public TradeWalletService(WalletsSetup walletsSetup, Preferences preferences) { public TradeWalletService(WalletsSetup walletsSetup, Preferences preferences) {
this.walletsSetup = walletsSetup; this.walletsSetup = walletsSetup;
this.preferences = preferences; this.preferences = preferences;
this.params = BisqEnvironment.getParameters(); this.params = BaseCurrencyNetwork.CURRENT_PARAMETERS;
walletsSetup.addSetupCompletedHandler(() -> { walletsSetup.addSetupCompletedHandler(() -> {
walletConfig = walletsSetup.getWalletConfig(); walletConfig = walletsSetup.getWalletConfig();
wallet = walletsSetup.getBtcWallet(); wallet = walletsSetup.getBtcWallet();

View file

@ -17,7 +17,6 @@
package bisq.core.btc.wallet; package bisq.core.btc.wallet;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.TransactionVerificationException;
import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.exceptions.WalletException;
import bisq.core.btc.listeners.AddressConfidenceListener; import bisq.core.btc.listeners.AddressConfidenceListener;
@ -27,6 +26,7 @@ import bisq.core.btc.setup.WalletsSetup;
import bisq.core.provider.fee.FeeService; import bisq.core.provider.fee.FeeService;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
@ -677,13 +677,13 @@ public abstract class WalletService {
@Nullable @Nullable
public static Address getAddressFromOutput(TransactionOutput output) { public static Address getAddressFromOutput(TransactionOutput output) {
return isOutputScriptConvertibleToAddress(output) ? return isOutputScriptConvertibleToAddress(output) ?
output.getScriptPubKey().getToAddress(BisqEnvironment.getParameters()) : null; output.getScriptPubKey().getToAddress(BaseCurrencyNetwork.CURRENT_PARAMETERS) : null;
} }
@Nullable @Nullable
public static String getAddressStringFromOutput(TransactionOutput output) { public static String getAddressStringFromOutput(TransactionOutput output) {
return isOutputScriptConvertibleToAddress(output) ? return isOutputScriptConvertibleToAddress(output) ?
output.getScriptPubKey().getToAddress(BisqEnvironment.getParameters()).toString() : null; output.getScriptPubKey().getToAddress(BaseCurrencyNetwork.CURRENT_PARAMETERS).toString() : null;
} }

View file

@ -87,6 +87,7 @@ import bisq.core.dao.state.model.DaoState;
import bisq.core.dao.state.unconfirmed.UnconfirmedBsqChangeOutputListService; import bisq.core.dao.state.unconfirmed.UnconfirmedBsqChangeOutputListService;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -97,8 +98,8 @@ import static com.google.inject.name.Names.named;
public class DaoModule extends AppModule { public class DaoModule extends AppModule {
public DaoModule(Environment environment) { public DaoModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override
@ -236,7 +237,7 @@ public class DaoModule extends AppModule {
bindConstant().annotatedWith(named(DaoOptionKeys.FULL_DAO_NODE)) bindConstant().annotatedWith(named(DaoOptionKeys.FULL_DAO_NODE))
.to(environment.getRequiredProperty(DaoOptionKeys.FULL_DAO_NODE)); .to(environment.getRequiredProperty(DaoOptionKeys.FULL_DAO_NODE));
bind(Boolean.class).annotatedWith(Names.named(DaoOptionKeys.DAO_ACTIVATED)).toInstance(BisqEnvironment.isDaoActivated(environment)); bind(Boolean.class).annotatedWith(Names.named(DaoOptionKeys.DAO_ACTIVATED)).toInstance(config.isDaoActivated());
} }
} }

View file

@ -17,7 +17,6 @@
package bisq.core.dao.governance.blindvote; package bisq.core.dao.governance.blindvote;
import bisq.core.dao.DaoOptionKeys;
import bisq.core.dao.DaoSetupService; import bisq.core.dao.DaoSetupService;
import bisq.core.dao.governance.blindvote.storage.BlindVotePayload; import bisq.core.dao.governance.blindvote.storage.BlindVotePayload;
import bisq.core.dao.governance.blindvote.storage.BlindVoteStorageService; import bisq.core.dao.governance.blindvote.storage.BlindVoteStorageService;
@ -31,8 +30,9 @@ import bisq.network.p2p.storage.payload.PersistableNetworkPayload;
import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreListener; import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreListener;
import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreService; import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreService;
import bisq.common.config.Config;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
@ -68,14 +68,14 @@ public class BlindVoteListService implements AppendOnlyDataStoreListener, DaoSta
BlindVoteStorageService blindVoteStorageService, BlindVoteStorageService blindVoteStorageService,
AppendOnlyDataStoreService appendOnlyDataStoreService, AppendOnlyDataStoreService appendOnlyDataStoreService,
BlindVoteValidator blindVoteValidator, BlindVoteValidator blindVoteValidator,
@Named(DaoOptionKeys.DAO_ACTIVATED) boolean daoActivated) { Config config) {
this.daoStateService = daoStateService; this.daoStateService = daoStateService;
this.p2PService = p2PService; this.p2PService = p2PService;
this.periodService = periodService; this.periodService = periodService;
this.blindVoteStorageService = blindVoteStorageService; this.blindVoteStorageService = blindVoteStorageService;
this.blindVoteValidator = blindVoteValidator; this.blindVoteValidator = blindVoteValidator;
if (daoActivated) if (config.isDaoActivated())
appendOnlyDataStoreService.addService(blindVoteStorageService); appendOnlyDataStoreService.addService(blindVoteStorageService);
} }

View file

@ -17,7 +17,6 @@
package bisq.core.dao.governance.blindvote; package bisq.core.dao.governance.blindvote;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.TransactionVerificationException;
import bisq.core.btc.exceptions.TxBroadcastException; import bisq.core.btc.exceptions.TxBroadcastException;
import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.exceptions.WalletException;
@ -48,6 +47,7 @@ import bisq.network.p2p.P2PService;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.crypto.CryptoException; import bisq.common.crypto.CryptoException;
import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ExceptionHandler; import bisq.common.handlers.ExceptionHandler;
@ -368,9 +368,9 @@ public class MyBlindVoteListService implements PersistedDataHost, DaoStateListen
// Republishing only will have effect if the payload creation date is < 5 hours as other nodes would not // Republishing only will have effect if the payload creation date is < 5 hours as other nodes would not
// accept payloads which are too old or are in future. // accept payloads which are too old or are in future.
// Only payloads received from seed nodes would ignore that date check. // Only payloads received from seed nodes would ignore that date check.
int minPeers = BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? 4 : 1; int minPeers = BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ? 4 : 1;
if ((p2PService.getNumConnectedPeers().get() >= minPeers && p2PService.isBootstrapped()) || if ((p2PService.getNumConnectedPeers().get() >= minPeers && p2PService.isBootstrapped()) ||
BisqEnvironment.getBaseCurrencyNetwork().isRegtest()) { BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest()) {
myBlindVoteList.stream() myBlindVoteList.stream()
.filter(blindVote -> periodService.isTxInPhaseAndCycle(blindVote.getTxId(), .filter(blindVote -> periodService.isTxInPhaseAndCycle(blindVote.getTxId(),
DaoPhase.Phase.BLIND_VOTE, DaoPhase.Phase.BLIND_VOTE,

View file

@ -17,9 +17,9 @@
package bisq.core.dao.governance.param; package bisq.core.dao.governance.param;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.proto.ProtoUtil; import bisq.common.proto.ProtoUtil;
import lombok.Getter; import lombok.Getter;
@ -106,9 +106,9 @@ public enum Param {
// the time locked payout tx in case the traders do not cooperate. Will be likely a donation address (Bisq, Tor,...) // the time locked payout tx in case the traders do not cooperate. Will be likely a donation address (Bisq, Tor,...)
// but can be also a burner address if we prefer to burn the BTC // but can be also a burner address if we prefer to burn the BTC
@SuppressWarnings("SpellCheckingInspection") @SuppressWarnings("SpellCheckingInspection")
RECIPIENT_BTC_ADDRESS(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? "1BVxNn3T12veSK6DgqwU4Hdn7QHcDDRag7" : // mainnet RECIPIENT_BTC_ADDRESS(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ? "1BVxNn3T12veSK6DgqwU4Hdn7QHcDDRag7" : // mainnet
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? "1BVxNn3T12veSK6DgqwU4Hdn7QHcDDRag7" : // daoBetaNet BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ? "1BVxNn3T12veSK6DgqwU4Hdn7QHcDDRag7" : // daoBetaNet
BisqEnvironment.getBaseCurrencyNetwork().isTestnet() ? "2N4mVTpUZAnhm9phnxB7VrHB4aBhnWrcUrV" : // testnet BaseCurrencyNetwork.CURRENT_NETWORK.isTestnet() ? "2N4mVTpUZAnhm9phnxB7VrHB4aBhnWrcUrV" : // testnet
"2MzBNTJDjjXgViKBGnatDU3yWkJ8pJkEg9w", // regtest or DAO testnet (regtest) "2MzBNTJDjjXgViKBGnatDU3yWkJ8pJkEg9w", // regtest or DAO testnet (regtest)
ParamType.ADDRESS), ParamType.ADDRESS),
@ -136,73 +136,73 @@ public enum Param {
// For testnet we want to have a short cycle of about a week (1012 blocks) // For testnet we want to have a short cycle of about a week (1012 blocks)
// For regtest we use very short periods // For regtest we use very short periods
PHASE_UNDEFINED("0", ParamType.BLOCK), PHASE_UNDEFINED("0", ParamType.BLOCK),
PHASE_PROPOSAL(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_PROPOSAL(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"3601" : // mainnet; 24 days "3601" : // mainnet; 24 days
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"4" : // regtest "4" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"144" : // daoBetaNet; 1 day "144" : // daoBetaNet; 1 day
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"134" : // dao regtest; 0.93 days "134" : // dao regtest; 0.93 days
"380", // testnet or dao testnet (server side regtest); 2.6 days "380", // testnet or dao testnet (server side regtest); 2.6 days
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_BREAK1(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_BREAK1(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"149" : // mainnet; 1 day "149" : // mainnet; 1 day
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"1" : // regtest "1" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"10" : // daoBetaNet "10" : // daoBetaNet
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"10" : // dao regtest "10" : // dao regtest
"10", // testnet or dao testnet (server side regtest) "10", // testnet or dao testnet (server side regtest)
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_BLIND_VOTE(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_BLIND_VOTE(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"451" : // mainnet; 3 days "451" : // mainnet; 3 days
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"2" : // regtest "2" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"144" : // daoBetaNet; 1 day "144" : // daoBetaNet; 1 day
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"134" : // dao regtest; 0.93 days "134" : // dao regtest; 0.93 days
"300", // testnet or dao testnet (server side regtest); 2 days "300", // testnet or dao testnet (server side regtest); 2 days
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_BREAK2(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_BREAK2(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"9" : // mainnet "9" : // mainnet
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"1" : // regtest "1" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"10" : // daoBetaNet "10" : // daoBetaNet
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"10" : // dao regtest "10" : // dao regtest
"10", // testnet or dao testnet (server side regtest) "10", // testnet or dao testnet (server side regtest)
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_VOTE_REVEAL(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_VOTE_REVEAL(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"451" : // mainnet; 3 days "451" : // mainnet; 3 days
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"2" : // regtest "2" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"144" : // daoBetaNet; 1 day "144" : // daoBetaNet; 1 day
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"132" : // dao regtest; 0.93 days "132" : // dao regtest; 0.93 days
"300", // testnet or dao testnet (server side regtest); 2 days "300", // testnet or dao testnet (server side regtest); 2 days
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_BREAK3(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_BREAK3(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"9" : // mainnet "9" : // mainnet
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"1" : // regtest "1" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"10" : // daoBetaNet "10" : // daoBetaNet
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"10" : // dao regtest "10" : // dao regtest
"10", // testnet or dao testnet (server side regtest) "10", // testnet or dao testnet (server side regtest)
ParamType.BLOCK, 2, 2), ParamType.BLOCK, 2, 2),
PHASE_RESULT(BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? PHASE_RESULT(BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
"10" : // mainnet "10" : // mainnet
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
"2" : // regtest "2" : // regtest
BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet() ?
"10" : // daoBetaNet "10" : // daoBetaNet
BisqEnvironment.getBaseCurrencyNetwork().isDaoRegTest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isDaoRegTest() ?
"2" : // dao regtest "2" : // dao regtest
"2", // testnet or dao testnet (server side regtest) "2", // testnet or dao testnet (server side regtest)
ParamType.BLOCK, 2, 2); ParamType.BLOCK, 2, 2);

View file

@ -17,7 +17,6 @@
package bisq.core.dao.governance.proposal; package bisq.core.dao.governance.proposal;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.exceptions.TxBroadcastException; import bisq.core.btc.exceptions.TxBroadcastException;
import bisq.core.btc.wallet.TxBroadcaster; import bisq.core.btc.wallet.TxBroadcaster;
import bisq.core.btc.wallet.WalletsManager; import bisq.core.btc.wallet.WalletsManager;
@ -32,6 +31,7 @@ import bisq.network.p2p.P2PService;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.crypto.PubKeyRing; import bisq.common.crypto.PubKeyRing;
import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
@ -220,9 +220,9 @@ public class MyProposalListService implements PersistedDataHost, DaoStateListene
private void rePublishMyProposalsOnceWellConnected() { private void rePublishMyProposalsOnceWellConnected() {
// We republish at each startup at any block during the cycle. We filter anyway for valid blind votes // We republish at each startup at any block during the cycle. We filter anyway for valid blind votes
// of that cycle so it is 1 blind vote getting rebroadcast at each startup to my neighbors. // of that cycle so it is 1 blind vote getting rebroadcast at each startup to my neighbors.
int minPeers = BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? 4 : 1; int minPeers = BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ? 4 : 1;
if ((p2PService.getNumConnectedPeers().get() >= minPeers && p2PService.isBootstrapped()) || if ((p2PService.getNumConnectedPeers().get() >= minPeers && p2PService.isBootstrapped()) ||
BisqEnvironment.getBaseCurrencyNetwork().isRegtest()) { BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest()) {
myProposalList.stream() myProposalList.stream()
.filter(proposal -> periodService.isTxInPhaseAndCycle(proposal.getTxId(), .filter(proposal -> periodService.isTxInPhaseAndCycle(proposal.getTxId(),
DaoPhase.Phase.PROPOSAL, DaoPhase.Phase.PROPOSAL,

View file

@ -17,7 +17,6 @@
package bisq.core.dao.governance.proposal.param; package bisq.core.dao.governance.proposal.param;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.wallet.Restrictions; import bisq.core.btc.wallet.Restrictions;
import bisq.core.dao.governance.ConsensusCritical; import bisq.core.dao.governance.ConsensusCritical;
import bisq.core.dao.governance.param.Param; import bisq.core.dao.governance.param.Param;
@ -32,6 +31,8 @@ import bisq.core.util.coin.BsqFormatter;
import bisq.core.util.validation.BtcAddressValidator; import bisq.core.util.validation.BtcAddressValidator;
import bisq.core.util.validation.InputValidator; import bisq.core.util.validation.InputValidator;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
import javax.inject.Inject; import javax.inject.Inject;
@ -212,7 +213,7 @@ public class ChangeParamValidator extends ProposalValidator implements Consensus
} }
private void validateBlockValue(int currentParamValueAsBlock, int inputValueAsBlock, Param param) throws ParamValidationException { private void validateBlockValue(int currentParamValueAsBlock, int inputValueAsBlock, Param param) throws ParamValidationException {
boolean isMainnet = BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); boolean isMainnet = BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet();
switch (param) { switch (param) {
case LOCK_TIME_TRADE_PAYOUT: case LOCK_TIME_TRADE_PAYOUT:
break; break;

View file

@ -17,13 +17,13 @@
package bisq.core.dao.node.full; package bisq.core.dao.node.full;
import bisq.core.app.BisqEnvironment;
import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.DaoOptionKeys;
import bisq.core.dao.state.model.blockchain.PubKeyScript; import bisq.core.dao.state.model.blockchain.PubKeyScript;
import bisq.core.dao.state.model.blockchain.TxInput; import bisq.core.dao.state.model.blockchain.TxInput;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -102,9 +102,9 @@ public class RpcService {
// mainnet is 8332, testnet 18332, regtest 18443 // mainnet is 8332, testnet 18332, regtest 18443
boolean isHostSet = rpcHost != null && !rpcHost.isEmpty(); boolean isHostSet = rpcHost != null && !rpcHost.isEmpty();
boolean isPortSet = rpcPort != null && !rpcPort.isEmpty(); boolean isPortSet = rpcPort != null && !rpcPort.isEmpty();
boolean isMainnet = BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); boolean isMainnet = BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet();
boolean isTestnet = BisqEnvironment.getBaseCurrencyNetwork().isTestnet(); boolean isTestnet = BaseCurrencyNetwork.CURRENT_NETWORK.isTestnet();
boolean isDaoBetaNet = BisqEnvironment.getBaseCurrencyNetwork().isDaoBetaNet(); boolean isDaoBetaNet = BaseCurrencyNetwork.CURRENT_NETWORK.isDaoBetaNet();
this.rpcHost = isHostSet ? rpcHost : "127.0.0.1"; this.rpcHost = isHostSet ? rpcHost : "127.0.0.1";
this.rpcPort = isPortSet ? rpcPort : this.rpcPort = isPortSet ? rpcPort :
isMainnet || isDaoBetaNet ? "8332" : isMainnet || isDaoBetaNet ? "8332" :

View file

@ -17,7 +17,6 @@
package bisq.core.dao.node.parser; package bisq.core.dao.node.parser;
import bisq.core.app.BisqEnvironment;
import bisq.core.dao.governance.bond.BondConsensus; import bisq.core.dao.governance.bond.BondConsensus;
import bisq.core.dao.governance.param.Param; import bisq.core.dao.governance.param.Param;
import bisq.core.dao.state.DaoStateService; import bisq.core.dao.state.DaoStateService;
@ -25,6 +24,8 @@ import bisq.core.dao.state.model.blockchain.OpReturnType;
import bisq.core.dao.state.model.blockchain.TxOutput; import bisq.core.dao.state.model.blockchain.TxOutput;
import bisq.core.dao.state.model.blockchain.TxOutputType; import bisq.core.dao.state.model.blockchain.TxOutputType;
import bisq.common.config.BaseCurrencyNetwork;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList; import java.util.ArrayList;
@ -411,8 +412,8 @@ class TxOutputParser {
} }
private int getActivateHardFork1Height() { private int getActivateHardFork1Height() {
return BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? ACTIVATE_HARD_FORK_1_HEIGHT_MAINNET : return BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ? ACTIVATE_HARD_FORK_1_HEIGHT_MAINNET :
BisqEnvironment.getBaseCurrencyNetwork().isTestnet() ? ACTIVATE_HARD_FORK_1_HEIGHT_TESTNET : BaseCurrencyNetwork.CURRENT_NETWORK.isTestnet() ? ACTIVATE_HARD_FORK_1_HEIGHT_TESTNET :
ACTIVATE_HARD_FORK_1_HEIGHT_REGTEST; ACTIVATE_HARD_FORK_1_HEIGHT_REGTEST;
} }

View file

@ -17,10 +17,10 @@
package bisq.core.dao.state; package bisq.core.dao.state;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.DaoOptionKeys;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
import javax.inject.Inject; import javax.inject.Inject;
@ -107,7 +107,7 @@ public class GenesisTxInfo {
public GenesisTxInfo(@Named(DaoOptionKeys.GENESIS_TX_ID) String genesisTxId, public GenesisTxInfo(@Named(DaoOptionKeys.GENESIS_TX_ID) String genesisTxId,
@Named(DaoOptionKeys.GENESIS_BLOCK_HEIGHT) Integer genesisBlockHeight, @Named(DaoOptionKeys.GENESIS_BLOCK_HEIGHT) Integer genesisBlockHeight,
@Named(DaoOptionKeys.GENESIS_TOTAL_SUPPLY) Long genesisTotalSupply) { @Named(DaoOptionKeys.GENESIS_TOTAL_SUPPLY) Long genesisTotalSupply) {
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
boolean isMainnet = baseCurrencyNetwork.isMainnet(); boolean isMainnet = baseCurrencyNetwork.isMainnet();
boolean isTestnet = baseCurrencyNetwork.isTestnet(); boolean isTestnet = baseCurrencyNetwork.isTestnet();
boolean isDaoTestNet = baseCurrencyNetwork.isDaoTestNet(); boolean isDaoTestNet = baseCurrencyNetwork.isDaoTestNet();

View file

@ -17,9 +17,10 @@
package bisq.core.dao.state.model.governance; package bisq.core.dao.state.model.governance;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.config.BaseCurrencyNetwork;
import lombok.Getter; import lombok.Getter;
@ -92,9 +93,9 @@ public enum BondedRoleType {
*/ */
BondedRoleType(long requiredBondUnit, int unlockTimeInDays, String link, boolean allowMultipleHolders) { BondedRoleType(long requiredBondUnit, int unlockTimeInDays, String link, boolean allowMultipleHolders) {
this.requiredBondUnit = requiredBondUnit; this.requiredBondUnit = requiredBondUnit;
this.unlockTimeInBlocks = BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ? this.unlockTimeInBlocks = BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ?
unlockTimeInDays * 144 : // mainnet (144 blocks per day) unlockTimeInDays * 144 : // mainnet (144 blocks per day)
BisqEnvironment.getBaseCurrencyNetwork().isRegtest() ? BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest() ?
5 : // regtest (arbitrarily low value for dev testing) 5 : // regtest (arbitrarily low value for dev testing)
144; // testnet (relatively short time for testing purposes) 144; // testnet (relatively short time for testing purposes)
this.link = link; this.link = link;

View file

@ -17,7 +17,6 @@
package bisq.core.dao.state.model.governance; package bisq.core.dao.state.model.governance;
import bisq.core.app.BisqEnvironment;
import bisq.core.dao.governance.param.Param; import bisq.core.dao.governance.param.Param;
import bisq.core.dao.governance.proposal.IssuanceProposal; import bisq.core.dao.governance.proposal.IssuanceProposal;
import bisq.core.dao.governance.proposal.ProposalType; import bisq.core.dao.governance.proposal.ProposalType;
@ -25,6 +24,7 @@ import bisq.core.dao.state.model.ImmutableDaoStateModel;
import bisq.core.dao.state.model.blockchain.TxType; import bisq.core.dao.state.model.blockchain.TxType;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Address; import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.AddressFormatException;
@ -121,7 +121,7 @@ public final class CompensationProposal extends Proposal implements IssuanceProp
public Address getAddress() throws AddressFormatException { public Address getAddress() throws AddressFormatException {
// Remove leading 'B' // Remove leading 'B'
String underlyingBtcAddress = bsqAddress.substring(1, bsqAddress.length()); String underlyingBtcAddress = bsqAddress.substring(1, bsqAddress.length());
return Address.fromBase58(BisqEnvironment.getParameters(), underlyingBtcAddress); return Address.fromBase58(BaseCurrencyNetwork.CURRENT_PARAMETERS, underlyingBtcAddress);
} }

View file

@ -25,6 +25,7 @@ import bisq.core.dao.state.model.ImmutableDaoStateModel;
import bisq.core.dao.state.model.blockchain.TxType; import bisq.core.dao.state.model.blockchain.TxType;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Address; import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.AddressFormatException;
@ -121,7 +122,7 @@ public final class ReimbursementProposal extends Proposal implements IssuancePro
public Address getAddress() throws AddressFormatException { public Address getAddress() throws AddressFormatException {
// Remove leading 'B' // Remove leading 'B'
String underlyingBtcAddress = bsqAddress.substring(1, bsqAddress.length()); String underlyingBtcAddress = bsqAddress.substring(1, bsqAddress.length());
return Address.fromBase58(BisqEnvironment.getParameters(), underlyingBtcAddress); return Address.fromBase58(BaseCurrencyNetwork.CURRENT_PARAMETERS, underlyingBtcAddress);
} }

View file

@ -18,7 +18,6 @@
package bisq.core.filter; package bisq.core.filter;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.nodes.BtcNodes; import bisq.core.btc.nodes.BtcNodes;
import bisq.core.payment.payload.PaymentAccountPayload; import bisq.core.payment.payload.PaymentAccountPayload;
import bisq.core.payment.payload.PaymentMethod; import bisq.core.payment.payload.PaymentMethod;
@ -36,6 +35,8 @@ import bisq.network.p2p.storage.payload.ProtectedStoragePayload;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.Config;
import bisq.common.config.ConfigFileEditor;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import org.bitcoinj.core.ECKey; import org.bitcoinj.core.ECKey;
@ -68,6 +69,7 @@ import javax.annotation.Nullable;
import static org.bitcoinj.core.Utils.HEX; import static org.bitcoinj.core.Utils.HEX;
public class FilterManager { public class FilterManager {
private static final Logger log = LoggerFactory.getLogger(FilterManager.class); private static final Logger log = LoggerFactory.getLogger(FilterManager.class);
public static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes"; public static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes";
@ -87,7 +89,7 @@ public class FilterManager {
private final KeyRing keyRing; private final KeyRing keyRing;
private final User user; private final User user;
private final Preferences preferences; private final Preferences preferences;
private final BisqEnvironment bisqEnvironment; private final ConfigFileEditor configFileEditor;
private final ProvidersRepository providersRepository; private final ProvidersRepository providersRepository;
private boolean ignoreDevMsg; private boolean ignoreDevMsg;
private final ObjectProperty<Filter> filterProperty = new SimpleObjectProperty<>(); private final ObjectProperty<Filter> filterProperty = new SimpleObjectProperty<>();
@ -106,7 +108,7 @@ public class FilterManager {
KeyRing keyRing, KeyRing keyRing,
User user, User user,
Preferences preferences, Preferences preferences,
BisqEnvironment bisqEnvironment, Config config,
ProvidersRepository providersRepository, ProvidersRepository providersRepository,
@Named(AppOptionKeys.IGNORE_DEV_MSG_KEY) boolean ignoreDevMsg, @Named(AppOptionKeys.IGNORE_DEV_MSG_KEY) boolean ignoreDevMsg,
@Named(AppOptionKeys.USE_DEV_PRIVILEGE_KEYS) boolean useDevPrivilegeKeys) { @Named(AppOptionKeys.USE_DEV_PRIVILEGE_KEYS) boolean useDevPrivilegeKeys) {
@ -114,7 +116,7 @@ public class FilterManager {
this.keyRing = keyRing; this.keyRing = keyRing;
this.user = user; this.user = user;
this.preferences = preferences; this.preferences = preferences;
this.bisqEnvironment = bisqEnvironment; this.configFileEditor = new ConfigFileEditor(config.getConfigFile());
this.providersRepository = providersRepository; this.providersRepository = providersRepository;
this.ignoreDevMsg = ignoreDevMsg; this.ignoreDevMsg = ignoreDevMsg;
pubKeyAsHex = useDevPrivilegeKeys ? pubKeyAsHex = useDevPrivilegeKeys ?
@ -201,9 +203,9 @@ public class FilterManager {
} }
private void resetFilters() { private void resetFilters() {
bisqEnvironment.saveBannedBtcNodes(null); saveBannedNodes(BANNED_BTC_NODES, null);
bisqEnvironment.saveBannedSeedNodes(null); saveBannedNodes(BANNED_SEED_NODES, null);
bisqEnvironment.saveBannedPriceRelayNodes(null); saveBannedNodes(BANNED_PRICE_RELAY_NODES, null);
if (providersRepository.getBannedNodes() != null) if (providersRepository.getBannedNodes() != null)
providersRepository.applyBannedNodes(null); providersRepository.applyBannedNodes(null);
@ -216,12 +218,12 @@ public class FilterManager {
// Seed nodes are requested at startup before we get the filter so we only apply the banned // Seed nodes are requested at startup before we get the filter so we only apply the banned
// nodes at the next startup and don't update the list in the P2P network domain. // nodes at the next startup and don't update the list in the P2P network domain.
// We persist it to the property file which is read before any other initialisation. // We persist it to the property file which is read before any other initialisation.
bisqEnvironment.saveBannedSeedNodes(filter.getSeedNodes()); saveBannedNodes(BANNED_SEED_NODES, filter.getSeedNodes());
bisqEnvironment.saveBannedBtcNodes(filter.getBtcNodes()); saveBannedNodes(BANNED_BTC_NODES, filter.getBtcNodes());
// Banned price relay nodes we can apply at runtime // Banned price relay nodes we can apply at runtime
final List<String> priceRelayNodes = filter.getPriceRelayNodes(); final List<String> priceRelayNodes = filter.getPriceRelayNodes();
bisqEnvironment.saveBannedPriceRelayNodes(priceRelayNodes); saveBannedNodes(BANNED_PRICE_RELAY_NODES, priceRelayNodes);
providersRepository.applyBannedNodes(priceRelayNodes); providersRepository.applyBannedNodes(priceRelayNodes);
@ -237,6 +239,13 @@ public class FilterManager {
} }
} }
private void saveBannedNodes(String optionName, List<String> bannedNodes) {
if (bannedNodes != null)
configFileEditor.setOption(optionName, String.join(",", bannedNodes));
else
configFileEditor.clearOption(optionName);
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// API // API

View file

@ -20,6 +20,7 @@ package bisq.core.filter;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -29,8 +30,8 @@ import static com.google.inject.name.Names.named;
public class FilterModule extends AppModule { public class FilterModule extends AppModule {
public FilterModule(Environment environment) { public FilterModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override

View file

@ -17,8 +17,6 @@
package bisq.core.locale; package bisq.core.locale;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.dao.governance.asset.AssetService; import bisq.core.dao.governance.asset.AssetService;
import bisq.core.filter.FilterManager; import bisq.core.filter.FilterManager;
@ -29,6 +27,7 @@ import bisq.asset.Token;
import bisq.asset.coins.BSQ; import bisq.asset.coins.BSQ;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
@ -55,7 +54,7 @@ import static com.google.common.base.Preconditions.checkArgument;
public class CurrencyUtil { public class CurrencyUtil {
public static void setup() { public static void setup() {
setBaseCurrencyCode(BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode()); setBaseCurrencyCode(BaseCurrencyNetwork.CURRENT_NETWORK.getCurrencyCode());
} }
private static final AssetRegistry assetRegistry = new AssetRegistry(); private static final AssetRegistry assetRegistry = new AssetRegistry();
@ -119,8 +118,8 @@ public class CurrencyUtil {
public static Stream<Asset> getSortedAssetStream() { public static Stream<Asset> getSortedAssetStream() {
return assetRegistry.stream() return assetRegistry.stream()
.filter(CurrencyUtil::assetIsNotBaseCurrency) .filter(CurrencyUtil::assetIsNotBaseCurrency)
.filter(asset -> isNotBsqOrBsqTradingActivated(asset, BisqEnvironment.getBaseCurrencyNetwork(), DevEnv.isDaoTradingActivated())) .filter(asset -> isNotBsqOrBsqTradingActivated(asset, BaseCurrencyNetwork.CURRENT_NETWORK, DevEnv.isDaoTradingActivated()))
.filter(asset -> assetMatchesNetworkIfMainnet(asset, BisqEnvironment.getBaseCurrencyNetwork())) .filter(asset -> assetMatchesNetworkIfMainnet(asset, BaseCurrencyNetwork.CURRENT_NETWORK))
.sorted(Comparator.comparing(Asset::getName)); .sorted(Comparator.comparing(Asset::getName));
} }

View file

@ -17,11 +17,9 @@
package bisq.core.locale; package bisq.core.locale;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -46,7 +44,7 @@ import org.jetbrains.annotations.NotNull;
@Slf4j @Slf4j
public class Res { public class Res {
public static void setup() { public static void setup() {
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
setBaseCurrencyCode(baseCurrencyNetwork.getCurrencyCode()); setBaseCurrencyCode(baseCurrencyNetwork.getCurrencyCode());
setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName()); setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName());
} }

View file

@ -17,12 +17,12 @@
package bisq.core.network.p2p.seed; package bisq.core.network.p2p.seed;
import bisq.core.app.BisqEnvironment;
import bisq.network.NetworkOptionKeys; import bisq.network.NetworkOptionKeys;
import bisq.network.p2p.NodeAddress; import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.seed.SeedNodeRepository; import bisq.network.p2p.seed.SeedNodeRepository;
import bisq.common.config.Config;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -50,14 +50,14 @@ public class DefaultSeedNodeRepository implements SeedNodeRepository {
private static final Pattern pattern = Pattern.compile("^([a-z0-9]+\\.onion:\\d+)"); private static final Pattern pattern = Pattern.compile("^([a-z0-9]+\\.onion:\\d+)");
private static final String ENDING = ".seednodes"; private static final String ENDING = ".seednodes";
private final Collection<NodeAddress> cache = new HashSet<>(); private final Collection<NodeAddress> cache = new HashSet<>();
private final BisqEnvironment bisqEnvironment; private final Config config;
@Nullable @Nullable
private final String seedNodes; private final String seedNodes;
@Inject @Inject
public DefaultSeedNodeRepository(BisqEnvironment environment, public DefaultSeedNodeRepository(Config config,
@Nullable @Named(NetworkOptionKeys.SEED_NODES_KEY) String seedNodes) { @Nullable @Named(NetworkOptionKeys.SEED_NODES_KEY) String seedNodes) {
bisqEnvironment = environment; this.config = config;
this.seedNodes = seedNodes; this.seedNodes = seedNodes;
} }
@ -72,7 +72,7 @@ public class DefaultSeedNodeRepository implements SeedNodeRepository {
} }
// else, we fetch the seed nodes from our resources // else, we fetch the seed nodes from our resources
InputStream fileInputStream = DefaultSeedNodeRepository.class.getClassLoader().getResourceAsStream(BisqEnvironment.getBaseCurrencyNetwork().name().toLowerCase() + ENDING); InputStream fileInputStream = DefaultSeedNodeRepository.class.getClassLoader().getResourceAsStream(config.getBaseCurrencyNetwork().name().toLowerCase() + ENDING);
BufferedReader seedNodeFile = new BufferedReader(new InputStreamReader(fileInputStream)); BufferedReader seedNodeFile = new BufferedReader(new InputStreamReader(fileInputStream));
// only clear if we have a fresh data source (otherwise, an exception would prevent us from getting here) // only clear if we have a fresh data source (otherwise, an exception would prevent us from getting here)
@ -90,7 +90,7 @@ public class DefaultSeedNodeRepository implements SeedNodeRepository {
}); });
// filter // filter
cache.removeAll(bisqEnvironment.getBannedSeedNodes().stream().map(NodeAddress::new).collect(Collectors.toSet())); cache.removeAll(config.getBannedSeedNodes().stream().map(NodeAddress::new).collect(Collectors.toSet()));
log.info("Seed nodes: {}", cache); log.info("Seed nodes: {}", cache);
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -18,6 +18,7 @@
package bisq.core.offer; package bisq.core.offer;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -28,8 +29,8 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class OfferModule extends AppModule { public class OfferModule extends AppModule {
public OfferModule(Environment environment) { public OfferModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override

View file

@ -17,12 +17,16 @@
package bisq.core.payment.validation; package bisq.core.payment.validation;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.CurrencyUtil; import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.core.util.validation.InputValidator; import bisq.core.util.validation.InputValidator;
import bisq.asset.AddressValidationResult;
import bisq.asset.Asset;
import bisq.asset.AssetRegistry;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import com.google.inject.Inject; import com.google.inject.Inject;
@ -30,12 +34,6 @@ import java.util.Optional;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import bisq.asset.AddressValidationResult;
import bisq.asset.Asset;
import bisq.asset.AssetRegistry;
@Slf4j @Slf4j
public final class AltCoinAddressValidator extends InputValidator { public final class AltCoinAddressValidator extends InputValidator {
@ -58,7 +56,7 @@ public final class AltCoinAddressValidator extends InputValidator {
return validationResult; return validationResult;
Optional<Asset> optionalAsset = CurrencyUtil.findAsset(assetRegistry, currencyCode, Optional<Asset> optionalAsset = CurrencyUtil.findAsset(assetRegistry, currencyCode,
BisqEnvironment.getBaseCurrencyNetwork(), DevEnv.isDaoTradingActivated()); BaseCurrencyNetwork.CURRENT_NETWORK, DevEnv.isDaoTradingActivated());
if (optionalAsset.isPresent()) { if (optionalAsset.isPresent()) {
Asset asset = optionalAsset.get(); Asset asset = optionalAsset.get();
AddressValidationResult result = asset.validateAddress(input); AddressValidationResult result = asset.validateAddress(input);

View file

@ -18,14 +18,16 @@
package bisq.core.presentation; package bisq.core.presentation;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import com.google.inject.Singleton; import com.google.inject.Singleton;
public class CorePresentationModule extends AppModule { public class CorePresentationModule extends AppModule {
public CorePresentationModule(Environment environment) {
super(environment); public CorePresentationModule(Environment environment, Config config) {
super(environment, config);
} }
@Override @Override

View file

@ -18,10 +18,11 @@
package bisq.core.provider; package bisq.core.provider;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.network.NetworkOptionKeys; import bisq.network.NetworkOptionKeys;
import bisq.common.config.Config;
import com.google.inject.Inject; import com.google.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
@ -48,6 +49,7 @@ public class ProvidersRepository {
"http://gztmprecgqjq64zh.onion/" // @wiz "http://gztmprecgqjq64zh.onion/" // @wiz
); );
private final Config config;
private final String providersFromProgramArgs; private final String providersFromProgramArgs;
private final boolean useLocalhostForP2P; private final boolean useLocalhostForP2P;
@ -65,16 +67,17 @@ public class ProvidersRepository {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
public ProvidersRepository(BisqEnvironment bisqEnvironment, public ProvidersRepository(Config config,
@Named(AppOptionKeys.PROVIDERS) String providers, @Named(AppOptionKeys.PROVIDERS) String providers,
@Named(NetworkOptionKeys.USE_LOCALHOST_FOR_P2P) boolean useLocalhostForP2P) { @Named(NetworkOptionKeys.USE_LOCALHOST_FOR_P2P) boolean useLocalhostForP2P) {
this.config = config;
this.providersFromProgramArgs = providers; this.providersFromProgramArgs = providers;
this.useLocalhostForP2P = useLocalhostForP2P; this.useLocalhostForP2P = useLocalhostForP2P;
Collections.shuffle(DEFAULT_NODES); Collections.shuffle(DEFAULT_NODES);
applyBannedNodes(bisqEnvironment.getBannedPriceRelayNodes()); applyBannedNodes(config.getBannedPriceRelayNodes());
} }
public void applyBannedNodes(@Nullable List<String> bannedNodes) { public void applyBannedNodes(@Nullable List<String> bannedNodes) {
@ -97,7 +100,7 @@ public class ProvidersRepository {
baseUrl = providerList.get(index); baseUrl = providerList.get(index);
index++; index++;
if (providerList.size() == 1 && BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) if (providerList.size() == 1 && config.getBaseCurrencyNetwork().isMainnet())
log.warn("We only have one provider"); log.warn("We only have one provider");
} else { } else {
baseUrl = ""; baseUrl = "";

View file

@ -17,12 +17,12 @@
package bisq.core.provider.fee; package bisq.core.provider.fee;
import bisq.core.app.BisqEnvironment;
import bisq.core.dao.governance.param.Param; import bisq.core.dao.governance.param.Param;
import bisq.core.dao.governance.period.PeriodService; import bisq.core.dao.governance.period.PeriodService;
import bisq.core.dao.state.DaoStateService; import bisq.core.dao.state.DaoStateService;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.handlers.FaultHandler; import bisq.common.handlers.FaultHandler;
import bisq.common.util.Tuple2; import bisq.common.util.Tuple2;
@ -117,7 +117,7 @@ public class FeeService {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void onAllServicesInitialized() { public void onAllServicesInitialized() {
minFeePerByte = BisqEnvironment.getBaseCurrencyNetwork().getDefaultMinFeePerByte(); minFeePerByte = BaseCurrencyNetwork.CURRENT_NETWORK.getDefaultMinFeePerByte();
requestFees(); requestFees();

View file

@ -22,12 +22,14 @@ import bisq.core.dao.DaoOptionKeys;
import bisq.common.app.Capabilities; import bisq.common.app.Capabilities;
import bisq.common.app.Capability; import bisq.common.app.Capability;
import bisq.common.config.Config;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class CoreNetworkCapabilities { public class CoreNetworkCapabilities {
static void setSupportedCapabilities(BisqEnvironment bisqEnvironment) {
static void setSupportedCapabilities(Config config) {
Capabilities.app.addAll( Capabilities.app.addAll(
Capability.TRADE_STATISTICS, Capability.TRADE_STATISTICS,
Capability.TRADE_STATISTICS_2, Capability.TRADE_STATISTICS_2,
@ -43,17 +45,16 @@ public class CoreNetworkCapabilities {
Capability.TRADE_STATISTICS_HASH_UPDATE Capability.TRADE_STATISTICS_HASH_UPDATE
); );
if (BisqEnvironment.isDaoActivated(bisqEnvironment)) { if (config.isDaoActivated()) {
maybeApplyDaoFullMode(bisqEnvironment); maybeApplyDaoFullMode(config);
} }
} }
public static void maybeApplyDaoFullMode(BisqEnvironment bisqEnvironment) { public static void maybeApplyDaoFullMode(Config config) {
// If we set dao full mode at the preferences view we add the capability there. We read the preferences a // If we set dao full mode at the preferences view we add the capability there. We read the preferences a
// bit later than we call that method so we have to add DAO_FULL_NODE Capability at preferences as well to // bit later than we call that method so we have to add DAO_FULL_NODE Capability at preferences as well to
// be sure it is set in both cases. // be sure it is set in both cases.
String isFullDaoNode = bisqEnvironment.getProperty(DaoOptionKeys.FULL_DAO_NODE, String.class, "false"); if (config.isFullDaoNode()) {
if (isFullDaoNode != null && !isFullDaoNode.isEmpty() && isFullDaoNode.toLowerCase().equals("true")) {
log.info("Set Capability.DAO_FULL_NODE"); log.info("Set Capability.DAO_FULL_NODE");
Capabilities.app.addAll(Capability.DAO_FULL_NODE); Capabilities.app.addAll(Capability.DAO_FULL_NODE);
} else { } else {

View file

@ -38,6 +38,7 @@ import bisq.core.user.User;
import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PService;
import bisq.common.config.Config;
import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.PersistedDataHost;
import com.google.inject.Injector; import com.google.inject.Injector;
@ -67,7 +68,7 @@ public class CorePersistedDataHost {
persistedDataHosts.add(injector.getInstance(RefundDisputeListService.class)); persistedDataHosts.add(injector.getInstance(RefundDisputeListService.class));
persistedDataHosts.add(injector.getInstance(P2PService.class)); persistedDataHosts.add(injector.getInstance(P2PService.class));
if (injector.getInstance(Key.get(Boolean.class, Names.named(DaoOptionKeys.DAO_ACTIVATED)))) { if (injector.getInstance(Config.class).isDaoActivated()) {
persistedDataHosts.add(injector.getInstance(BallotListService.class)); persistedDataHosts.add(injector.getInstance(BallotListService.class));
persistedDataHosts.add(injector.getInstance(MyBlindVoteListService.class)); persistedDataHosts.add(injector.getInstance(MyBlindVoteListService.class));
persistedDataHosts.add(injector.getInstance(MyVoteListService.class)); persistedDataHosts.add(injector.getInstance(MyVoteListService.class));

View file

@ -17,13 +17,12 @@
package bisq.core.setup; package bisq.core.setup;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.CurrencyUtil; import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.CommonOptionKeys;
import bisq.common.app.Log; import bisq.common.app.Log;
import bisq.common.app.Version; import bisq.common.app.Version;
import bisq.common.config.Config;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -37,14 +36,13 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class CoreSetup { public class CoreSetup {
public static void setup(BisqEnvironment bisqEnvironment) { public static void setup(Config config) {
setupLog(bisqEnvironment); setupLog(config);
CoreNetworkCapabilities.setSupportedCapabilities(bisqEnvironment); CoreNetworkCapabilities.setSupportedCapabilities(config);
Res.setup(); Res.setup();
CurrencyUtil.setup(); CurrencyUtil.setup();
bisqEnvironment.saveBaseCryptoNetwork(BisqEnvironment.getBaseCurrencyNetwork());
Version.setBaseCryptoNetworkId(BisqEnvironment.getBaseCurrencyNetwork().ordinal()); Version.setBaseCryptoNetworkId(config.getBaseCurrencyNetwork().ordinal());
Version.printVersion(); Version.printVersion();
try { try {
@ -57,11 +55,11 @@ public class CoreSetup {
} }
} }
private static void setupLog(BisqEnvironment bisqEnvironment) { private static void setupLog(Config config) {
String logPath = Paths.get(bisqEnvironment.getAppDataDir(), "bisq").toString(); String logPath = Paths.get(config.getAppDataDir().getPath(), "bisq").toString();
Log.setup(logPath); Log.setup(logPath);
log.info("\n\n\nLog files under: " + logPath); log.info("\n\n\nLog files under: " + logPath);
Utilities.printSysInfo(); Utilities.printSysInfo();
Log.setLevel(Level.toLevel(bisqEnvironment.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY))); Log.setLevel(Level.toLevel(config.getLogLevel()));
} }
} }

View file

@ -17,7 +17,6 @@
package bisq.core.support.dispute.agent; package bisq.core.support.dispute.agent;
import bisq.core.app.BisqEnvironment;
import bisq.core.filter.FilterManager; import bisq.core.filter.FilterManager;
import bisq.network.p2p.NodeAddress; import bisq.network.p2p.NodeAddress;
@ -25,6 +24,7 @@ import bisq.network.p2p.P2PService;
import bisq.network.p2p.storage.HashMapChangedListener; import bisq.network.p2p.storage.HashMapChangedListener;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ResultHandler; import bisq.common.handlers.ResultHandler;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -62,7 +62,7 @@ public abstract class DisputeAgentService<T extends DisputeAgent> {
ResultHandler resultHandler, ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) { ErrorMessageHandler errorMessageHandler) {
log.debug("addDisputeAgent disputeAgent.hashCode() " + disputeAgent.hashCode()); log.debug("addDisputeAgent disputeAgent.hashCode() " + disputeAgent.hashCode());
if (!BisqEnvironment.getBaseCurrencyNetwork().isMainnet() || if (!BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet() ||
!Utilities.encodeToHex(disputeAgent.getRegistrationPubKey()).equals(DevEnv.DEV_PRIVILEGE_PUB_KEY)) { !Utilities.encodeToHex(disputeAgent.getRegistrationPubKey()).equals(DevEnv.DEV_PRIVILEGE_PUB_KEY)) {
boolean result = p2PService.addProtectedStorageEntry(disputeAgent); boolean result = p2PService.addProtectedStorageEntry(disputeAgent);
if (result) { if (result) {

View file

@ -30,6 +30,7 @@ import bisq.core.trade.statistics.TradeStatistics2StorageService;
import bisq.core.trade.statistics.TradeStatisticsManager; import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -39,8 +40,8 @@ import static com.google.inject.name.Names.named;
public class TradeModule extends AppModule { public class TradeModule extends AppModule {
public TradeModule(Environment environment) { public TradeModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override

View file

@ -17,11 +17,10 @@
package bisq.core.trade.protocol.tasks.maker; package bisq.core.trade.protocol.tasks.maker;
import bisq.core.app.BisqEnvironment;
import bisq.core.trade.Trade; import bisq.core.trade.Trade;
import bisq.core.trade.protocol.tasks.TradeTask; import bisq.core.trade.protocol.tasks.TradeTask;
import bisq.common.app.DevEnv; import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.taskrunner.TaskRunner; import bisq.common.taskrunner.TaskRunner;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -40,7 +39,7 @@ public class MakerSetsLockTime extends TradeTask {
// 10 days for altcoins, 20 days for other payment methods // 10 days for altcoins, 20 days for other payment methods
int delay = processModel.getOffer().getPaymentMethod().isAsset() ? 144 * 10 : 144 * 20; int delay = processModel.getOffer().getPaymentMethod().isAsset() ? 144 * 10 : 144 * 20;
if (BisqEnvironment.getBaseCurrencyNetwork().isRegtest()) { if (BaseCurrencyNetwork.CURRENT_NETWORK.isRegtest()) {
delay = 5; delay = 5;
} }

View file

@ -18,8 +18,6 @@
package bisq.core.user; package bisq.core.user;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.btc.BtcOptionKeys; import bisq.core.btc.BtcOptionKeys;
import bisq.core.btc.nodes.BtcNodes; import bisq.core.btc.nodes.BtcNodes;
import bisq.core.btc.wallet.Restrictions; import bisq.core.btc.wallet.Restrictions;
@ -37,6 +35,8 @@ import bisq.core.setup.CoreNetworkCapabilities;
import bisq.network.p2p.network.BridgeAddressProvider; import bisq.network.p2p.network.BridgeAddressProvider;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.PersistedDataHost;
import bisq.common.storage.Storage; import bisq.common.storage.Storage;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -135,7 +135,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
private final ObservableMap<String, Boolean> dontShowAgainMapAsObservable = FXCollections.observableHashMap(); private final ObservableMap<String, Boolean> dontShowAgainMapAsObservable = FXCollections.observableHashMap();
private final Storage<PreferencesPayload> storage; private final Storage<PreferencesPayload> storage;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final String btcNodesFromOptions, useTorFlagFromOptions, referralIdFromOptions, fullDaoNodeFromOptions, private final String btcNodesFromOptions, useTorFlagFromOptions, referralIdFromOptions, fullDaoNodeFromOptions,
rpcUserFromOptions, rpcPwFromOptions, blockNotifyPortFromOptions; rpcUserFromOptions, rpcPwFromOptions, blockNotifyPortFromOptions;
@Getter @Getter
@ -150,7 +150,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
@Inject @Inject
public Preferences(Storage<PreferencesPayload> storage, public Preferences(Storage<PreferencesPayload> storage,
BisqEnvironment bisqEnvironment, Config config,
@Named(BtcOptionKeys.BTC_NODES) String btcNodesFromOptions, @Named(BtcOptionKeys.BTC_NODES) String btcNodesFromOptions,
@Named(BtcOptionKeys.USE_TOR_FOR_BTC) String useTorFlagFromOptions, @Named(BtcOptionKeys.USE_TOR_FOR_BTC) String useTorFlagFromOptions,
@Named(AppOptionKeys.REFERRAL_ID) String referralId, @Named(AppOptionKeys.REFERRAL_ID) String referralId,
@ -161,7 +161,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
this.storage = storage; this.storage = storage;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.btcNodesFromOptions = btcNodesFromOptions; this.btcNodesFromOptions = btcNodesFromOptions;
this.useTorFlagFromOptions = useTorFlagFromOptions; this.useTorFlagFromOptions = useTorFlagFromOptions;
this.referralIdFromOptions = referralId; this.referralIdFromOptions = referralId;
@ -206,7 +206,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
@Override @Override
public void readPersisted() { public void readPersisted() {
PreferencesPayload persisted = storage.initAndGetPersistedWithFileName("PreferencesPayload", 100); PreferencesPayload persisted = storage.initAndGetPersistedWithFileName("PreferencesPayload", 100);
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
TradeCurrency preferredTradeCurrency; TradeCurrency preferredTradeCurrency;
if (persisted != null) { if (persisted != null) {
prefPayload = persisted; prefPayload = persisted;
@ -304,7 +304,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
// We set the capability in CoreNetworkCapabilities if the program argument is set. // We set the capability in CoreNetworkCapabilities if the program argument is set.
// If we have set it in the preferences view we handle it here. // If we have set it in the preferences view we handle it here.
CoreNetworkCapabilities.maybeApplyDaoFullMode(bisqEnvironment); CoreNetworkCapabilities.maybeApplyDaoFullMode(config);
initialReadDone = true; initialReadDone = true;
persist(); persist();
@ -375,7 +375,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
} }
public void setBlockChainExplorer(BlockChainExplorer blockChainExplorer) { public void setBlockChainExplorer(BlockChainExplorer blockChainExplorer) {
if (BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) if (BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet())
setBlockChainExplorerMainNet(blockChainExplorer); setBlockChainExplorerMainNet(blockChainExplorer);
else else
setBlockChainExplorerTestNet(blockChainExplorer); setBlockChainExplorerTestNet(blockChainExplorer);
@ -696,7 +696,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
} }
public BlockChainExplorer getBlockChainExplorer() { public BlockChainExplorer getBlockChainExplorer() {
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
switch (baseCurrencyNetwork) { switch (baseCurrencyNetwork) {
case BTC_MAINNET: case BTC_MAINNET:
return prefPayload.getBlockChainExplorerMainNet(); return prefPayload.getBlockChainExplorerMainNet();
@ -715,7 +715,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
} }
public ArrayList<BlockChainExplorer> getBlockChainExplorers() { public ArrayList<BlockChainExplorer> getBlockChainExplorers() {
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
switch (baseCurrencyNetwork) { switch (baseCurrencyNetwork) {
case BTC_MAINNET: case BTC_MAINNET:
return BTC_MAIN_NET_EXPLORERS; return BTC_MAIN_NET_EXPLORERS;
@ -743,8 +743,8 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
// We override the useTorForBitcoinJ and set it to false if we detected a localhost node or if we are not on mainnet, // We override the useTorForBitcoinJ and set it to false if we detected a localhost node or if we are not on mainnet,
// unless the useTorForBtc parameter is explicitly provided. // unless the useTorForBtc parameter is explicitly provided.
// On testnet there are very few Bitcoin tor nodes and we don't provide tor nodes. // On testnet there are very few Bitcoin tor nodes and we don't provide tor nodes.
if ((!BisqEnvironment.getBaseCurrencyNetwork().isMainnet() if ((!BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet()
|| bisqEnvironment.isBitcoinLocalhostNodeRunning()) || config.isLocalBitcoinNodeIsRunning())
&& (useTorFlagFromOptions == null || useTorFlagFromOptions.isEmpty())) && (useTorFlagFromOptions == null || useTorFlagFromOptions.isEmpty()))
return false; return false;
else else
@ -775,7 +775,7 @@ public final class Preferences implements PersistedDataHost, BridgeAddressProvid
} }
public long getWithdrawalTxFeeInBytes() { public long getWithdrawalTxFeeInBytes() {
return Math.max(prefPayload.getWithdrawalTxFeeInBytes(), BisqEnvironment.getBaseCurrencyNetwork().getDefaultMinFeePerByte()); return Math.max(prefPayload.getWithdrawalTxFeeInBytes(), BaseCurrencyNetwork.CURRENT_NETWORK.getDefaultMinFeePerByte());
} }
public boolean isDaoFullNode() { public boolean isDaoFullNode() {

View file

@ -17,7 +17,6 @@
package bisq.core.util.coin; package bisq.core.util.coin;
import bisq.core.app.BisqEnvironment;
import bisq.core.dao.governance.param.Param; import bisq.core.dao.governance.param.Param;
import bisq.core.dao.governance.proposal.ProposalValidationException; import bisq.core.dao.governance.proposal.ProposalValidationException;
import bisq.core.locale.GlobalSettings; import bisq.core.locale.GlobalSettings;
@ -29,6 +28,7 @@ import bisq.core.util.validation.BtcAddressValidator;
import bisq.core.util.validation.InputValidator; import bisq.core.util.validation.InputValidator;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.util.MathUtils; import bisq.common.util.MathUtils;
import org.bitcoinj.core.Address; import org.bitcoinj.core.Address;
@ -72,7 +72,7 @@ public class BsqFormatter implements CoinFormatter {
@Inject @Inject
public BsqFormatter() { public BsqFormatter() {
this.btcCoinFormat = BisqEnvironment.getParameters().getMonetaryFormat(); this.btcCoinFormat = BaseCurrencyNetwork.CURRENT_PARAMETERS.getMonetaryFormat();
this.monetaryFormat = new MonetaryFormat().shift(6).code(6, "BSQ").minDecimals(2); this.monetaryFormat = new MonetaryFormat().shift(6).code(6, "BSQ").minDecimals(2);
this.immutableCoinFormatter = new ImmutableCoinFormatter(monetaryFormat); this.immutableCoinFormatter = new ImmutableCoinFormatter(monetaryFormat);
@ -110,7 +110,7 @@ public class BsqFormatter implements CoinFormatter {
encoded = encoded.substring(prefix.length(), encoded.length()); encoded = encoded.substring(prefix.length(), encoded.length());
try { try {
return Address.fromBase58(BisqEnvironment.getParameters(), encoded); return Address.fromBase58(BaseCurrencyNetwork.CURRENT_PARAMETERS, encoded);
} catch (AddressFormatException e) { } catch (AddressFormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View file

@ -17,9 +17,10 @@
package bisq.core.util.validation; package bisq.core.util.validation;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.config.BaseCurrencyNetwork;
import org.bitcoinj.core.Address; import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.AddressFormatException;
@ -43,7 +44,7 @@ public final class BtcAddressValidator extends InputValidator {
private ValidationResult validateBtcAddress(String input) { private ValidationResult validateBtcAddress(String input) {
try { try {
Address.fromBase58(BisqEnvironment.getParameters(), input); Address.fromBase58(BaseCurrencyNetwork.CURRENT_PARAMETERS, input);
return new ValidationResult(true); return new ValidationResult(true);
} catch (AddressFormatException e) { } catch (AddressFormatException e) {
return new ValidationResult(false, Res.get("validation.btc.invalidFormat")); return new ValidationResult(false, Res.get("validation.btc.invalidFormat"));

View file

@ -17,6 +17,8 @@
package bisq.core.app; package bisq.core.app;
import bisq.common.config.BisqHelpFormatter;
import joptsimple.OptionParser; import joptsimple.OptionParser;
import java.net.URISyntaxException; import java.net.URISyntaxException;

View file

@ -17,7 +17,7 @@
package bisq.core.locale; package bisq.core.locale;
import bisq.core.btc.BaseCurrencyNetwork; import bisq.common.config.BaseCurrencyNetwork;
import bisq.asset.Asset; import bisq.asset.Asset;
import bisq.asset.AssetRegistry; import bisq.asset.AssetRegistry;

View file

@ -17,11 +17,9 @@
package bisq.core.network.p2p.seed; package bisq.core.network.p2p.seed;
import bisq.core.app.BisqEnvironment;
import bisq.network.p2p.NodeAddress; import bisq.network.p2p.NodeAddress;
import org.springframework.core.env.PropertySource; import bisq.common.config.TestConfig;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -30,7 +28,7 @@ public class DefaultSeedNodeRepositoryTest {
@Test @Test
public void getSeedNodes() { public void getSeedNodes() {
DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new BisqEnvironment(new PropertySource.StubPropertySource("name")), null); DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new TestConfig(), null);
Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty()); Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty());
} }
@ -39,7 +37,7 @@ public class DefaultSeedNodeRepositoryTest {
String seed1 = "asdf:8001"; String seed1 = "asdf:8001";
String seed2 = "fdsa:6001"; String seed2 = "fdsa:6001";
String seedNodes = seed1 + "," + seed2; String seedNodes = seed1 + "," + seed2;
DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new BisqEnvironment(new PropertySource.StubPropertySource("name")), seedNodes); DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new TestConfig(), seedNodes);
Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty()); Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty());
Assert.assertEquals(2, DUT.getSeedNodeAddresses().size()); Assert.assertEquals(2, DUT.getSeedNodeAddresses().size());
Assert.assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed1))); Assert.assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed1)));

View file

@ -17,27 +17,25 @@
package bisq.core.payment.validation; package bisq.core.payment.validation;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.locale.CurrencyUtil; import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.asset.AssetRegistry;
import bisq.common.config.BaseCurrencyNetwork;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import bisq.asset.AssetRegistry;
public class AltCoinAddressValidatorTest { public class AltCoinAddressValidatorTest {
@Test @Test
public void test() { public void test() {
AltCoinAddressValidator validator = new AltCoinAddressValidator(new AssetRegistry()); AltCoinAddressValidator validator = new AltCoinAddressValidator(new AssetRegistry());
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); BaseCurrencyNetwork baseCurrencyNetwork = BaseCurrencyNetwork.CURRENT_NETWORK;
String currencyCode = baseCurrencyNetwork.getCurrencyCode(); String currencyCode = baseCurrencyNetwork.getCurrencyCode();
Res.setBaseCurrencyCode(currencyCode); Res.setBaseCurrencyCode(currencyCode);
Res.setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName()); Res.setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName());

View file

@ -17,7 +17,6 @@
package bisq.core.user; package bisq.core.user;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.CountryUtil; import bisq.core.locale.CountryUtil;
import bisq.core.locale.CryptoCurrency; import bisq.core.locale.CryptoCurrency;
import bisq.core.locale.CurrencyUtil; import bisq.core.locale.CurrencyUtil;
@ -25,6 +24,7 @@ import bisq.core.locale.FiatCurrency;
import bisq.core.locale.GlobalSettings; import bisq.core.locale.GlobalSettings;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.config.TestConfig;
import bisq.common.storage.Storage; import bisq.common.storage.Storage;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
@ -48,7 +48,6 @@ public class PreferencesTest {
private Preferences preferences; private Preferences preferences;
private Storage storage; private Storage storage;
private BisqEnvironment bisqEnvironment;
@Before @Before
public void setUp() { public void setUp() {
@ -59,9 +58,7 @@ public class PreferencesTest {
Res.setBaseCurrencyName("Bitcoin"); Res.setBaseCurrencyName("Bitcoin");
storage = mock(Storage.class); storage = mock(Storage.class);
bisqEnvironment = mock(BisqEnvironment.class); preferences = new Preferences(storage, new TestConfig(), null, null, null, null, null, null, null);
preferences = new Preferences(storage, bisqEnvironment, null, null, null, null, null, null, null);
} }
@Test @Test

View file

@ -17,7 +17,6 @@
package bisq.daemon.app; package bisq.daemon.app;
import bisq.core.app.BisqExecutable;
import bisq.core.app.BisqHeadlessAppMain; import bisq.core.app.BisqHeadlessAppMain;
import bisq.core.app.BisqSetup; import bisq.core.app.BisqSetup;
import bisq.core.app.CoreModule; import bisq.core.app.CoreModule;
@ -39,14 +38,8 @@ import lombok.extern.slf4j.Slf4j;
public class BisqDaemonMain extends BisqHeadlessAppMain implements BisqSetup.BisqSetupListener { public class BisqDaemonMain extends BisqHeadlessAppMain implements BisqSetup.BisqSetupListener {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (BisqExecutable.setupInitialOptionParser(args)) {
// For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
// In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
Thread.currentThread().setContextClassLoader(BisqDaemonMain.class.getClassLoader());
new BisqDaemonMain().execute(args); new BisqDaemonMain().execute(args);
} }
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// First synchronous execution tasks // First synchronous execution tasks
@ -82,7 +75,7 @@ public class BisqDaemonMain extends BisqHeadlessAppMain implements BisqSetup.Bis
@Override @Override
protected AppModule getModule() { protected AppModule getModule() {
return new CoreModule(bisqEnvironment); return new CoreModule(bisqEnvironment, config);
} }
@Override @Override

View file

@ -26,6 +26,7 @@ import bisq.core.app.AppOptionKeys;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -37,8 +38,8 @@ import java.util.ResourceBundle;
public class DesktopModule extends AppModule { public class DesktopModule extends AppModule {
public DesktopModule(Environment environment) { public DesktopModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override

View file

@ -34,7 +34,6 @@ import bisq.desktop.util.ImageUtil;
import bisq.core.app.AppOptionKeys; import bisq.core.app.AppOptionKeys;
import bisq.core.app.AvoidStandbyModeService; import bisq.core.app.AvoidStandbyModeService;
import bisq.core.app.BisqEnvironment;
import bisq.core.app.OSXStandbyModeDisabler; import bisq.core.app.OSXStandbyModeDisabler;
import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.btc.wallet.WalletsManager; import bisq.core.btc.wallet.WalletsManager;
@ -47,6 +46,7 @@ import bisq.core.user.Preferences;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.app.Log; import bisq.common.app.Log;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.setup.GracefulShutDownHandler; import bisq.common.setup.GracefulShutDownHandler;
import bisq.common.setup.UncaughtExceptionHandler; import bisq.common.setup.UncaughtExceptionHandler;
import bisq.common.util.Profiler; import bisq.common.util.Profiler;
@ -243,8 +243,8 @@ public class BisqApp extends Application implements UncaughtExceptionHandler {
// configure the primary stage // configure the primary stage
String appName = injector.getInstance(Key.get(String.class, Names.named(AppOptionKeys.APP_NAME_KEY))); String appName = injector.getInstance(Key.get(String.class, Names.named(AppOptionKeys.APP_NAME_KEY)));
if (!BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) if (!BaseCurrencyNetwork.CURRENT_NETWORK.isMainnet())
appName += " [" + Res.get(BisqEnvironment.getBaseCurrencyNetwork().name()) + "]"; appName += " [" + Res.get(BaseCurrencyNetwork.CURRENT_NETWORK.name()) + "]";
stage.setTitle(appName); stage.setTitle(appName);
stage.setScene(scene); stage.setScene(scene);

View file

@ -38,21 +38,24 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class BisqAppMain extends BisqExecutable { public class BisqAppMain extends BisqExecutable {
public static final String DEFAULT_APP_NAME = "Bisq";
private BisqApp application; private BisqApp application;
public BisqAppMain() { public BisqAppMain() {
super("Bisq Desktop", "bisq-desktop", Version.VERSION); super("Bisq Desktop", "bisq-desktop", DEFAULT_APP_NAME, Version.VERSION);
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (BisqExecutable.setupInitialOptionParser(args)) { // For some reason the JavaFX launch process results in us losing the thread
// For some reason the JavaFX launch process results in us losing the thread context class loader: reset it. // context class loader: reset it. In order to work around a bug in JavaFX 8u25
// In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method: // and below, you must include the following code as the first line of your
// realMain method:
Thread.currentThread().setContextClassLoader(BisqAppMain.class.getClassLoader()); Thread.currentThread().setContextClassLoader(BisqAppMain.class.getClassLoader());
new BisqAppMain().execute(args); new BisqAppMain().execute(args);
} }
}
@Override @Override
public void onSetupComplete() { public void onSetupComplete() {
@ -101,7 +104,7 @@ public class BisqAppMain extends BisqExecutable {
@Override @Override
protected AppModule getModule() { protected AppModule getModule() {
return new BisqAppModule(bisqEnvironment); return new BisqAppModule(bisqEnvironment, config);
} }
@Override @Override

View file

@ -22,26 +22,19 @@ import bisq.desktop.DesktopModule;
import bisq.core.app.CoreModule; import bisq.core.app.CoreModule;
import bisq.common.app.AppModule; import bisq.common.app.AppModule;
import bisq.common.config.Config;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
public class BisqAppModule extends AppModule { public class BisqAppModule extends AppModule {
public BisqAppModule(Environment environment) { public BisqAppModule(Environment environment, Config config) {
super(environment); super(environment, config);
} }
@Override @Override
protected void configure() { protected void configure() {
install(coreModule()); install(new CoreModule(environment, config));
install(desktopModule()); install(new DesktopModule(environment, config));
}
private CoreModule coreModule() {
return new CoreModule(environment);
}
private DesktopModule desktopModule() {
return new DesktopModule(environment);
} }
} }

View file

@ -20,7 +20,7 @@ package bisq.desktop.app;
import bisq.desktop.util.GUIUtil; import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.ImageUtil; import bisq.desktop.util.ImageUtil;
import bisq.core.exceptions.BisqException; import bisq.common.BisqException;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.UserThread; import bisq.common.UserThread;

View file

@ -43,7 +43,7 @@ import bisq.desktop.util.DisplayUtils;
import bisq.desktop.util.Transitions; import bisq.desktop.util.Transitions;
import bisq.core.dao.monitoring.DaoStateMonitoringService; import bisq.core.dao.monitoring.DaoStateMonitoringService;
import bisq.core.exceptions.BisqException; import bisq.common.BisqException;
import bisq.core.locale.GlobalSettings; import bisq.core.locale.GlobalSettings;
import bisq.core.locale.LanguageUtil; import bisq.core.locale.LanguageUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;

View file

@ -40,11 +40,10 @@ import bisq.desktop.util.GUIUtil;
import bisq.core.account.sign.SignedWitnessService; import bisq.core.account.sign.SignedWitnessService;
import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.alert.PrivateNotificationManager; import bisq.core.alert.PrivateNotificationManager;
import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.app.BisqSetup; import bisq.core.app.BisqSetup;
import bisq.core.btc.setup.WalletsSetup; import bisq.core.btc.setup.WalletsSetup;
import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.BtcWalletService;
import bisq.common.config.Config;
import bisq.core.locale.CryptoCurrency; import bisq.core.locale.CryptoCurrency;
import bisq.core.locale.CurrencyUtil; import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;
@ -118,7 +117,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
private final TacWindow tacWindow; private final TacWindow tacWindow;
@Getter @Getter
private final PriceFeedService priceFeedService; private final PriceFeedService priceFeedService;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final AccountAgeWitnessService accountAgeWitnessService; private final AccountAgeWitnessService accountAgeWitnessService;
@Getter @Getter
private final TorNetworkSettingsWindow torNetworkSettingsWindow; private final TorNetworkSettingsWindow torNetworkSettingsWindow;
@ -158,7 +157,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
TacWindow tacWindow, TacWindow tacWindow,
FeeService feeService, FeeService feeService,
PriceFeedService priceFeedService, PriceFeedService priceFeedService,
BisqEnvironment bisqEnvironment, Config config,
AccountAgeWitnessService accountAgeWitnessService, AccountAgeWitnessService accountAgeWitnessService,
TorNetworkSettingsWindow torNetworkSettingsWindow, TorNetworkSettingsWindow torNetworkSettingsWindow,
CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler) { CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler) {
@ -179,7 +178,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
this.notificationCenter = notificationCenter; this.notificationCenter = notificationCenter;
this.tacWindow = tacWindow; this.tacWindow = tacWindow;
this.priceFeedService = priceFeedService; this.priceFeedService = priceFeedService;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.accountAgeWitnessService = accountAgeWitnessService; this.accountAgeWitnessService = accountAgeWitnessService;
this.torNetworkSettingsWindow = torNetworkSettingsWindow; this.torNetworkSettingsWindow = torNetworkSettingsWindow;
this.corruptedDatabaseFilesHandler = corruptedDatabaseFilesHandler; this.corruptedDatabaseFilesHandler = corruptedDatabaseFilesHandler;
@ -318,7 +317,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
.onClose(() -> BisqApp.getShutDownHandler().run()) .onClose(() -> BisqApp.getShutDownHandler().run())
.show()); .show());
bisqSetup.setDisplayUpdateHandler((alert, key) -> new DisplayUpdateDownloadWindow(alert) bisqSetup.setDisplayUpdateHandler((alert, key) -> new DisplayUpdateDownloadWindow(alert, config)
.actionButtonText(Res.get("displayUpdateDownloadWindow.button.downloadLater")) .actionButtonText(Res.get("displayUpdateDownloadWindow.button.downloadLater"))
.onAction(() -> { .onAction(() -> {
preferences.dontShowAgain(key, false); // update later preferences.dontShowAgain(key, false); // update later
@ -371,8 +370,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
bisqSetup.setShowPopupIfInvalidBtcConfigHandler(this::showPopupIfInvalidBtcConfig); bisqSetup.setShowPopupIfInvalidBtcConfigHandler(this::showPopupIfInvalidBtcConfig);
corruptedDatabaseFilesHandler.getCorruptedDatabaseFiles().ifPresent(files -> new Popup() corruptedDatabaseFilesHandler.getCorruptedDatabaseFiles().ifPresent(files -> new Popup()
.warning(Res.get("popup.warning.incompatibleDB", files.toString(), .warning(Res.get("popup.warning.incompatibleDB", files.toString(), config.getAppDataDir()))
bisqEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY)))
.useShutDownButton() .useShutDownButton()
.show()); .show());
@ -438,7 +436,7 @@ public class MainViewModel implements ViewModel, BisqSetup.BisqSetupListener {
checkNumberOfBtcPeersTimer = UserThread.runAfter(() -> { checkNumberOfBtcPeersTimer = UserThread.runAfter(() -> {
// check again numPeers // check again numPeers
if (walletsSetup.numPeersProperty().get() == 0) { if (walletsSetup.numPeersProperty().get() == 0) {
if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) if (config.isLocalBitcoinNodeIsRunning())
getWalletServiceErrorMsg().set(Res.get("mainView.networkWarning.localhostBitcoinLost", Res.getBaseCurrencyName().toLowerCase())); getWalletServiceErrorMsg().set(Res.get("mainView.networkWarning.localhostBitcoinLost", Res.getBaseCurrencyName().toLowerCase()));
else else
getWalletServiceErrorMsg().set(Res.get("mainView.networkWarning.allConnectionsLost", Res.getBaseCurrencyName().toLowerCase())); getWalletServiceErrorMsg().set(Res.get("mainView.networkWarning.allConnectionsLost", Res.getBaseCurrencyName().toLowerCase()));

View file

@ -22,11 +22,10 @@ import bisq.desktop.common.view.FxmlView;
import bisq.desktop.main.overlays.popups.Popup; import bisq.desktop.main.overlays.popups.Popup;
import bisq.desktop.util.Layout; import bisq.desktop.util.Layout;
import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.core.user.Preferences; import bisq.core.user.Preferences;
import bisq.common.config.Config;
import bisq.common.storage.FileUtil; import bisq.common.storage.FileUtil;
import bisq.common.util.Tuple2; import bisq.common.util.Tuple2;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -73,10 +72,10 @@ public class BackupView extends ActivatableView<GridPane, Void> {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private BackupView(Preferences preferences, BisqEnvironment environment) { private BackupView(Preferences preferences, Config config) {
super(); super();
this.preferences = preferences; this.preferences = preferences;
dataDir = new File(environment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY)); dataDir = new File(config.getAppDataDir().getPath());
logFile = new File(Paths.get(dataDir.getPath(), "bisq.log").toString()); logFile = new File(Paths.get(dataDir.getPath(), "bisq.log").toString());
} }

View file

@ -72,7 +72,6 @@ import bisq.desktop.util.validation.UpholdValidator;
import bisq.desktop.util.validation.WeChatPayValidator; import bisq.desktop.util.validation.WeChatPayValidator;
import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.core.offer.OfferRestrictions; import bisq.core.offer.OfferRestrictions;
import bisq.core.payment.CashDepositAccount; import bisq.core.payment.CashDepositAccount;
@ -90,6 +89,7 @@ import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter; import bisq.core.util.coin.CoinFormatter;
import bisq.core.util.validation.InputValidator; import bisq.core.util.validation.InputValidator;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.util.Tuple2; import bisq.common.util.Tuple2;
import bisq.common.util.Tuple3; import bisq.common.util.Tuple3;
@ -256,7 +256,7 @@ public class FiatAccountsView extends PaymentAccountsView<GridPane, FiatAccounts
.closeButtonText(Res.get("shared.cancel")) .closeButtonText(Res.get("shared.cancel"))
.actionButtonText(Res.get("shared.iUnderstand")) .actionButtonText(Res.get("shared.iUnderstand"))
.onAction(() -> { .onAction(() -> {
final String currencyName = BisqEnvironment.getBaseCurrencyNetwork().getCurrencyName(); final String currencyName = BaseCurrencyNetwork.CURRENT_NETWORK.getCurrencyName();
if (paymentAccount instanceof ClearXchangeAccount) { if (paymentAccount instanceof ClearXchangeAccount) {
new Popup().information(Res.get("payment.clearXchange.info", currencyName, currencyName)) new Popup().information(Res.get("payment.clearXchange.info", currencyName, currencyName))
.width(900) .width(900)

View file

@ -31,7 +31,7 @@ import bisq.desktop.util.Layout;
import bisq.desktop.util.validation.BsqValidator; import bisq.desktop.util.validation.BsqValidator;
import bisq.desktop.util.validation.RegexValidator; import bisq.desktop.util.validation.RegexValidator;
import bisq.core.btc.BaseCurrencyNetwork; import bisq.common.config.BaseCurrencyNetwork;
import bisq.core.dao.DaoFacade; import bisq.core.dao.DaoFacade;
import bisq.core.dao.governance.bond.Bond; import bisq.core.dao.governance.bond.Bond;
import bisq.core.dao.governance.bond.role.BondedRole; import bisq.core.dao.governance.bond.role.BondedRole;

View file

@ -27,7 +27,6 @@ import bisq.desktop.util.FormBuilder;
import bisq.desktop.util.GUIUtil; import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.Transitions; import bisq.desktop.util.Transitions;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.GlobalSettings; import bisq.core.locale.GlobalSettings;
import bisq.core.locale.LanguageUtil; import bisq.core.locale.LanguageUtil;
import bisq.core.locale.Res; import bisq.core.locale.Res;
@ -35,6 +34,7 @@ import bisq.core.user.DontShowAgainLookup;
import bisq.common.Timer; import bisq.common.Timer;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.Config;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
@ -81,8 +81,6 @@ import javafx.collections.ObservableList;
import javafx.util.Duration; import javafx.util.Duration;
import java.nio.file.Paths;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -845,8 +843,8 @@ public abstract class Overlay<T extends Overlay<T>> {
gridPane.getChildren().add(logButton); gridPane.getChildren().add(logButton);
logButton.setOnAction(event -> { logButton.setOnAction(event -> {
try { try {
File dataDir = new File(BisqEnvironment.getStaticAppDataDir()); File dataDir = Config.CURRENT_APP_DATA_DIR;
File logFile = new File(Paths.get(dataDir.getPath(), "bisq.log").toString()); File logFile = new File(dataDir, "bisq.log");
Utilities.openFile(logFile); Utilities.openFile(logFile);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -17,6 +17,7 @@
package bisq.desktop.main.overlays.windows; package bisq.desktop.main.overlays.windows;
import bisq.desktop.app.BisqAppMain;
import bisq.desktop.components.AutoTooltipToggleButton; import bisq.desktop.components.AutoTooltipToggleButton;
import bisq.desktop.main.overlays.Overlay; import bisq.desktop.main.overlays.Overlay;
@ -101,7 +102,7 @@ public class DaoLaunchWindow extends Overlay<DaoLaunchWindow> {
@Override @Override
protected void addHeadLine() { protected void addHeadLine() {
Label versionNumber = addLabel(gridPane, ++rowIndex, BisqEnvironment.DEFAULT_APP_NAME + " v1.0"); Label versionNumber = addLabel(gridPane, ++rowIndex, BisqAppMain.DEFAULT_APP_NAME + " v1.0");
versionNumber.getStyleClass().add("dao-launch-version"); versionNumber.getStyleClass().add("dao-launch-version");
GridPane.setColumnSpan(versionNumber, 2); GridPane.setColumnSpan(versionNumber, 2);
Label headlineLabel = addLabel(gridPane, ++rowIndex, headLine); Label headlineLabel = addLabel(gridPane, ++rowIndex, headLine);

View file

@ -17,6 +17,7 @@
package bisq.desktop.main.overlays.windows; package bisq.desktop.main.overlays.windows;
import bisq.desktop.app.BisqAppMain;
import bisq.desktop.components.AutoTooltipLabel; import bisq.desktop.components.AutoTooltipLabel;
import bisq.desktop.components.ExternalHyperlink; import bisq.desktop.components.ExternalHyperlink;
import bisq.desktop.components.HyperlinkWithIcon; import bisq.desktop.components.HyperlinkWithIcon;
@ -83,7 +84,7 @@ public class NewTradeProtocolLaunchWindow extends Overlay<NewTradeProtocolLaunch
@Override @Override
protected void addHeadLine() { protected void addHeadLine() {
Label versionNumber = new AutoTooltipLabel(BisqEnvironment.DEFAULT_APP_NAME + " v1.2"); Label versionNumber = new AutoTooltipLabel(BisqAppMain.DEFAULT_APP_NAME + " v1.2");
versionNumber.getStyleClass().add("news-version"); versionNumber.getStyleClass().add("news-version");
HBox.setHgrow(versionNumber, Priority.ALWAYS); HBox.setHgrow(versionNumber, Priority.ALWAYS);
versionNumber.setMaxWidth(Double.MAX_VALUE); versionNumber.setMaxWidth(Double.MAX_VALUE);

View file

@ -27,6 +27,7 @@ import bisq.core.alert.Alert;
import bisq.core.app.BisqEnvironment; import bisq.core.app.BisqEnvironment;
import bisq.core.locale.Res; import bisq.core.locale.Res;
import bisq.common.config.Config;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
@ -71,6 +72,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j @Slf4j
public class DisplayUpdateDownloadWindow extends Overlay<DisplayUpdateDownloadWindow> { public class DisplayUpdateDownloadWindow extends Overlay<DisplayUpdateDownloadWindow> {
private final Alert alert; private final Alert alert;
private final Config config;
private Optional<DownloadTask> downloadTaskOptional; private Optional<DownloadTask> downloadTaskOptional;
private VerifyTask verifyTask; private VerifyTask verifyTask;
private ProgressBar progressBar; private ProgressBar progressBar;
@ -81,9 +83,9 @@ public class DisplayUpdateDownloadWindow extends Overlay<DisplayUpdateDownloadWi
// Public API // Public API
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public DisplayUpdateDownloadWindow(Alert alert) { public DisplayUpdateDownloadWindow(Alert alert, Config config) {
this.alert = alert; this.alert = alert;
this.config = config;
this.type = Type.Attention; this.type = Type.Attention;
} }
@ -291,7 +293,7 @@ public class DisplayUpdateDownloadWindow extends Overlay<DisplayUpdateDownloadWi
scanner.close(); scanner.close();
final String hashOfJar = sb.toString(); final String hashOfJar = sb.toString();
Path path = Paths.get(BisqEnvironment.getStaticAppDataDir(), fileDescriptor.getFileName()); Path path = Paths.get(config.getAppDataDir().getPath(), fileDescriptor.getFileName());
final String target = path.toString(); final String target = path.toString();
try (PrintWriter writer = new PrintWriter(target, "UTF-8")) { try (PrintWriter writer = new PrintWriter(target, "UTF-8")) {
writer.println(hashOfJar); writer.println(hashOfJar);

View file

@ -29,7 +29,6 @@ import bisq.desktop.main.overlays.windows.TorNetworkSettingsWindow;
import bisq.desktop.util.GUIUtil; import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.validation.RegexValidator; import bisq.desktop.util.validation.RegexValidator;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.nodes.BtcNodes; import bisq.core.btc.nodes.BtcNodes;
import bisq.core.btc.setup.WalletsSetup; import bisq.core.btc.setup.WalletsSetup;
import bisq.core.filter.Filter; import bisq.core.filter.Filter;
@ -43,6 +42,7 @@ import bisq.network.p2p.network.Statistic;
import bisq.common.ClockWatcher; import bisq.common.ClockWatcher;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.config.Config;
import javax.inject.Inject; import javax.inject.Inject;
@ -108,7 +108,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
private final Preferences preferences; private final Preferences preferences;
private final BtcNodes btcNodes; private final BtcNodes btcNodes;
private final FilterManager filterManager; private final FilterManager filterManager;
private final BisqEnvironment bisqEnvironment; private final Config config;
private final TorNetworkSettingsWindow torNetworkSettingsWindow; private final TorNetworkSettingsWindow torNetworkSettingsWindow;
private final ClockWatcher clockWatcher; private final ClockWatcher clockWatcher;
private final WalletsSetup walletsSetup; private final WalletsSetup walletsSetup;
@ -137,7 +137,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
Preferences preferences, Preferences preferences,
BtcNodes btcNodes, BtcNodes btcNodes,
FilterManager filterManager, FilterManager filterManager,
BisqEnvironment bisqEnvironment, Config config,
TorNetworkSettingsWindow torNetworkSettingsWindow, TorNetworkSettingsWindow torNetworkSettingsWindow,
ClockWatcher clockWatcher) { ClockWatcher clockWatcher) {
super(); super();
@ -146,7 +146,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
this.preferences = preferences; this.preferences = preferences;
this.btcNodes = btcNodes; this.btcNodes = btcNodes;
this.filterManager = filterManager; this.filterManager = filterManager;
this.bisqEnvironment = bisqEnvironment; this.config = config;
this.torNetworkSettingsWindow = torNetworkSettingsWindow; this.torNetworkSettingsWindow = torNetworkSettingsWindow;
this.clockWatcher = clockWatcher; this.clockWatcher = clockWatcher;
} }
@ -165,7 +165,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
bitcoinPeerSubVersionColumn.setGraphic(new AutoTooltipLabel(Res.get("settings.net.subVersionColumn"))); bitcoinPeerSubVersionColumn.setGraphic(new AutoTooltipLabel(Res.get("settings.net.subVersionColumn")));
bitcoinPeerHeightColumn.setGraphic(new AutoTooltipLabel(Res.get("settings.net.heightColumn"))); bitcoinPeerHeightColumn.setGraphic(new AutoTooltipLabel(Res.get("settings.net.heightColumn")));
localhostBtcNodeInfoLabel.setText(Res.get("settings.net.localhostBtcNodeInfo")); localhostBtcNodeInfoLabel.setText(Res.get("settings.net.localhostBtcNodeInfo"));
if (!bisqEnvironment.isBitcoinLocalhostNodeRunning()) { if (!config.isLocalBitcoinNodeIsRunning()) {
localhostBtcNodeInfoLabel.setVisible(false); localhostBtcNodeInfoLabel.setVisible(false);
} }
useProvidedNodesRadio.setText(Res.get("settings.net.useProvidedNodesRadio")); useProvidedNodesRadio.setText(Res.get("settings.net.useProvidedNodesRadio"));
@ -380,7 +380,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
} }
private void onBitcoinPeersToggleSelected(boolean calledFromUser) { private void onBitcoinPeersToggleSelected(boolean calledFromUser) {
boolean bitcoinLocalhostNodeRunning = bisqEnvironment.isBitcoinLocalhostNodeRunning(); boolean bitcoinLocalhostNodeRunning = config.isLocalBitcoinNodeIsRunning();
useTorForBtcJCheckBox.setDisable(bitcoinLocalhostNodeRunning); useTorForBtcJCheckBox.setDisable(bitcoinLocalhostNodeRunning);
bitcoinNodesLabel.setDisable(bitcoinLocalhostNodeRunning); bitcoinNodesLabel.setDisable(bitcoinLocalhostNodeRunning);
btcNodesLabel.setDisable(bitcoinLocalhostNodeRunning); btcNodesLabel.setDisable(bitcoinLocalhostNodeRunning);
@ -460,7 +460,7 @@ public class NetworkSettingsView extends ActivatableView<GridPane, Void> {
private void applyPreventPublicBtcNetwork() { private void applyPreventPublicBtcNetwork() {
final boolean preventPublicBtcNetwork = isPreventPublicBtcNetwork(); final boolean preventPublicBtcNetwork = isPreventPublicBtcNetwork();
usePublicNodesRadio.setDisable(bisqEnvironment.isBitcoinLocalhostNodeRunning() || preventPublicBtcNetwork); usePublicNodesRadio.setDisable(config.isLocalBitcoinNodeIsRunning() || preventPublicBtcNetwork);
if (preventPublicBtcNetwork && selectedBitcoinNodesOption == BtcNodes.BitcoinNodesOption.PUBLIC) { if (preventPublicBtcNetwork && selectedBitcoinNodesOption == BtcNodes.BitcoinNodesOption.PUBLIC) {
selectedBitcoinNodesOption = BtcNodes.BitcoinNodesOption.PROVIDED; selectedBitcoinNodesOption = BtcNodes.BitcoinNodesOption.PROVIDED;
preferences.setBitcoinNodesOptionOrdinal(selectedBitcoinNodesOption.ordinal()); preferences.setBitcoinNodesOptionOrdinal(selectedBitcoinNodesOption.ordinal());

View file

@ -30,7 +30,6 @@ import bisq.desktop.util.ImageUtil;
import bisq.desktop.util.Layout; import bisq.desktop.util.Layout;
import bisq.desktop.util.validation.RegexValidator; import bisq.desktop.util.validation.RegexValidator;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.wallet.Restrictions; import bisq.core.btc.wallet.Restrictions;
import bisq.core.dao.DaoFacade; import bisq.core.dao.DaoFacade;
import bisq.core.dao.DaoOptionKeys; import bisq.core.dao.DaoOptionKeys;
@ -53,6 +52,7 @@ import bisq.core.util.validation.IntegerValidator;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.util.Tuple3; import bisq.common.util.Tuple3;
import bisq.common.util.Utilities; import bisq.common.util.Utilities;
@ -273,7 +273,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Preferenc
String estimatedFee = String.valueOf(feeService.getTxFeePerByte().value); String estimatedFee = String.valueOf(feeService.getTxFeePerByte().value);
try { try {
int withdrawalTxFeePerByte = Integer.parseInt(transactionFeeInputTextField.getText()); int withdrawalTxFeePerByte = Integer.parseInt(transactionFeeInputTextField.getText());
final long minFeePerByte = BisqEnvironment.getBaseCurrencyNetwork().getDefaultMinFeePerByte(); final long minFeePerByte = BaseCurrencyNetwork.CURRENT_NETWORK.getDefaultMinFeePerByte();
if (withdrawalTxFeePerByte < minFeePerByte) { if (withdrawalTxFeePerByte < minFeePerByte) {
new Popup().warning(Res.get("setting.preferences.txFeeMin", minFeePerByte)).show(); new Popup().warning(Res.get("setting.preferences.txFeeMin", minFeePerByte)).show();
transactionFeeInputTextField.setText(estimatedFee); transactionFeeInputTextField.setText(estimatedFee);
@ -650,7 +650,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Preferenc
.collect(Collectors.toList()); .collect(Collectors.toList());
selectBaseCurrencyNetworkComboBox.setItems(FXCollections.observableArrayList(baseCurrencyNetworks)); selectBaseCurrencyNetworkComboBox.setItems(FXCollections.observableArrayList(baseCurrencyNetworks));
selectBaseCurrencyNetworkComboBox.setOnAction(e -> onSelectNetwork()); selectBaseCurrencyNetworkComboBox.setOnAction(e -> onSelectNetwork());
selectBaseCurrencyNetworkComboBox.getSelectionModel().select(BisqEnvironment.getBaseCurrencyNetwork());*/ selectBaseCurrencyNetworkComboBox.getSelectionModel().select(BaseCurrencyNetwork.CURRENT_VALUE);*/
boolean useCustomWithdrawalTxFee = preferences.isUseCustomWithdrawalTxFee(); boolean useCustomWithdrawalTxFee = preferences.isUseCustomWithdrawalTxFee();
useCustomFee.setSelected(useCustomWithdrawalTxFee); useCustomFee.setSelected(useCustomWithdrawalTxFee);
@ -920,7 +920,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Preferenc
} }
/* private void onSelectNetwork() { /* private void onSelectNetwork() {
if (selectBaseCurrencyNetworkComboBox.getSelectionModel().getSelectedItem() != BisqEnvironment.getBaseCurrencyNetwork()) if (selectBaseCurrencyNetworkComboBox.getSelectionModel().getSelectedItem() != BaseCurrencyNetwork.CURRENT_VALUE)
selectNetwork(); selectNetwork();
} }
@ -932,7 +932,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Preferenc
}) })
.actionButtonText(Res.get("shared.shutDown")) .actionButtonText(Res.get("shared.shutDown"))
.closeButtonText(Res.get("shared.cancel")) .closeButtonText(Res.get("shared.cancel"))
.onClose(() -> selectBaseCurrencyNetworkComboBox.getSelectionModel().select(BisqEnvironment.getBaseCurrencyNetwork())) .onClose(() -> selectBaseCurrencyNetworkComboBox.getSelectionModel().select(BaseCurrencyNetwork.CURRENT_VALUE))
.show(); .show();
}*/ }*/

View file

@ -31,7 +31,6 @@ import bisq.desktop.util.validation.RegexValidator;
import bisq.core.account.witness.AccountAgeWitness; import bisq.core.account.witness.AccountAgeWitness;
import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.account.witness.AccountAgeWitnessService;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.setup.WalletsSetup; import bisq.core.btc.setup.WalletsSetup;
import bisq.core.btc.wallet.WalletsManager; import bisq.core.btc.wallet.WalletsManager;
import bisq.core.locale.Country; import bisq.core.locale.Country;
@ -59,6 +58,7 @@ import bisq.network.p2p.P2PService;
import bisq.common.UserThread; import bisq.common.UserThread;
import bisq.common.app.DevEnv; import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.proto.persistable.PersistableList; import bisq.common.proto.persistable.PersistableList;
import bisq.common.proto.persistable.PersistenceProtoResolver; import bisq.common.proto.persistable.PersistenceProtoResolver;
import bisq.common.storage.CorruptedDatabaseFilesHandler; import bisq.common.storage.CorruptedDatabaseFilesHandler;
@ -692,7 +692,7 @@ public class GUIUtil {
public static void showClearXchangeWarning() { public static void showClearXchangeWarning() {
String key = "confirmClearXchangeRequirements"; String key = "confirmClearXchangeRequirements";
final String currencyName = BisqEnvironment.getBaseCurrencyNetwork().getCurrencyName(); final String currencyName = BaseCurrencyNetwork.CURRENT_NETWORK.getCurrencyName();
new Popup().information(Res.get("payment.clearXchange.info", currencyName, currencyName)) new Popup().information(Res.get("payment.clearXchange.info", currencyName, currencyName))
.width(900) .width(900)
.closeButtonText(Res.get("shared.iConfirm")) .closeButtonText(Res.get("shared.iConfirm"))
@ -702,7 +702,7 @@ public class GUIUtil {
public static String getBitcoinURI(String address, Coin amount, String label) { public static String getBitcoinURI(String address, Coin amount, String label) {
return address != null ? return address != null ?
BitcoinURI.convertToBitcoinURI(Address.fromBase58(BisqEnvironment.getParameters(), BitcoinURI.convertToBitcoinURI(Address.fromBase58(BaseCurrencyNetwork.CURRENT_PARAMETERS,
address), amount, label, null) : address), amount, label, null) :
""; "";
} }

View file

@ -53,6 +53,7 @@ import bisq.network.p2p.network.BridgeAddressProvider;
import bisq.network.p2p.seed.SeedNodeRepository; import bisq.network.p2p.seed.SeedNodeRepository;
import bisq.common.ClockWatcher; import bisq.common.ClockWatcher;
import bisq.common.config.TestConfig;
import bisq.common.crypto.KeyRing; import bisq.common.crypto.KeyRing;
import bisq.common.crypto.KeyStorage; import bisq.common.crypto.KeyStorage;
import bisq.common.crypto.PubKeyRing; import bisq.common.crypto.PubKeyRing;
@ -82,7 +83,7 @@ public class GuiceSetupTest {
Res.setup(); Res.setup();
CurrencyUtil.setup(); CurrencyUtil.setup();
injector = Guice.createInjector(new BisqAppModule(new BisqEnvironment(new MockPropertySource()))); injector = Guice.createInjector(new BisqAppModule(new BisqEnvironment(new MockPropertySource()), new TestConfig()));
} }
@Test @Test

Some files were not shown because too many files have changed in this diff Show more