Reformat Java sources with Editorconfig settings

This change is the result of a global reformatting in IDEA now that
`.editorconfig` settings are in place. Note that Editorconfig's
`continuation_indent_size` property [1] was also added and set to 8
here, as this reflects the dominant style already present in the
codebase. i.e. in created a much smaller diff to set the continuation
indent to 8 that would have been created leaving this property out and
letting it default to 4.

[1]: https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties
This commit is contained in:
Chris Beams 2017-11-04 20:11:30 +01:00
parent d8845f0cc6
commit e1a6f87a98
No known key found for this signature in database
GPG Key ID: 3D214F8F5BC5ED73
62 changed files with 1602 additions and 1607 deletions

View File

@ -3,6 +3,7 @@ root = true
[*]
indent_style = space
indent_size = 4
continuation_indent_size = 8
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true

View File

@ -29,7 +29,7 @@ public class Version {
// VERSION = 0.5.0 introduces proto buffer for the P2P network and local DB and is a not backward compatible update
// Therefore all sub versions start again with 1
// We use semantic versioning with major, minor and patch
public static final String VERSION = "0.5.3";
public static final String VERSION = "0.5.3";
public static int getMajorVersion(String version) {
return getSubVersion(version, 0);

View File

@ -30,7 +30,7 @@ public class CountryUtil {
public static List<Country> getAllSepaEuroCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"AT", "BE", "CY", "DE", "EE", "FI", "FR", "GR", "IE",
"IT", "LV", "LT", "LU", "MC", "MT", "NL", "PT", "SK", "SI", "ES"};
"IT", "LV", "LT", "LU", "MC", "MT", "NL", "PT", "SK", "SI", "ES"};
populateCountryListByCodes(list, codes);
list.sort((a, b) -> a.name.compareTo(b.name));
@ -59,7 +59,7 @@ public class CountryUtil {
public static List<Country> getAllSepaNonEuroCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"BG", "HR", "CZ", "DK", "GB", "HU", "PL", "RO",
"SE", "IS", "NO", "LI", "CH"};
"SE", "IS", "NO", "LI", "CH"};
populateCountryListByCodes(list, codes);
list.sort((a, b) -> a.name.compareTo(b.name));
return list;
@ -129,7 +129,7 @@ public class CountryUtil {
public static List<Country> getAllCountriesForRegion(Region selectedRegion) {
return Lists.newArrayList(Collections2.filter(getAllCountries(), country ->
selectedRegion != null && country != null && selectedRegion.equals(country.region)));
selectedRegion != null && country != null && selectedRegion.equals(country.region)));
}
public static List<Country> getAllCountries() {
@ -157,7 +157,7 @@ public class CountryUtil {
// Filter duplicate locale entries
Set<Locale> allLocalesAsSet = allLocales.stream().filter(locale -> !locale.getCountry().isEmpty())
.collect(Collectors.toSet());
.collect(Collectors.toSet());
List<Locale> allCountryLocales = new ArrayList<>();
allCountryLocales.addAll(allLocalesAsSet);

View File

@ -35,8 +35,8 @@ public class CurrencyUtil {
private static List<FiatCurrency> createAllSortedFiatCurrenciesList() {
Set<FiatCurrency> set = CountryUtil.getAllCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
List<FiatCurrency> list = new ArrayList<>(set);
list.sort(TradeCurrency::compareTo);
return list;
@ -188,34 +188,34 @@ public class CurrencyUtil {
*/
private static Set<TradeCurrency> getSortedSEPACurrencyCodes() {
return CountryUtil.getAllSepaCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
}
// At OKPay you can exchange internally those currencies
public static List<TradeCurrency> getAllOKPayCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("EUR"),
new FiatCurrency("USD"),
new FiatCurrency("GBP"),
new FiatCurrency("CHF"),
new FiatCurrency("RUB"),
new FiatCurrency("PLN"),
new FiatCurrency("JPY"),
new FiatCurrency("CAD"),
new FiatCurrency("AUD"),
new FiatCurrency("CZK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("DKK"),
new FiatCurrency("HRK"),
new FiatCurrency("HUF"),
new FiatCurrency("NZD"),
new FiatCurrency("RON"),
new FiatCurrency("TRY"),
new FiatCurrency("ZAR"),
new FiatCurrency("HKD"),
new FiatCurrency("CNY")
new FiatCurrency("EUR"),
new FiatCurrency("USD"),
new FiatCurrency("GBP"),
new FiatCurrency("CHF"),
new FiatCurrency("RUB"),
new FiatCurrency("PLN"),
new FiatCurrency("JPY"),
new FiatCurrency("CAD"),
new FiatCurrency("AUD"),
new FiatCurrency("CZK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("DKK"),
new FiatCurrency("HRK"),
new FiatCurrency("HUF"),
new FiatCurrency("NZD"),
new FiatCurrency("RON"),
new FiatCurrency("TRY"),
new FiatCurrency("ZAR"),
new FiatCurrency("HKD"),
new FiatCurrency("CNY")
));
currencies.sort(TradeCurrency::compareTo);
return currencies;

View File

@ -54,11 +54,11 @@ public class Utilities {
// TODO check out Jackson lib
public static String objectToJson(Object object) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new AnnotationExclusionStrategy())
.setExclusionStrategies(new AnnotationExclusionStrategy())
/*.excludeFieldsWithModifiers(Modifier.TRANSIENT)*/
/* .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)*/
.setPrettyPrinting()
.create();
.setPrettyPrinting()
.create();
return gson.toJson(object);
}
@ -74,11 +74,11 @@ public class Utilities {
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
.setNameFormat(name)
.setDaemon(true)
.build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
return executor;
@ -91,10 +91,10 @@ public class Utilities {
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
@ -132,8 +132,8 @@ public class Utilities {
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
return arch.endsWith("64")
|| wow64Arch != null && wow64Arch.endsWith("64")
? "64" : "32";
|| wow64Arch != null && wow64Arch.endsWith("64")
? "64" : "32";
} else if (osArch.contains("arm")) {
// armv8 is 64 bit, armv7l is 32 bit
return osArch.contains("64") || osArch.contains("v8") ? "64" : "32";
@ -146,12 +146,12 @@ public class Utilities {
public static void printSysInfo() {
log.info("System info: os.name={}; os.version={}; os.arch={}; sun.arch.data.model={}; JRE={}; JVM={}",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
getJVMArchitecture(),
(System.getProperty("java.runtime.version", "-") + " (" + System.getProperty("java.vendor", "-") + ")"),
(System.getProperty("java.vm.version", "-") + " (" + System.getProperty("java.vm.name", "-") + ")")
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
getJVMArchitecture(),
(System.getProperty("java.runtime.version", "-") + " (" + System.getProperty("java.vendor", "-") + ")"),
(System.getProperty("java.vm.version", "-") + " (" + System.getProperty("java.vm.name", "-") + ")")
);
}
@ -173,8 +173,8 @@ public class Utilities {
public static void openURI(URI uri) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.BROWSE)) {
&& isDesktopSupported()
&& getDesktop().isSupported(Action.BROWSE)) {
getDesktop().browse(uri);
} else {
// Maybe Application.HostServices works in those cases?
@ -190,8 +190,8 @@ public class Utilities {
public static void openFile(File file) throws IOException {
if (!isLinux()
&& isDesktopSupported()
&& getDesktop().isSupported(Action.OPEN)) {
&& isDesktopSupported()
&& getDesktop().isSupported(Action.OPEN)) {
getDesktop().open(file);
} else {
// Maybe Application.HostServices works in those cases?
@ -256,7 +256,7 @@ public class Utilities {
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
Gson gson =
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.fromJson(jsonString, classOfT);
}
@ -370,7 +370,7 @@ public class Utilities {
public static boolean isCtrlPressed(KeyCode keyCode, KeyEvent keyEvent) {
return new KeyCodeCombination(keyCode, KeyCombination.SHORTCUT_DOWN).match(keyEvent) ||
new KeyCodeCombination(keyCode, KeyCombination.CONTROL_DOWN).match(keyEvent);
new KeyCodeCombination(keyCode, KeyCombination.CONTROL_DOWN).match(keyEvent);
}
public static boolean isAltPressed(KeyCode keyCode, KeyEvent keyEvent) {
@ -523,6 +523,6 @@ public class Utilities {
final String name = System.getProperty("java.runtime.name");
final String ver = System.getProperty("java.version");
return name != null && name.equals("Java(TM) SE Runtime Environment")
&& ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
&& ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
}
}

View File

@ -18,11 +18,11 @@
package io.bisq.consensus;
/**
* Market interface for classes which are used in the trade contract.
* Market interface for classes which are used in the trade contract.
* Any change of the class fields would breaking backward compatibility.
* If a field needs to get added it needs to be annotated with @JsonExclude (thus excluded from the contract JSON).
* Better to use the excludeFromJsonDataMap (annotated with @JsonExclude; used in PaymentAccountPayload) to
* add a key/value pair.
* If a field needs to get added it needs to be annotated with @JsonExclude (thus excluded from the contract JSON).
* Better to use the excludeFromJsonDataMap (annotated with @JsonExclude; used in PaymentAccountPayload) to
* add a key/value pair.
*/
public interface RestrictedByContractJson {
}

View File

@ -55,8 +55,8 @@ public class AppSetupWithP2P extends AppSetup {
AccountAgeWitnessService accountAgeWitnessService,
FilterManager filterManager) {
super(encryptionService,
keyRing,
tradeStatisticsManager);
keyRing,
tradeStatisticsManager);
this.p2PService = p2PService;
this.accountAgeWitnessService = accountAgeWitnessService;
this.filterManager = filterManager;
@ -82,10 +82,10 @@ public class AppSetupWithP2P extends AppSetup {
@Override
protected void initBasicServices() {
readMapsFromResourcesBinding = EasyBind.combine(SetupUtils.readPersistableNetworkPayloadMapFromResources(p2PService),
SetupUtils.readEntryMapFromResources(p2PService),
(result1, result2) -> {
return result1 && result2;
});
SetupUtils.readEntryMapFromResources(p2PService),
(result1, result2) -> {
return result1 && result2;
});
readMapsFromResourcesBindingSubscription = readMapsFromResourcesBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue)
startInitP2PNetwork();
@ -118,7 +118,7 @@ public class AppSetupWithP2P extends AppSetup {
// We only check at seed nodes as they are running the latest version
// Other disconnects might be caused by peers running an older version
if (connection.getPeerType() == Connection.PeerType.SEED_NODE &&
closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason);
log.warn("RULE_VIOLATION onDisconnect connection=" + connection);
}

View File

@ -41,11 +41,11 @@ public class AppSetupWithP2PAndDAO extends AppSetupWithP2P {
FilterManager filterManager,
BsqBlockchainManager bsqBlockchainManager) {
super(encryptionService,
keyRing,
p2PService,
tradeStatisticsManager,
accountAgeWitnessService,
filterManager);
keyRing,
p2PService,
tradeStatisticsManager,
accountAgeWitnessService,
filterManager);
this.bsqBlockchainManager = bsqBlockchainManager;
}

View File

@ -174,93 +174,93 @@ public class BisqEnvironment extends StandardEnvironment {
private List<String> bannedSeedNodes;
private final String btcNodes, seedNodes, ignoreDevMsg, useTorForBtc, rpcUser, rpcPassword,
rpcPort, rpcBlockNotificationPort, dumpBlockchainData, fullDaoNode,
myAddress, banList, dumpStatistics, maxMemory, socks5ProxyBtcAddress,
socks5ProxyHttpAddress;
rpcPort, rpcBlockNotificationPort, dumpBlockchainData, fullDaoNode,
myAddress, banList, dumpStatistics, maxMemory, socks5ProxyBtcAddress,
socks5ProxyHttpAddress;
public BisqEnvironment(OptionSet options) {
this(new JOptCommandLinePropertySource(BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull(
options)));
options)));
}
@SuppressWarnings("ConstantConditions")
public BisqEnvironment(PropertySource commandLineProperties) {
//CommonOptionKeys
logLevel = commandLineProperties.containsProperty(CommonOptionKeys.LOG_LEVEL_KEY) ?
(String) commandLineProperties.getProperty(CommonOptionKeys.LOG_LEVEL_KEY) :
LOG_LEVEL_DEFAULT;
(String) commandLineProperties.getProperty(CommonOptionKeys.LOG_LEVEL_KEY) :
LOG_LEVEL_DEFAULT;
//AppOptionKeys
userDataDir = commandLineProperties.containsProperty(AppOptionKeys.USER_DATA_DIR_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.USER_DATA_DIR_KEY) :
DEFAULT_USER_DATA_DIR;
(String) commandLineProperties.getProperty(AppOptionKeys.USER_DATA_DIR_KEY) :
DEFAULT_USER_DATA_DIR;
appName = commandLineProperties.containsProperty(AppOptionKeys.APP_NAME_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.APP_NAME_KEY) :
DEFAULT_APP_NAME;
(String) commandLineProperties.getProperty(AppOptionKeys.APP_NAME_KEY) :
DEFAULT_APP_NAME;
appDataDir = commandLineProperties.containsProperty(AppOptionKeys.APP_DATA_DIR_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.APP_DATA_DIR_KEY) :
appDataDir(userDataDir, appName);
(String) commandLineProperties.getProperty(AppOptionKeys.APP_DATA_DIR_KEY) :
appDataDir(userDataDir, appName);
ignoreDevMsg = commandLineProperties.containsProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY) :
"";
(String) commandLineProperties.getProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY) :
"";
dumpStatistics = commandLineProperties.containsProperty(AppOptionKeys.DUMP_STATISTICS) ?
(String) commandLineProperties.getProperty(AppOptionKeys.DUMP_STATISTICS) :
"";
(String) commandLineProperties.getProperty(AppOptionKeys.DUMP_STATISTICS) :
"";
maxMemory = commandLineProperties.containsProperty(AppOptionKeys.MAX_MEMORY) ?
(String) commandLineProperties.getProperty(AppOptionKeys.MAX_MEMORY) :
"";
(String) commandLineProperties.getProperty(AppOptionKeys.MAX_MEMORY) :
"";
providers = commandLineProperties.containsProperty(AppOptionKeys.PROVIDERS) ?
(String) commandLineProperties.getProperty(AppOptionKeys.PROVIDERS) :
"";
(String) commandLineProperties.getProperty(AppOptionKeys.PROVIDERS) :
"";
//NetworkOptionKeys
seedNodes = commandLineProperties.containsProperty(NetworkOptionKeys.SEED_NODES_KEY) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SEED_NODES_KEY) :
"";
(String) commandLineProperties.getProperty(NetworkOptionKeys.SEED_NODES_KEY) :
"";
myAddress = commandLineProperties.containsProperty(NetworkOptionKeys.MY_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.MY_ADDRESS) :
"";
(String) commandLineProperties.getProperty(NetworkOptionKeys.MY_ADDRESS) :
"";
banList = commandLineProperties.containsProperty(NetworkOptionKeys.BAN_LIST) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.BAN_LIST) :
"";
(String) commandLineProperties.getProperty(NetworkOptionKeys.BAN_LIST) :
"";
socks5ProxyBtcAddress = commandLineProperties.containsProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS) :
"";
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS) :
"";
socks5ProxyHttpAddress = commandLineProperties.containsProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS) ?
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS) :
"";
(String) commandLineProperties.getProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS) :
"";
//RpcOptionKeys
rpcUser = commandLineProperties.containsProperty(DaoOptionKeys.RPC_USER) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_USER) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_USER) :
"";
rpcPassword = commandLineProperties.containsProperty(DaoOptionKeys.RPC_PASSWORD) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_PASSWORD) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_PASSWORD) :
"";
rpcPort = commandLineProperties.containsProperty(DaoOptionKeys.RPC_PORT) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_PORT) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_PORT) :
"";
rpcBlockNotificationPort = commandLineProperties.containsProperty(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT) :
"";
dumpBlockchainData = commandLineProperties.containsProperty(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA) :
"";
fullDaoNode = commandLineProperties.containsProperty(DaoOptionKeys.FULL_DAO_NODE) ?
(String) commandLineProperties.getProperty(DaoOptionKeys.FULL_DAO_NODE) :
"";
(String) commandLineProperties.getProperty(DaoOptionKeys.FULL_DAO_NODE) :
"";
btcNodes = commandLineProperties.containsProperty(BtcOptionKeys.BTC_NODES) ?
(String) commandLineProperties.getProperty(BtcOptionKeys.BTC_NODES) :
"";
(String) commandLineProperties.getProperty(BtcOptionKeys.BTC_NODES) :
"";
useTorForBtc = commandLineProperties.containsProperty(BtcOptionKeys.USE_TOR_FOR_BTC) ?
(String) commandLineProperties.getProperty(BtcOptionKeys.USE_TOR_FOR_BTC) :
"";
(String) commandLineProperties.getProperty(BtcOptionKeys.USE_TOR_FOR_BTC) :
"";
MutablePropertySources propertySources = this.getPropertySources();
propertySources.addFirst(commandLineProperties);
@ -274,7 +274,7 @@ public class BisqEnvironment extends StandardEnvironment {
bannedSeedNodes = !bannedSeedNodesAsString.isEmpty() ? Arrays.asList(StringUtils.deleteWhitespace(bannedSeedNodesAsString).split(",")) : null;
baseCurrencyNetwork = BaseCurrencyNetwork.valueOf(getProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK,
getDefaultBaseCurrencyNetwork().name()).toUpperCase());
getDefaultBaseCurrencyNetwork().name()).toUpperCase());
btcNetworkDir = Paths.get(appDataDir, baseCurrencyNetwork.name().toLowerCase()).toString();
File btcNetworkDirFile = new File(btcNetworkDir);

View File

@ -65,24 +65,24 @@ public class ArbitratorManager {
@SuppressWarnings("ConstantConditions")
private static final List<String> publicKeys = DevEnv.USE_DEV_PRIVILEGE_KEYS ?
new ArrayList<>(Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY)) :
new ArrayList<>(Arrays.asList(
"0365c6af94681dbee69de1851f98d4684063bf5c2d64b1c73ed5d90434f375a054",
"031c502a60f9dbdb5ae5e438a79819e4e1f417211dd537ac12c9bc23246534c4bd",
"02c1e5a242387b6d5319ce27246cea6edaaf51c3550591b528d2578a4753c56c2c",
"025c319faf7067d9299590dd6c97fe7e56cd4dac61205ccee1cd1fc390142390a2",
"038f6e24c2bfe5d51d0a290f20a9a657c270b94ef2b9c12cd15ca3725fa798fc55",
"0255256ff7fb615278c4544a9bbd3f5298b903b8a011cd7889be19b6b1c45cbefe",
"024a3a37289f08c910fbd925ebc72b946f33feaeff451a4738ee82037b4cda2e95",
"02a88b75e9f0f8afba1467ab26799dcc38fd7a6468fb2795444b425eb43e2c10bd",
"02349a51512c1c04c67118386f4d27d768c5195a83247c150a4b722d161722ba81",
"03f718a2e0dc672c7cdec0113e72c3322efc70412bb95870750d25c32cd98de17d",
"028ff47ee2c56e66313928975c58fa4f1b19a0f81f3a96c4e9c9c3c6768075509e",
"02b517c0cbc3a49548f448ddf004ed695c5a1c52ec110be1bfd65fa0ca0761c94b",
"03df837a3a0f3d858e82f3356b71d1285327f101f7c10b404abed2abc1c94e7169",
"0203a90fb2ab698e524a5286f317a183a84327b8f8c3f7fa4a98fec9e1cefd6b72",
"023c99cc073b851c892d8c43329ca3beb5d2213ee87111af49884e3ce66cbd5ba5"
));
new ArrayList<>(Collections.singletonList(DevEnv.DEV_PRIVILEGE_PUB_KEY)) :
new ArrayList<>(Arrays.asList(
"0365c6af94681dbee69de1851f98d4684063bf5c2d64b1c73ed5d90434f375a054",
"031c502a60f9dbdb5ae5e438a79819e4e1f417211dd537ac12c9bc23246534c4bd",
"02c1e5a242387b6d5319ce27246cea6edaaf51c3550591b528d2578a4753c56c2c",
"025c319faf7067d9299590dd6c97fe7e56cd4dac61205ccee1cd1fc390142390a2",
"038f6e24c2bfe5d51d0a290f20a9a657c270b94ef2b9c12cd15ca3725fa798fc55",
"0255256ff7fb615278c4544a9bbd3f5298b903b8a011cd7889be19b6b1c45cbefe",
"024a3a37289f08c910fbd925ebc72b946f33feaeff451a4738ee82037b4cda2e95",
"02a88b75e9f0f8afba1467ab26799dcc38fd7a6468fb2795444b425eb43e2c10bd",
"02349a51512c1c04c67118386f4d27d768c5195a83247c150a4b722d161722ba81",
"03f718a2e0dc672c7cdec0113e72c3322efc70412bb95870750d25c32cd98de17d",
"028ff47ee2c56e66313928975c58fa4f1b19a0f81f3a96c4e9c9c3c6768075509e",
"02b517c0cbc3a49548f448ddf004ed695c5a1c52ec110be1bfd65fa0ca0761c94b",
"03df837a3a0f3d858e82f3356b71d1285327f101f7c10b404abed2abc1c94e7169",
"0203a90fb2ab698e524a5286f317a183a84327b8f8c3f7fa4a98fec9e1cefd6b72",
"023c99cc073b851c892d8c43329ca3beb5d2213ee87111af49884e3ce66cbd5ba5"
));
///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields
@ -176,39 +176,39 @@ public class ArbitratorManager {
Map<NodeAddress, Arbitrator> map = arbitratorService.getArbitrators();
arbitratorsObservableMap.clear();
Map<NodeAddress, Arbitrator> filtered = map.values().stream()
.filter(e -> {
final boolean isInPublicKeyInList = isPublicKeyInList(Utils.HEX.encode(e.getRegistrationPubKey()));
if (!isInPublicKeyInList)
log.warn("We got an arbitrator which is not in our list of publicKeys. RegistrationPubKey={}, nodeAddress={}",
Utilities.bytesAsHexString(e.getRegistrationPubKey()),
e.getNodeAddress().getFullAddress());
final boolean isSigValid = verifySignature(e.getPubKeyRing().getSignaturePubKey(),
e.getRegistrationPubKey(),
e.getRegistrationSignature());
if (!isSigValid)
log.warn("Sig check for arbitrator failed. Arbitrator=", e.toString());
.filter(e -> {
final boolean isInPublicKeyInList = isPublicKeyInList(Utils.HEX.encode(e.getRegistrationPubKey()));
if (!isInPublicKeyInList)
log.warn("We got an arbitrator which is not in our list of publicKeys. RegistrationPubKey={}, nodeAddress={}",
Utilities.bytesAsHexString(e.getRegistrationPubKey()),
e.getNodeAddress().getFullAddress());
final boolean isSigValid = verifySignature(e.getPubKeyRing().getSignaturePubKey(),
e.getRegistrationPubKey(),
e.getRegistrationSignature());
if (!isSigValid)
log.warn("Sig check for arbitrator failed. Arbitrator=", e.toString());
return isInPublicKeyInList && isSigValid;
})
.collect(Collectors.toMap(Arbitrator::getNodeAddress, Function.identity()));
return isInPublicKeyInList && isSigValid;
})
.collect(Collectors.toMap(Arbitrator::getNodeAddress, Function.identity()));
arbitratorsObservableMap.putAll(filtered);
arbitratorsObservableMap.values().stream()
.filter(persistedAcceptedArbitrators::contains)
.forEach(a -> {
user.addAcceptedArbitrator(a);
user.addAcceptedMediator(getMediator(a)
);
});
if (preferences.isAutoSelectArbitrators()) {
arbitratorsObservableMap.values().stream()
.filter(user::hasMatchingLanguage)
.filter(persistedAcceptedArbitrators::contains)
.forEach(a -> {
user.addAcceptedArbitrator(a);
user.addAcceptedMediator(getMediator(a)
);
});
if (preferences.isAutoSelectArbitrators()) {
arbitratorsObservableMap.values().stream()
.filter(user::hasMatchingLanguage)
.forEach(a -> {
user.addAcceptedArbitrator(a);
user.addAcceptedMediator(getMediator(a)
);
});
} else {
// if we don't have any arbitrator we set all matching
// we use a delay as we might get our matching arbitrator a bit delayed (first we get one we did not selected
@ -216,12 +216,12 @@ public class ArbitratorManager {
UserThread.runAfter(() -> {
if (user.getAcceptedArbitrators().isEmpty()) {
arbitratorsObservableMap.values().stream()
.filter(user::hasMatchingLanguage)
.forEach(a -> {
user.addAcceptedArbitrator(a);
user.addAcceptedMediator(getMediator(a)
);
});
.filter(user::hasMatchingLanguage)
.forEach(a -> {
user.addAcceptedArbitrator(a);
user.addAcceptedMediator(getMediator(a)
);
});
}
}, 100, TimeUnit.MILLISECONDS);
}
@ -231,28 +231,28 @@ public class ArbitratorManager {
@NotNull
public static Mediator getMediator(Arbitrator arbitrator) {
return new Mediator(arbitrator.getNodeAddress(),
arbitrator.getPubKeyRing(),
arbitrator.getLanguageCodes(),
arbitrator.getRegistrationDate(),
arbitrator.getRegistrationPubKey(),
arbitrator.getRegistrationSignature(),
arbitrator.getEmailAddress(),
null,
arbitrator.getExtraDataMap());
arbitrator.getPubKeyRing(),
arbitrator.getLanguageCodes(),
arbitrator.getRegistrationDate(),
arbitrator.getRegistrationPubKey(),
arbitrator.getRegistrationSignature(),
arbitrator.getEmailAddress(),
null,
arbitrator.getExtraDataMap());
}
public void addArbitrator(Arbitrator arbitrator, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
user.setRegisteredArbitrator(arbitrator);
arbitratorsObservableMap.put(arbitrator.getNodeAddress(), arbitrator);
arbitratorService.addArbitrator(arbitrator,
() -> {
log.debug("Arbitrator successfully saved in P2P network");
resultHandler.handleResult();
() -> {
log.debug("Arbitrator successfully saved in P2P network");
resultHandler.handleResult();
if (arbitratorsObservableMap.size() > 0)
UserThread.runAfter(this::updateArbitratorMap, 100, TimeUnit.MILLISECONDS);
},
errorMessageHandler::handleErrorMessage);
if (arbitratorsObservableMap.size() > 0)
UserThread.runAfter(this::updateArbitratorMap, 100, TimeUnit.MILLISECONDS);
},
errorMessageHandler::handleErrorMessage);
}
public void removeArbitrator(ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
@ -261,11 +261,11 @@ public class ArbitratorManager {
user.setRegisteredArbitrator(null);
arbitratorsObservableMap.remove(registeredArbitrator.getNodeAddress());
arbitratorService.removeArbitrator(registeredArbitrator,
() -> {
log.debug("Arbitrator successfully removed from P2P network");
resultHandler.handleResult();
},
errorMessageHandler::handleErrorMessage);
() -> {
log.debug("Arbitrator successfully removed from P2P network");
resultHandler.handleResult();
},
errorMessageHandler::handleErrorMessage);
}
}
@ -303,14 +303,14 @@ public class ArbitratorManager {
Arbitrator registeredArbitrator = user.getRegisteredArbitrator();
if (registeredArbitrator != null) {
addArbitrator(registeredArbitrator,
this::updateArbitratorMap,
errorMessage -> {
if (retryRepublishArbitratorTimer == null)
retryRepublishArbitratorTimer = UserThread.runPeriodically(() -> {
stopRetryRepublishArbitratorTimer();
republishArbitrator();
}, RETRY_REPUBLISH_SEC);
}
this::updateArbitratorMap,
errorMessage -> {
if (retryRepublishArbitratorTimer == null)
retryRepublishArbitratorTimer = UserThread.runPeriodically(() -> {
stopRetryRepublishArbitratorTimer();
republishArbitrator();
}, RETRY_REPUBLISH_SEC);
}
);
}
}

View File

@ -67,7 +67,7 @@ public class ArbitratorService {
public void addArbitrator(Arbitrator arbitrator, final ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
log.debug("addArbitrator arbitrator.hashCode() " + arbitrator.hashCode());
if (!BisqEnvironment.getBaseCurrencyNetwork().isMainnet() ||
!Utilities.encodeToHex(arbitrator.getRegistrationPubKey()).equals(DevEnv.DEV_PRIVILEGE_PUB_KEY)) {
!Utilities.encodeToHex(arbitrator.getRegistrationPubKey()).equals(DevEnv.DEV_PRIVILEGE_PUB_KEY)) {
boolean result = p2PService.addData(arbitrator, true);
if (result) {
log.trace("Add arbitrator to network was successful. Arbitrator.hashCode() = " + arbitrator.hashCode());
@ -100,11 +100,11 @@ public class ArbitratorService {
if (bannedArbitrators != null)
log.warn("bannedArbitrators=" + bannedArbitrators);
Set<Arbitrator> arbitratorSet = p2PService.getDataMap().values().stream()
.filter(data -> data.getProtectedStoragePayload() instanceof Arbitrator)
.map(data -> (Arbitrator) data.getProtectedStoragePayload())
.filter(a -> bannedArbitrators == null ||
!bannedArbitrators.contains(a.getNodeAddress().getHostName()))
.collect(Collectors.toSet());
.filter(data -> data.getProtectedStoragePayload() instanceof Arbitrator)
.map(data -> (Arbitrator) data.getProtectedStoragePayload())
.filter(a -> bannedArbitrators == null ||
!bannedArbitrators.contains(a.getNodeAddress().getHostName()))
.collect(Collectors.toSet());
Map<NodeAddress, Arbitrator> map = new HashMap<>();
for (Arbitrator arbitrator : arbitratorSet) {

View File

@ -517,7 +517,7 @@ public abstract class WalletService {
public DeterministicKey findKeyFromPubKeyHash(byte[] pubKeyHash) {
return wallet.getActiveKeychain().findKeyFromPubHash(pubKeyHash);
}
public DeterministicKey findKeyFromPubKey(byte[] pubKey) {
return wallet.getActiveKeychain().findKeyFromPubKey(pubKey);
}

View File

@ -62,10 +62,10 @@ public class BsqFullNode extends BsqNode {
FeeService feeService,
SeedNodesRepository seedNodesRepository) {
super(p2PService,
bsqParser,
bsqChainState,
feeService,
seedNodesRepository);
bsqParser,
bsqChainState,
feeService,
seedNodesRepository);
this.bsqFullNodeExecutor = bsqFullNodeExecutor;
this.jsonChainStateExporter = jsonChainStateExporter;
}
@ -80,23 +80,23 @@ public class BsqFullNode extends BsqNode {
// super.onAllServicesInitialized(errorMessageHandler) is called
// bsqFullNodeExecutor.setup is and async call.
bsqFullNodeExecutor.setup(() -> {
super.onAllServicesInitialized(errorMessageHandler);
startParseBlocks();
},
throwable -> {
log.error(throwable.toString());
throwable.printStackTrace();
});
super.onAllServicesInitialized(errorMessageHandler);
startParseBlocks();
},
throwable -> {
log.error(throwable.toString());
throwable.printStackTrace();
});
}
@Override
protected void parseBlocksWithChainHeadHeight(int startBlockHeight, int genesisBlockHeight, String genesisTxId) {
log.info("parseBlocksWithChainHeadHeight startBlockHeight={}", startBlockHeight);
bsqFullNodeExecutor.requestChainHeadHeight(chainHeadHeight -> parseBlocks(startBlockHeight, genesisBlockHeight, genesisTxId, chainHeadHeight),
throwable -> {
log.error(throwable.toString());
throwable.printStackTrace();
});
throwable -> {
log.error(throwable.toString());
throwable.printStackTrace();
});
}
@Override
@ -105,27 +105,27 @@ public class BsqFullNode extends BsqNode {
if (chainHeadHeight != startBlockHeight) {
if (startBlockHeight <= chainHeadHeight) {
bsqFullNodeExecutor.parseBlocks(startBlockHeight,
chainHeadHeight,
genesisBlockHeight,
genesisTxId,
this::onNewBsqBlock,
() -> {
// we are done but it might be that new blocks have arrived in the meantime,
// so we try again with startBlockHeight set to current chainHeadHeight
// We also set up the listener in the else main branch where we check
// if we at chainTip, so do nto include here another check as it would
// not trigger the listener registration.
parseBlocksWithChainHeadHeight(chainHeadHeight,
genesisBlockHeight,
genesisTxId);
}, throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
chainHeadHeight,
genesisBlockHeight,
genesisTxId,
this::onNewBsqBlock,
() -> {
// we are done but it might be that new blocks have arrived in the meantime,
// so we try again with startBlockHeight set to current chainHeadHeight
// We also set up the listener in the else main branch where we check
// if we at chainTip, so do nto include here another check as it would
// not trigger the listener registration.
parseBlocksWithChainHeadHeight(chainHeadHeight,
genesisBlockHeight,
genesisTxId);
}, throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
} else {
log.warn("We are trying to start with a block which is above the chain height of bitcoin core. We need probably wait longer until bitcoin core has fully synced. We try again after a delay of 1 min.");
UserThread.runAfter(() -> parseBlocksWithChainHeadHeight(startBlockHeight, genesisBlockHeight, genesisTxId), 60);
@ -159,47 +159,47 @@ public class BsqFullNode extends BsqNode {
private void createRequestBlocksManager() {
requestManager = new RequestManager(p2PService.getNetworkNode(),
p2PService.getPeerManager(),
p2PService.getBroadcaster(),
seedNodesRepository.getSeedNodeAddresses(),
bsqChainState,
new RequestManager.Listener() {
@Override
public void onBlockReceived(GetBsqBlocksResponse getBsqBlocksResponse) {
p2PService.getPeerManager(),
p2PService.getBroadcaster(),
seedNodesRepository.getSeedNodeAddresses(),
bsqChainState,
new RequestManager.Listener() {
@Override
public void onBlockReceived(GetBsqBlocksResponse getBsqBlocksResponse) {
}
}
@Override
public void onNewBsqBlockBroadcastMessage(NewBsqBlockBroadcastMessage newBsqBlockBroadcastMessage) {
@Override
public void onNewBsqBlockBroadcastMessage(NewBsqBlockBroadcastMessage newBsqBlockBroadcastMessage) {
}
}
@Override
public void onNoSeedNodeAvailable() {
@Override
public void onNoSeedNodeAvailable() {
}
}
@Override
public void onFault(String errorMessage, @Nullable Connection connection) {
@Override
public void onFault(String errorMessage, @Nullable Connection connection) {
}
});
}
});
}
private void addBlockHandler() {
// We register our handler for new blocks
bsqFullNodeExecutor.addBlockHandler(btcdBlock -> bsqFullNodeExecutor.parseBtcdBlock(btcdBlock,
genesisBlockHeight,
genesisTxId,
this::onNewBsqBlock,
throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
}));
genesisBlockHeight,
genesisTxId,
this::onNewBsqBlock,
throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
}));
}
@Override

View File

@ -57,10 +57,10 @@ public class BsqLiteNode extends BsqNode {
FeeService feeService,
SeedNodesRepository seedNodesRepository) {
super(p2PService,
bsqParser,
bsqChainState,
feeService,
seedNodesRepository);
bsqParser,
bsqChainState,
feeService,
seedNodesRepository);
this.bsqLiteNodeExecutor = bsqLiteNodeExecutor;
}
@ -79,64 +79,64 @@ public class BsqLiteNode extends BsqNode {
super.onP2PNetworkReady();
requestManager = new RequestManager(p2PService.getNetworkNode(),
p2PService.getPeerManager(),
p2PService.getBroadcaster(),
seedNodesRepository.getSeedNodeAddresses(),
bsqChainState,
new RequestManager.Listener() {
@Override
public void onBlockReceived(GetBsqBlocksResponse getBsqBlocksResponse) {
List<BsqBlock> bsqBlockList = new ArrayList<>(getBsqBlocksResponse.getBsqBlocks());
log.info("received msg with {} items", bsqBlockList.size());
if (bsqBlockList.size() > 0)
log.info("block height of last item: {}", bsqBlockList.get(bsqBlockList.size() - 1).getHeight());
// Be safe and reset all mutable data in case the provider would not have done it
bsqBlockList.stream().forEach(BsqBlock::reset);
bsqLiteNodeExecutor.parseBsqBlocksForLiteNode(bsqBlockList,
genesisBlockHeight,
genesisTxId,
BsqLiteNode.this::onNewBsqBlock,
() -> onParseBlockchainComplete(genesisBlockHeight, genesisTxId), throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
}
@Override
public void onNewBsqBlockBroadcastMessage(NewBsqBlockBroadcastMessage newBsqBlockBroadcastMessage) {
BsqBlock bsqBlock = newBsqBlockBroadcastMessage.getBsqBlock();
// Be safe and reset all mutable data in case the provider would not have done it
bsqBlock.reset();
log.info("received broadcastNewBsqBlock bsqBlock {}", bsqBlock.getHeight());
if (!bsqChainState.containsBlock(bsqBlock)) {
bsqLiteNodeExecutor.parseBsqBlockForLiteNode(bsqBlock,
genesisBlockHeight,
genesisTxId,
() -> onNewBsqBlock(bsqBlock), throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
p2PService.getPeerManager(),
p2PService.getBroadcaster(),
seedNodesRepository.getSeedNodeAddresses(),
bsqChainState,
new RequestManager.Listener() {
@Override
public void onBlockReceived(GetBsqBlocksResponse getBsqBlocksResponse) {
List<BsqBlock> bsqBlockList = new ArrayList<>(getBsqBlocksResponse.getBsqBlocks());
log.info("received msg with {} items", bsqBlockList.size());
if (bsqBlockList.size() > 0)
log.info("block height of last item: {}", bsqBlockList.get(bsqBlockList.size() - 1).getHeight());
// Be safe and reset all mutable data in case the provider would not have done it
bsqBlockList.stream().forEach(BsqBlock::reset);
bsqLiteNodeExecutor.parseBsqBlocksForLiteNode(bsqBlockList,
genesisBlockHeight,
genesisTxId,
BsqLiteNode.this::onNewBsqBlock,
() -> onParseBlockchainComplete(genesisBlockHeight, genesisTxId), throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
}
}
@Override
public void onNoSeedNodeAvailable() {
@Override
public void onNewBsqBlockBroadcastMessage(NewBsqBlockBroadcastMessage newBsqBlockBroadcastMessage) {
BsqBlock bsqBlock = newBsqBlockBroadcastMessage.getBsqBlock();
// Be safe and reset all mutable data in case the provider would not have done it
bsqBlock.reset();
log.info("received broadcastNewBsqBlock bsqBlock {}", bsqBlock.getHeight());
if (!bsqChainState.containsBlock(bsqBlock)) {
bsqLiteNodeExecutor.parseBsqBlockForLiteNode(bsqBlock,
genesisBlockHeight,
genesisTxId,
() -> onNewBsqBlock(bsqBlock), throwable -> {
if (throwable instanceof BlockNotConnectingException) {
startReOrgFromLastSnapshot();
} else {
log.error(throwable.toString());
throwable.printStackTrace();
}
});
}
}
}
@Override
public void onNoSeedNodeAvailable() {
@Override
public void onFault(String errorMessage, @Nullable Connection connection) {
}
}
});
@Override
public void onFault(String errorMessage, @Nullable Connection connection) {
}
});
// delay a bit to not stress too much at startup
UserThread.runAfter(this::startParseBlocks, 2);

View File

@ -80,9 +80,9 @@ public abstract class BsqNode {
genesisBlockHeight = bsqChainState.getGenesisBlockHeight();
bsqChainState.setCreateCompensationRequestFee(feeService.getCreateCompensationRequestFee().value,
genesisBlockHeight);
genesisBlockHeight);
bsqChainState.setVotingFee(feeService.getVotingTxFee().value,
genesisBlockHeight);
genesisBlockHeight);
}
@ -122,18 +122,18 @@ public abstract class BsqNode {
log.info("startParseBlocks");
int startBlockHeight = Math.max(genesisBlockHeight, bsqChainState.getChainHeadHeight() + 1);
log.info("Parse blocks:\n" +
" Start block height={}\n" +
" Genesis txId={}\n" +
" Genesis block height={}\n" +
" BsqChainState block height={}\n",
startBlockHeight,
genesisTxId,
genesisBlockHeight,
bsqChainState.getChainHeadHeight());
" Start block height={}\n" +
" Genesis txId={}\n" +
" Genesis block height={}\n" +
" BsqChainState block height={}\n",
startBlockHeight,
genesisTxId,
genesisBlockHeight,
bsqChainState.getChainHeadHeight());
parseBlocksWithChainHeadHeight(startBlockHeight,
genesisBlockHeight,
genesisTxId);
genesisBlockHeight,
genesisTxId);
}
abstract protected void parseBlocksWithChainHeadHeight(int startBlockHeight, int genesisBlockHeight, String genesisTxId);

View File

@ -107,13 +107,13 @@ public final class Filter implements ProtectedStoragePayload {
byte[] ownerPubKeyBytes,
@Nullable Map<String, String> extraDataMap) {
this(bannedOfferIds,
bannedNodeAddress,
bannedPaymentAccounts,
bannedCurrencies,
bannedPaymentMethods,
arbitrators,
seedNodes,
priceRelayNodes);
bannedNodeAddress,
bannedPaymentAccounts,
bannedCurrencies,
bannedPaymentMethods,
arbitrators,
seedNodes,
priceRelayNodes);
this.signatureAsBase64 = signatureAsBase64;
this.ownerPubKeyBytes = ownerPubKeyBytes;
this.extraDataMap = extraDataMap;
@ -126,14 +126,14 @@ public final class Filter implements ProtectedStoragePayload {
checkNotNull(signatureAsBase64, "signatureAsBase64 must nto be null");
checkNotNull(ownerPubKeyBytes, "ownerPubKeyBytes must nto be null");
List<PB.PaymentAccountFilter> paymentAccountFilterList = bannedPaymentAccounts.stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList());
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList());
final PB.Filter.Builder builder = PB.Filter.newBuilder()
.addAllBannedOfferIds(bannedOfferIds)
.addAllBannedNodeAddress(bannedNodeAddress)
.addAllBannedPaymentAccounts(paymentAccountFilterList)
.setSignatureAsBase64(signatureAsBase64)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes));
.addAllBannedOfferIds(bannedOfferIds)
.addAllBannedNodeAddress(bannedNodeAddress)
.addAllBannedPaymentAccounts(paymentAccountFilterList)
.setSignatureAsBase64(signatureAsBase64)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes));
Optional.ofNullable(bannedCurrencies).ifPresent(builder::addAllBannedCurrencies);
Optional.ofNullable(bannedPaymentMethods).ifPresent(builder::addAllBannedPaymentMethods);
@ -147,18 +147,18 @@ public final class Filter implements ProtectedStoragePayload {
public static Filter fromProto(PB.Filter proto) {
return new Filter(proto.getBannedOfferIdsList().stream().collect(Collectors.toList()),
proto.getBannedNodeAddressList().stream().collect(Collectors.toList()),
proto.getBannedPaymentAccountsList().stream()
.map(PaymentAccountFilter::fromProto)
.collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getBannedCurrenciesList()) ? null : proto.getBannedCurrenciesList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getBannedPaymentMethodsList()) ? null : proto.getBannedPaymentMethodsList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getArbitratorsList()) ? null : proto.getArbitratorsList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getSeedNodesList()) ? null : proto.getSeedNodesList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getPriceRelayNodesList()) ? null : proto.getPriceRelayNodesList().stream().collect(Collectors.toList()),
proto.getSignatureAsBase64(),
proto.getOwnerPubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
proto.getBannedNodeAddressList().stream().collect(Collectors.toList()),
proto.getBannedPaymentAccountsList().stream()
.map(PaymentAccountFilter::fromProto)
.collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getBannedCurrenciesList()) ? null : proto.getBannedCurrenciesList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getBannedPaymentMethodsList()) ? null : proto.getBannedPaymentMethodsList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getArbitratorsList()) ? null : proto.getArbitratorsList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getSeedNodesList()) ? null : proto.getSeedNodesList().stream().collect(Collectors.toList()),
CollectionUtils.isEmpty(proto.getPriceRelayNodesList()) ? null : proto.getPriceRelayNodesList().stream().collect(Collectors.toList()),
proto.getSignatureAsBase64(),
proto.getOwnerPubKeyBytes().toByteArray(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap());
}

View File

@ -75,8 +75,8 @@ public class FilterManager {
@SuppressWarnings("ConstantConditions")
private static final String pubKeyAsHex = DevEnv.USE_DEV_PRIVILEGE_KEYS ?
DevEnv.DEV_PRIVILEGE_PUB_KEY :
"022ac7b7766b0aedff82962522c2c14fb8d1961dabef6e5cfd10edc679456a32f1";
DevEnv.DEV_PRIVILEGE_PUB_KEY :
"022ac7b7766b0aedff82962522c2c14fb8d1961dabef6e5cfd10edc679456a32f1";
private ECKey filterSigningKey;
@ -223,11 +223,11 @@ public class FilterManager {
// We dont use full data from Filter as we are only interested in the filter data not the sig and keys
private String getHexFromData(Filter filter) {
PB.Filter.Builder builder = PB.Filter.newBuilder()
.addAllBannedOfferIds(filter.getBannedOfferIds())
.addAllBannedNodeAddress(filter.getBannedNodeAddress())
.addAllBannedPaymentAccounts(filter.getBannedPaymentAccounts().stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList()));
.addAllBannedOfferIds(filter.getBannedOfferIds())
.addAllBannedNodeAddress(filter.getBannedNodeAddress())
.addAllBannedPaymentAccounts(filter.getBannedPaymentAccounts().stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList()));
Optional.ofNullable(filter.getBannedCurrencies()).ifPresent(builder::addAllBannedCurrencies);
Optional.ofNullable(filter.getBannedPaymentMethods()).ifPresent(builder::addAllBannedPaymentMethods);
@ -242,60 +242,60 @@ public class FilterManager {
public boolean isCurrencyBanned(String currencyCode) {
return getFilter() != null &&
getFilter().getBannedCurrencies() != null &&
getFilter().getBannedCurrencies().stream()
.filter(e -> e.equals(currencyCode))
.findAny()
.isPresent();
getFilter().getBannedCurrencies() != null &&
getFilter().getBannedCurrencies().stream()
.filter(e -> e.equals(currencyCode))
.findAny()
.isPresent();
}
public boolean isPaymentMethodBanned(PaymentMethod paymentMethod) {
return getFilter() != null &&
getFilter().getBannedPaymentMethods() != null &&
getFilter().getBannedPaymentMethods().stream()
.filter(e -> e.equals(paymentMethod.getId()))
.findAny()
.isPresent();
getFilter().getBannedPaymentMethods() != null &&
getFilter().getBannedPaymentMethods().stream()
.filter(e -> e.equals(paymentMethod.getId()))
.findAny()
.isPresent();
}
public boolean isOfferIdBanned(String offerId) {
return getFilter() != null &&
getFilter().getBannedOfferIds().stream()
.filter(e -> e.equals(offerId))
.findAny()
.isPresent();
getFilter().getBannedOfferIds().stream()
.filter(e -> e.equals(offerId))
.findAny()
.isPresent();
}
public boolean isNodeAddressBanned(String nodeAddress) {
return getFilter() != null &&
getFilter().getBannedNodeAddress().stream()
.filter(e -> e.equals(nodeAddress))
.findAny()
.isPresent();
getFilter().getBannedNodeAddress().stream()
.filter(e -> e.equals(nodeAddress))
.findAny()
.isPresent();
}
public boolean isPeersPaymentAccountDataAreBanned(PaymentAccountPayload paymentAccountPayload,
PaymentAccountFilter[] appliedPaymentAccountFilter) {
return getFilter() != null &&
getFilter().getBannedPaymentAccounts().stream()
.filter(paymentAccountFilter -> {
final boolean samePaymentMethodId = paymentAccountFilter.getPaymentMethodId().equals(
paymentAccountPayload.getPaymentMethodId());
if (samePaymentMethodId) {
try {
Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getGetMethodName());
String result = (String) method.invoke(paymentAccountPayload);
appliedPaymentAccountFilter[0] = paymentAccountFilter;
return result.equals(paymentAccountFilter.getValue());
} catch (Throwable e) {
log.error(e.getMessage());
return false;
}
} else {
return false;
}
})
.findAny()
.isPresent();
getFilter().getBannedPaymentAccounts().stream()
.filter(paymentAccountFilter -> {
final boolean samePaymentMethodId = paymentAccountFilter.getPaymentMethodId().equals(
paymentAccountPayload.getPaymentMethodId());
if (samePaymentMethodId) {
try {
Method method = paymentAccountPayload.getClass().getMethod(paymentAccountFilter.getGetMethodName());
String result = (String) method.invoke(paymentAccountPayload);
appliedPaymentAccountFilter[0] = paymentAccountFilter;
return result.equals(paymentAccountFilter.getValue());
} catch (Throwable e) {
log.error(e.getMessage());
return false;
}
} else {
return false;
}
})
.findAny()
.isPresent();
}
}

View File

@ -34,20 +34,20 @@ public class CoreSeedNodesRepository implements SeedNodesRepository {
Set<NodeAddress> nodeAddresses;
if (seedNodes != null && !seedNodes.isEmpty()) {
nodeAddresses = Arrays.asList(StringUtils.deleteWhitespace(seedNodes).split(","))
.stream()
.map(NodeAddress::new)
.collect(Collectors.toSet());
.stream()
.map(NodeAddress::new)
.collect(Collectors.toSet());
} else {
nodeAddresses = useLocalhostForP2P ? localhostSeedNodeAddresses : torSeedNodeAddresses;
nodeAddresses = nodeAddresses.stream()
.filter(e -> String.valueOf(e.getPort()).endsWith("0" + String.valueOf(networkId)))
.collect(Collectors.toSet());
.filter(e -> String.valueOf(e.getPort()).endsWith("0" + String.valueOf(networkId)))
.collect(Collectors.toSet());
}
seedNodeAddresses = nodeAddresses.stream()
.filter(e -> myAddress == null || myAddress.isEmpty() || !e.getFullAddress().equals(myAddress))
.filter(e -> bannedNodes == null || !bannedNodes.contains(e.getHostName()))
.collect(Collectors.toSet());
.filter(e -> myAddress == null || myAddress.isEmpty() || !e.getFullAddress().equals(myAddress))
.filter(e -> bannedNodes == null || !bannedNodes.contains(e.getHostName()))
.collect(Collectors.toSet());
if (bannedNodes == null)
log.info("seedNodeAddresses={}", seedNodeAddresses);
@ -61,44 +61,44 @@ public class CoreSeedNodesRepository implements SeedNodesRepository {
// - regtest uses port 8002
@SuppressWarnings("ConstantConditions")
private Set<NodeAddress> torSeedNodeAddresses = Sets.newHashSet(
// BTC mainnet
// BTC mainnet
//TODO dev dont use live nodes atm!
new NodeAddress("3f3cu2yw7u457ztq.onion:8000"),
new NodeAddress("723ljisnynbtdohi.onion:8000"),
new NodeAddress("rm7b56wbrcczpjvl.onion:8000"),
new NodeAddress("fl3mmribyxgrv63c.onion:8000"),
//TODO dev dont use live nodes atm!
new NodeAddress("3f3cu2yw7u457ztq.onion:8000"),
new NodeAddress("723ljisnynbtdohi.onion:8000"),
new NodeAddress("rm7b56wbrcczpjvl.onion:8000"),
new NodeAddress("fl3mmribyxgrv63c.onion:8000"),
//TODO dev
// local dev
// new NodeAddress("joehwtpe7ijnz4df.onion:8000"),
//TODO dev
// local dev
// new NodeAddress("joehwtpe7ijnz4df.onion:8000"),
// BTC testnet
new NodeAddress("nbphlanpgbei4okt.onion:8001"),
// BTC testnet
new NodeAddress("nbphlanpgbei4okt.onion:8001"),
// BTC regtest
// For development you need to change that to your local onion addresses
// 1. Run a seed node with prog args: --bitcoinNetwork=regtest --nodePort=8002 --myAddress=rxdkppp3vicnbgqt:8002 --appName=bisq_seed_node_rxdkppp3vicnbgqt.onion_8002
// 2. Find your local onion address in bisq_seed_node_rxdkppp3vicnbgqt.onion_8002/regtest/tor/hiddenservice/hostname
// 3. Shut down the seed node
// 4. Rename the directory with your local onion address
// 5. Edit here your found onion address (new NodeAddress("YOUR_ONION.onion:8002")
new NodeAddress("rxdkppp3vicnbgqt.onion:8002"),
// BTC regtest
// For development you need to change that to your local onion addresses
// 1. Run a seed node with prog args: --bitcoinNetwork=regtest --nodePort=8002 --myAddress=rxdkppp3vicnbgqt:8002 --appName=bisq_seed_node_rxdkppp3vicnbgqt.onion_8002
// 2. Find your local onion address in bisq_seed_node_rxdkppp3vicnbgqt.onion_8002/regtest/tor/hiddenservice/hostname
// 3. Shut down the seed node
// 4. Rename the directory with your local onion address
// 5. Edit here your found onion address (new NodeAddress("YOUR_ONION.onion:8002")
new NodeAddress("rxdkppp3vicnbgqt.onion:8002"),
// LTC mainnet
new NodeAddress("acyvotgewx46pebw.onion:8003"),
// new NodeAddress("pklgy3vdfn3obkur.onion:8003"), removed in version 0.6
// LTC mainnet
new NodeAddress("acyvotgewx46pebw.onion:8003"),
// new NodeAddress("pklgy3vdfn3obkur.onion:8003"), removed in version 0.6
// keep the below but we don't run them atm
// keep the below but we don't run them atm
/* new NodeAddress("cfciqxcowuhjdnkl.onion:8003"),
new NodeAddress("bolqw3hs55uii7ku.onion:8003"),*/
// DOGE mainnet
// new NodeAddress("t6bwuj75mvxswavs.onion:8006"), removed in version 0.6 (DOGE not supported anymore)
// DOGE mainnet
// new NodeAddress("t6bwuj75mvxswavs.onion:8006"), removed in version 0.6 (DOGE not supported anymore)
//DASH mainnet
new NodeAddress("toeu5ikb27ydscxt.onion:8009")
//new NodeAddress("ae4yvaivhnekkhqf.onion:8009") removed in version 0.6
//DASH mainnet
new NodeAddress("toeu5ikb27ydscxt.onion:8009")
//new NodeAddress("ae4yvaivhnekkhqf.onion:8009") removed in version 0.6
);
// Addresses are used if the last digit of their port match the network id:
@ -106,34 +106,34 @@ public class CoreSeedNodesRepository implements SeedNodesRepository {
// - testnet use port ends in 1
// - regtest use port ends in 2
private Set<NodeAddress> localhostSeedNodeAddresses = Sets.newHashSet(
// BTC
// mainnet
new NodeAddress("localhost:2000"),
new NodeAddress("localhost:3000"),
new NodeAddress("localhost:4000"),
// BTC
// mainnet
new NodeAddress("localhost:2000"),
new NodeAddress("localhost:3000"),
new NodeAddress("localhost:4000"),
// testnet
new NodeAddress("localhost:2001"),
new NodeAddress("localhost:3001"),
new NodeAddress("localhost:4001"),
// testnet
new NodeAddress("localhost:2001"),
new NodeAddress("localhost:3001"),
new NodeAddress("localhost:4001"),
// regtest
new NodeAddress("localhost:2002"),
new NodeAddress("localhost:3002"),
// regtest
new NodeAddress("localhost:2002"),
new NodeAddress("localhost:3002"),
/* new NodeAddress("localhost:4002"),*/
// LTC
// mainnet
new NodeAddress("localhost:2003"),
// LTC
// mainnet
new NodeAddress("localhost:2003"),
// regtest
new NodeAddress("localhost:2005"),
// regtest
new NodeAddress("localhost:2005"),
// DOGE regtest
new NodeAddress("localhost:2008"),
// DOGE regtest
new NodeAddress("localhost:2008"),
// DASH regtest
new NodeAddress("localhost:2011")
// DASH regtest
new NodeAddress("localhost:2011")
);
@ -147,6 +147,6 @@ public class CoreSeedNodesRepository implements SeedNodesRepository {
public boolean isSeedNode(NodeAddress nodeAddress) {
return Stream.concat(localhostSeedNodeAddresses.stream(), torSeedNodeAddresses.stream())
.filter(e -> e.equals(nodeAddress)).findAny().isPresent();
.filter(e -> e.equals(nodeAddress)).findAny().isPresent();
}
}

View File

@ -105,16 +105,16 @@ public class Offer implements NetworkPayload, PersistablePayload {
public void checkOfferAvailability(OfferAvailabilityModel model, ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
availabilityProtocol = new OfferAvailabilityProtocol(model,
() -> {
cancelAvailabilityRequest();
resultHandler.handleResult();
},
(errorMessage) -> {
if (availabilityProtocol != null)
availabilityProtocol.cancel();
log.error(errorMessage);
errorMessageHandler.handleErrorMessage(errorMessage);
});
() -> {
cancelAvailabilityRequest();
resultHandler.handleResult();
},
(errorMessage) -> {
if (availabilityProtocol != null)
availabilityProtocol.cancel();
log.error(errorMessage);
errorMessageHandler.handleErrorMessage(errorMessage);
});
availabilityProtocol.sendOfferAvailabilityRequest();
}
@ -134,28 +134,28 @@ public class Offer implements NetworkPayload, PersistablePayload {
double marketPriceMargin = offerPayload.getMarketPriceMargin();
if (CurrencyUtil.isCryptoCurrency(currencyCode)) {
factor = getDirection() == OfferPayload.Direction.SELL ?
1 - marketPriceMargin : 1 + marketPriceMargin;
1 - marketPriceMargin : 1 + marketPriceMargin;
} else {
factor = getDirection() == OfferPayload.Direction.BUY ?
1 - marketPriceMargin : 1 + marketPriceMargin;
1 - marketPriceMargin : 1 + marketPriceMargin;
}
double marketPriceAsDouble = marketPrice.getPrice();
double targetPriceAsDouble = marketPriceAsDouble * factor;
try {
int precision = CurrencyUtil.isCryptoCurrency(currencyCode) ?
Altcoin.SMALLEST_UNIT_EXPONENT :
Fiat.SMALLEST_UNIT_EXPONENT;
Altcoin.SMALLEST_UNIT_EXPONENT :
Fiat.SMALLEST_UNIT_EXPONENT;
double scaled = MathUtils.scaleUpByPowerOf10(targetPriceAsDouble, precision);
final long roundedToLong = MathUtils.roundDoubleToLong(scaled);
return Price.valueOf(currencyCode, roundedToLong);
} catch (Exception e) {
log.error("Exception at getPrice / parseToFiat: " + e.toString() + "\n" +
"That case should never happen.");
"That case should never happen.");
return null;
}
} else {
log.debug("We don't have a market price.\n" +
"That case could only happen if you don't have a price feed.");
"That case could only happen if you don't have a price feed.");
return null;
}
} else {
@ -164,7 +164,7 @@ public class Offer implements NetworkPayload, PersistablePayload {
}
public void checkTradePriceTolerance(long takersTradePrice) throws TradePriceOutOfToleranceException,
MarketPriceNotAvailableException, IllegalArgumentException {
MarketPriceNotAvailableException, IllegalArgumentException {
Price tradePrice = Price.valueOf(getCurrencyCode(), takersTradePrice);
Price offerPrice = getPrice();
if (offerPrice == null)
@ -179,8 +179,8 @@ public class Offer implements NetworkPayload, PersistablePayload {
// from one provider.
if (Math.abs(1 - factor) > 0.01) {
String msg = "Taker's trade price is too far away from our calculated price based on the market price.\n" +
"tradePrice=" + tradePrice.getValue() + "\n" +
"offerPrice=" + offerPrice.getValue();
"tradePrice=" + tradePrice.getValue() + "\n" +
"offerPrice=" + offerPrice.getValue();
log.warn(msg);
throw new TradePriceOutOfToleranceException(msg);
}
@ -270,8 +270,8 @@ public class Offer implements NetworkPayload, PersistablePayload {
public PaymentMethod getPaymentMethod() {
return new PaymentMethod(offerPayload.getPaymentMethodId(),
offerPayload.getMaxTradePeriod(),
Coin.valueOf(offerPayload.getMaxTradeLimit()));
offerPayload.getMaxTradePeriod(),
Coin.valueOf(offerPayload.getMaxTradeLimit()));
}
// utils
@ -365,8 +365,8 @@ public class Offer implements NetworkPayload, PersistablePayload {
public String getCurrencyCode() {
return CurrencyUtil.isCryptoCurrency(offerPayload.getBaseCurrencyCode()) ?
offerPayload.getBaseCurrencyCode() :
offerPayload.getCounterCurrencyCode();
offerPayload.getBaseCurrencyCode() :
offerPayload.getCounterCurrencyCode();
}
public long getProtocolVersion() {
@ -473,9 +473,9 @@ public class Offer implements NetworkPayload, PersistablePayload {
@Override
public String toString() {
return "Offer{" +
"getErrorMessage()='" + getErrorMessage() + '\'' +
", state=" + getState() +
", offerPayload=" + offerPayload +
'}';
"getErrorMessage()='" + getErrorMessage() + '\'' +
", state=" + getState() +
", offerPayload=" + offerPayload +
'}';
}
}

View File

@ -30,7 +30,7 @@ import javax.annotation.Nullable;
/**
* This class holds utility methods for the creation of an Offer.
* Most of these are extracted here because they are used both in the GUI and in the API.
*
* <p>
* Long-term there could be a GUI-agnostic OfferService which provides these and other functionalities to both the
* GUI and the API.
*/
@ -45,7 +45,7 @@ public class OfferUtil {
public static boolean isBuyOffer(OfferPayload.Direction direction) {
return direction == OfferPayload.Direction.BUY;
}
/**
* Returns the makerFee as Coin, this can be priced in BTC or BSQ.
*
@ -108,7 +108,7 @@ public class OfferUtil {
* @return
*/
public static boolean isCurrencyForMakerFeeBtc(Preferences preferences, BsqWalletService bsqWalletService, Coin amount, boolean marketPriceAvailable, double marketPriceMargin) {
return preferences.getPayFeeInBtc() ||
return preferences.getPayFeeInBtc() ||
!isBsqForFeeAvailable(bsqWalletService, amount, marketPriceAvailable, marketPriceMargin);
}

View File

@ -57,8 +57,8 @@ public class AccountAgeWitness implements LazyProcessedPayload, PersistableNetwo
@Override
public PB.PersistableNetworkPayload toProtoMessage() {
final PB.AccountAgeWitness.Builder builder = PB.AccountAgeWitness.newBuilder()
.setHash(ByteString.copyFrom(hash))
.setDate(date);
.setHash(ByteString.copyFrom(hash))
.setDate(date);
return PB.PersistableNetworkPayload.newBuilder().setAccountAgeWitness(builder).build();
}
@ -73,8 +73,8 @@ public class AccountAgeWitness implements LazyProcessedPayload, PersistableNetwo
hash = new byte[0];
}
return new AccountAgeWitness(
hash,
proto.getDate());
hash,
proto.getDate());
}
@ -106,8 +106,8 @@ public class AccountAgeWitness implements LazyProcessedPayload, PersistableNetwo
@Override
public String toString() {
return "AccountAgeWitness{" +
"\n hash=" + Utilities.bytesAsHexString(hash) +
",\n date=" + new Date(date) +
"\n}";
"\n hash=" + Utilities.bytesAsHexString(hash) +
",\n date=" + new Date(date) +
"\n}";
}
}

View File

@ -108,13 +108,13 @@ public class AccountAgeWitnessService {
private void republishAllFiatAccounts() {
if (user.getPaymentAccounts() != null)
user.getPaymentAccounts().stream()
.filter(e -> !(e instanceof CryptoCurrencyAccount))
.forEach(e -> {
// We delay with a random interval of 20-60 sec to ensure to be better connected and don't stress the
// P2P network with publishing all at once at startup time.
final int delayInSec = 20 + new Random().nextInt(40);
UserThread.runAfter(() -> p2PService.addPersistableNetworkPayload(getMyWitness(e.getPaymentAccountPayload()), true), delayInSec);
});
.filter(e -> !(e instanceof CryptoCurrencyAccount))
.forEach(e -> {
// We delay with a random interval of 20-60 sec to ensure to be better connected and don't stress the
// P2P network with publishing all at once at startup time.
final int delayInSec = 20 + new Random().nextInt(40);
UserThread.runAfter(() -> p2PService.addPersistableNetworkPayload(getMyWitness(e.getPaymentAccountPayload()), true), delayInSec);
});
}
private void addToMap(AccountAgeWitness accountAgeWitness) {
@ -141,14 +141,14 @@ public class AccountAgeWitnessService {
public AccountAgeWitness getNewWitness(PaymentAccountPayload paymentAccountPayload, PubKeyRing pubKeyRing) {
byte[] accountInputDataWithSalt = getAccountInputDataWithSalt(paymentAccountPayload);
byte[] hash = Hash.getSha256Ripemd160hash(Utilities.concatenateByteArrays(accountInputDataWithSalt,
pubKeyRing.getSignaturePubKeyBytes()));
pubKeyRing.getSignaturePubKeyBytes()));
return new AccountAgeWitness(hash, new Date().getTime());
}
public Optional<AccountAgeWitness> findWitness(PaymentAccountPayload paymentAccountPayload, PubKeyRing pubKeyRing) {
byte[] accountInputDataWithSalt = getAccountInputDataWithSalt(paymentAccountPayload);
byte[] hash = Hash.getSha256Ripemd160hash(Utilities.concatenateByteArrays(accountInputDataWithSalt,
pubKeyRing.getSignaturePubKeyBytes()));
pubKeyRing.getSignaturePubKeyBytes()));
return getWitnessByHash(hash);
}
@ -188,8 +188,8 @@ public class AccountAgeWitnessService {
final long accountAge = getAccountAge((accountAgeWitnessOptional.get()), now);
AccountAge accountAgeCategory = accountAgeWitnessOptional.isPresent() ?
getAccountAgeCategory(accountAge) :
AccountAgeWitnessService.AccountAge.LESS_ONE_MONTH;
getAccountAgeCategory(accountAge) :
AccountAgeWitnessService.AccountAge.LESS_ONE_MONTH;
// TODO Fade in by date can be removed after feb 2018
// We want to fade in the limit over 2 months to avoid that all users get limited to 25% of the limit when
@ -226,11 +226,11 @@ public class AccountAgeWitnessService {
final long limit = MathUtils.roundDoubleToLong((double) maxTradeLimit.value * factor);
log.info("accountAgeCategory={}, accountAge={}, limit={}, factor={}, accountAgeWitnessHash={}",
accountAgeCategory,
accountAge / TimeUnit.DAYS.toMillis(1) + " days",
Coin.valueOf(limit).toFriendlyString(),
factor,
accountAgeWitnessOptional.isPresent() ? Utilities.bytesAsHexString(accountAgeWitnessOptional.get().getHash()) : "accountAgeWitnessOptional not present");
accountAgeCategory,
accountAge / TimeUnit.DAYS.toMillis(1) + " days",
Coin.valueOf(limit).toFriendlyString(),
factor,
accountAgeWitnessOptional.isPresent() ? Utilities.bytesAsHexString(accountAgeWitnessOptional.get().getHash()) : "accountAgeWitnessOptional not present");
return limit;
} else {
return maxTradeLimit.value;
@ -275,8 +275,8 @@ public class AccountAgeWitnessService {
public long getMakersAccountAge(Offer offer, Date peersCurrentDate) {
final Optional<String> accountAgeWitnessHash = offer.getAccountAgeWitnessHashAsHex();
final Optional<AccountAgeWitness> witnessByHashAsHex = accountAgeWitnessHash.isPresent() ?
getWitnessByHashAsHex(accountAgeWitnessHash.get()) :
Optional.<AccountAgeWitness>empty();
getWitnessByHashAsHex(accountAgeWitnessHash.get()) :
Optional.<AccountAgeWitness>empty();
return witnessByHashAsHex.isPresent() ? getAccountAge(witnessByHashAsHex.get(), peersCurrentDate) : -1L;
}
@ -343,7 +343,7 @@ public class AccountAgeWitnessService {
final boolean result = witnessDate.after(releaseDateWithTolerance);
if (!result) {
final String msg = "Witness date is set earlier than release date of ageWitness feature. " +
"ageWitnessReleaseDate=" + ageWitnessReleaseDate + ", witnessDate=" + witnessDate;
"ageWitnessReleaseDate=" + ageWitnessReleaseDate + ", witnessDate=" + witnessDate;
log.warn(msg);
errorMessageHandler.handleErrorMessage(msg);
}
@ -354,7 +354,7 @@ public class AccountAgeWitnessService {
final boolean result = Math.abs(peersCurrentDate.getTime() - new Date().getTime()) <= TimeUnit.DAYS.toMillis(1);
if (!result) {
final String msg = "Peers current date is further then 1 day off to our current date. " +
"PeersCurrentDate=" + peersCurrentDate + "; myCurrentDate=" + new Date();
"PeersCurrentDate=" + peersCurrentDate + "; myCurrentDate=" + new Date();
log.warn(msg);
errorMessageHandler.handleErrorMessage(msg);
}
@ -367,7 +367,7 @@ public class AccountAgeWitnessService {
final boolean result = Arrays.equals(witnessHash, hash);
if (!result) {
final String msg = "witnessHash is not matching peers hash. " +
"witnessHash=" + Utilities.bytesAsHexString(witnessHash) + ", hash=" + Utilities.bytesAsHexString(hash);
"witnessHash=" + Utilities.bytesAsHexString(witnessHash) + ", hash=" + Utilities.bytesAsHexString(hash);
log.warn(msg);
errorMessageHandler.handleErrorMessage(msg);
}
@ -387,8 +387,8 @@ public class AccountAgeWitnessService {
boolean result = tradeAmount.value <= peersCurrentTradeLimit;
if (!result) {
String msg = "The peers trade limit is less than the traded amount.\n" +
"tradeAmount=" + tradeAmount.toFriendlyString() +
"\nPeers trade limit=" + Coin.valueOf(peersCurrentTradeLimit).toFriendlyString();
"tradeAmount=" + tradeAmount.toFriendlyString() +
"\nPeers trade limit=" + Coin.valueOf(peersCurrentTradeLimit).toFriendlyString();
log.warn(msg);
errorMessageHandler.handleErrorMessage(msg);
}
@ -408,8 +408,8 @@ public class AccountAgeWitnessService {
}
if (!result) {
final String msg = "Signature of nonce is not correct. " +
"peersPublicKey=" + peersPublicKey + ", nonce(hex)=" + Utilities.bytesAsHexString(nonce) +
", signature=" + Utilities.bytesAsHexString(signature);
"peersPublicKey=" + peersPublicKey + ", nonce(hex)=" + Utilities.bytesAsHexString(nonce) +
", signature=" + Utilities.bytesAsHexString(signature);
log.warn(msg);
errorMessageHandler.handleErrorMessage(msg);
}

View File

@ -25,8 +25,8 @@ public class PaymentAccountUtil {
public static ObservableList<PaymentAccount> getPossiblePaymentAccounts(Offer offer, Set<PaymentAccount> paymentAccounts) {
ObservableList<PaymentAccount> result = FXCollections.observableArrayList();
result.addAll(paymentAccounts.stream()
.filter(paymentAccount -> isPaymentAccountValidForOffer(offer, paymentAccount))
.collect(Collectors.toList()));
.filter(paymentAccount -> isPaymentAccountValidForOffer(offer, paymentAccount))
.collect(Collectors.toList()));
return result;
}
@ -34,16 +34,16 @@ public class PaymentAccountUtil {
public static String getInfoForMismatchingPaymentMethodLimits(Offer offer, PaymentAccount paymentAccount) {
// dont translate atm as it is not used so far in the UI just for logs
return "Payment methods have different trade limits or trade periods.\n" +
"Our local Payment method: " + paymentAccount.getPaymentMethod().toString() + "\n" +
"Payment method from offer: " + offer.getPaymentMethod().toString();
"Our local Payment method: " + paymentAccount.getPaymentMethod().toString() + "\n" +
"Payment method from offer: " + offer.getPaymentMethod().toString();
}
//TODO not tested with all combinations yet....
public static boolean isPaymentAccountValidForOffer(Offer offer, PaymentAccount paymentAccount) {
// check if we have a matching currency
Set<String> paymentAccountCurrencyCodes = paymentAccount.getTradeCurrencies().stream()
.map(TradeCurrency::getCode)
.collect(Collectors.toSet());
.map(TradeCurrency::getCode)
.collect(Collectors.toSet());
boolean matchesCurrencyCode = paymentAccountCurrencyCodes.contains(offer.getCurrencyCode());
if (!matchesCurrencyCode)
return false;
@ -52,7 +52,7 @@ public class PaymentAccountUtil {
final boolean arePaymentMethodsEqual = paymentAccount.getPaymentMethod().equals(offer.getPaymentMethod());
if (!arePaymentMethodsEqual &&
paymentAccount.getPaymentMethod().getId().equals(offer.getPaymentMethod().getId()))
paymentAccount.getPaymentMethod().getId().equals(offer.getPaymentMethod().getId()))
log.warn(getInfoForMismatchingPaymentMethodLimits(offer, paymentAccount));
if (paymentAccount instanceof CountryBasedPaymentAccount) {
@ -60,14 +60,14 @@ public class PaymentAccountUtil {
// check if we have a matching country
boolean matchesCountryCodes = offer.getAcceptedCountryCodes() != null && countryBasedPaymentAccount.getCountry() != null &&
offer.getAcceptedCountryCodes().contains(countryBasedPaymentAccount.getCountry().code);
offer.getAcceptedCountryCodes().contains(countryBasedPaymentAccount.getCountry().code);
if (!matchesCountryCodes)
return false;
if (paymentAccount instanceof SepaAccount || offer.getPaymentMethod().equals(PaymentMethod.SEPA)) {
return arePaymentMethodsEqual;
} else if (offer.getPaymentMethod().equals(PaymentMethod.SAME_BANK) ||
offer.getPaymentMethod().equals(PaymentMethod.SPECIFIC_BANKS)) {
offer.getPaymentMethod().equals(PaymentMethod.SPECIFIC_BANKS)) {
final List<String> acceptedBankIds = offer.getAcceptedBankIds();
checkNotNull(acceptedBankIds, "offer.getAcceptedBankIds() must not be null");
@ -105,11 +105,11 @@ public class PaymentAccountUtil {
Set<PaymentAccount> paymentAccounts,
AccountAgeWitnessService service) {
List<PaymentAccount> list = paymentAccounts.stream()
.filter(paymentAccount -> isPaymentAccountValidForOffer(offer, paymentAccount))
.sorted((o1, o2) -> {
return new Long(service.getAccountAge(service.getMyWitness(o2.getPaymentAccountPayload()), new Date()))
.compareTo(service.getAccountAge(service.getMyWitness(o1.getPaymentAccountPayload()), new Date()));
}).collect(Collectors.toList());
.filter(paymentAccount -> isPaymentAccountValidForOffer(offer, paymentAccount))
.sorted((o1, o2) -> {
return new Long(service.getAccountAge(service.getMyWitness(o2.getPaymentAccountPayload()), new Date()))
.compareTo(service.getAccountAge(service.getMyWitness(o1.getPaymentAccountPayload()), new Date()));
}).collect(Collectors.toList());
list.stream().forEach(e -> log.info("getMostMaturePaymentAccountForOffer AccountName={}, witnessHashAsHex={}", e.getAccountName(), service.getMyWitnessHashAsHex(e.getPaymentAccountPayload())));
final Optional<PaymentAccount> first = list.stream().findFirst();
if (first.isPresent())

View File

@ -34,7 +34,7 @@ public final class SepaAccount extends CountryBasedPaymentAccount implements Ban
@Override
protected PaymentAccountPayload createPayload() {
return new SepaAccountPayload(paymentMethod.getId(), id,
CountryUtil.getAllSepaCountries());
CountryUtil.getAllSepaCountries());
}
@Override

View File

@ -152,38 +152,38 @@ public final class PaymentMethod implements PersistablePayload, Comparable {
}
ALL_VALUES = new ArrayList<>(Arrays.asList(
// EUR
SEPA = new PaymentMethod(SEPA_ID, 6 * DAY, maxTradeLimitMidRisk),
// EUR
SEPA = new PaymentMethod(SEPA_ID, 6 * DAY, maxTradeLimitMidRisk),
// UK
FASTER_PAYMENTS = new PaymentMethod(FASTER_PAYMENTS_ID, DAY, maxTradeLimitMidRisk),
// UK
FASTER_PAYMENTS = new PaymentMethod(FASTER_PAYMENTS_ID, DAY, maxTradeLimitMidRisk),
// Sweden
SWISH = new PaymentMethod(SWISH_ID, DAY, maxTradeLimitLowRisk),
// Sweden
SWISH = new PaymentMethod(SWISH_ID, DAY, maxTradeLimitLowRisk),
// US
CLEAR_X_CHANGE = new PaymentMethod(CLEAR_X_CHANGE_ID, 4 * DAY, maxTradeLimitMidRisk),
CHASE_QUICK_PAY = new PaymentMethod(CHASE_QUICK_PAY_ID, DAY, maxTradeLimitMidRisk),
US_POSTAL_MONEY_ORDER = new PaymentMethod(US_POSTAL_MONEY_ORDER_ID, 8 * DAY, maxTradeLimitMidRisk),
// US
CLEAR_X_CHANGE = new PaymentMethod(CLEAR_X_CHANGE_ID, 4 * DAY, maxTradeLimitMidRisk),
CHASE_QUICK_PAY = new PaymentMethod(CHASE_QUICK_PAY_ID, DAY, maxTradeLimitMidRisk),
US_POSTAL_MONEY_ORDER = new PaymentMethod(US_POSTAL_MONEY_ORDER_ID, 8 * DAY, maxTradeLimitMidRisk),
// Canada
INTERAC_E_TRANSFER = new PaymentMethod(INTERAC_E_TRANSFER_ID, DAY, maxTradeLimitMidRisk),
// Canada
INTERAC_E_TRANSFER = new PaymentMethod(INTERAC_E_TRANSFER_ID, DAY, maxTradeLimitMidRisk),
// Global
CASH_DEPOSIT = new PaymentMethod(CASH_DEPOSIT_ID, 4 * DAY, maxTradeLimitMidRisk),
NATIONAL_BANK = new PaymentMethod(NATIONAL_BANK_ID, 4 * DAY, maxTradeLimitMidRisk),
SAME_BANK = new PaymentMethod(SAME_BANK_ID, 2 * DAY, maxTradeLimitMidRisk),
SPECIFIC_BANKS = new PaymentMethod(SPECIFIC_BANKS_ID, 4 * DAY, maxTradeLimitMidRisk),
// Global
CASH_DEPOSIT = new PaymentMethod(CASH_DEPOSIT_ID, 4 * DAY, maxTradeLimitMidRisk),
NATIONAL_BANK = new PaymentMethod(NATIONAL_BANK_ID, 4 * DAY, maxTradeLimitMidRisk),
SAME_BANK = new PaymentMethod(SAME_BANK_ID, 2 * DAY, maxTradeLimitMidRisk),
SPECIFIC_BANKS = new PaymentMethod(SPECIFIC_BANKS_ID, 4 * DAY, maxTradeLimitMidRisk),
// Trans national
OK_PAY = new PaymentMethod(OK_PAY_ID, DAY, maxTradeLimitVeryLowRisk),
PERFECT_MONEY = new PaymentMethod(PERFECT_MONEY_ID, DAY, maxTradeLimitLowRisk),
// Trans national
OK_PAY = new PaymentMethod(OK_PAY_ID, DAY, maxTradeLimitVeryLowRisk),
PERFECT_MONEY = new PaymentMethod(PERFECT_MONEY_ID, DAY, maxTradeLimitLowRisk),
// China
ALI_PAY = new PaymentMethod(ALI_PAY_ID, DAY, maxTradeLimitLowRisk),
// China
ALI_PAY = new PaymentMethod(ALI_PAY_ID, DAY, maxTradeLimitLowRisk),
// Altcoins
BLOCK_CHAINS = new PaymentMethod(BLOCK_CHAINS_ID, DAY, maxTradeLimitVeryLowRisk)
// Altcoins
BLOCK_CHAINS = new PaymentMethod(BLOCK_CHAINS_ID, DAY, maxTradeLimitVeryLowRisk)
));
}
return ALL_VALUES;
@ -197,16 +197,16 @@ public final class PaymentMethod implements PersistablePayload, Comparable {
@Override
public PB.PaymentMethod toProtoMessage() {
return PB.PaymentMethod.newBuilder()
.setId(id)
.setMaxTradePeriod(maxTradePeriod)
.setMaxTradeLimit(maxTradeLimit)
.build();
.setId(id)
.setMaxTradePeriod(maxTradePeriod)
.setMaxTradeLimit(maxTradeLimit)
.build();
}
public static PaymentMethod fromProto(PB.PaymentMethod proto) {
return new PaymentMethod(proto.getId(),
proto.getMaxTradePeriod(),
Coin.valueOf(proto.getMaxTradeLimit()));
proto.getMaxTradePeriod(),
Coin.valueOf(proto.getMaxTradeLimit()));
}

View File

@ -117,7 +117,7 @@ public class CoreNetworkProtoResolver extends CoreProtoResolver implements Netwo
return GetBsqBlocksResponse.fromProto(proto.getGetBsqBlocksResponse(), messageVersion);
case NEW_BSQ_BLOCK_BROADCAST_MESSAGE:
return NewBsqBlockBroadcastMessage.fromProto(proto.getNewBsqBlockBroadcastMessage(), messageVersion);
case ADD_PERSISTABLE_NETWORK_PAYLOAD_MESSAGE:
return AddPersistableNetworkPayloadMessage.fromProto(proto.getAddPersistableNetworkPayloadMessage(), this, messageVersion);
default:

View File

@ -38,7 +38,7 @@ public abstract class HttpClientProvider {
@Override
public String toString() {
return "HttpClientProvider{" +
"\n httpClient=" + httpClient +
"\n}";
"\n httpClient=" + httpClient +
"\n}";
}
}

View File

@ -76,9 +76,9 @@ public class ProvidersRepository {
}
providerList = Arrays.asList(StringUtils.deleteWhitespace(providerAsString).split(","))
.stream()
.filter(e -> bannedNodes == null || !bannedNodes.contains(e.replace("http://", "").replace("/", "").replace(".onion", "")))
.collect(Collectors.toList());
.stream()
.filter(e -> bannedNodes == null || !bannedNodes.contains(e.replace("http://", "").replace("/", "").replace(".onion", "")))
.collect(Collectors.toList());
if (!providerList.isEmpty())
baseUrl = providerList.get(new Random().nextInt(providerList.size()));
@ -87,7 +87,7 @@ public class ProvidersRepository {
log.info("selected baseUrl={}, providerList={}", baseUrl, providerList);
else
log.warn("We received banned provider nodes: bannedNodes={}, selected baseUrl={}, providerList={}",
bannedNodes, baseUrl, providerList);
bannedNodes, baseUrl, providerList);
}

View File

@ -123,29 +123,29 @@ public final class PayDepositRequest extends TradeMessage {
@Override
public PB.NetworkEnvelope toProtoNetworkEnvelope() {
PB.PayDepositRequest.Builder builder = PB.PayDepositRequest.newBuilder()
.setTradeId(tradeId)
.setSenderNodeAddress(senderNodeAddress.toProtoMessage())
.setTradeAmount(tradeAmount)
.setTradePrice(tradePrice)
.setTxFee(txFee)
.setTakerFee(takerFee)
.setIsCurrencyForTakerFeeBtc(isCurrencyForTakerFeeBtc)
.addAllRawTransactionInputs(rawTransactionInputs.stream()
.map(RawTransactionInput::toProtoMessage).collect(Collectors.toList()))
.setChangeOutputValue(changeOutputValue)
.setTakerMultiSigPubKey(ByteString.copyFrom(takerMultiSigPubKey))
.setTakerPayoutAddressString(takerPayoutAddressString)
.setTakerPubKeyRing(takerPubKeyRing.toProtoMessage())
.setTakerPaymentAccountPayload((PB.PaymentAccountPayload) takerPaymentAccountPayload.toProtoMessage())
.setTakerAccountId(takerAccountId)
.setTakerFeeTxId(takerFeeTxId)
.addAllAcceptedArbitratorNodeAddresses(acceptedArbitratorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage).collect(Collectors.toList()))
.addAllAcceptedMediatorNodeAddresses(acceptedMediatorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage).collect(Collectors.toList()))
.setArbitratorNodeAddress(arbitratorNodeAddress.toProtoMessage())
.setMediatorNodeAddress(mediatorNodeAddress.toProtoMessage())
.setUid(uid);
.setTradeId(tradeId)
.setSenderNodeAddress(senderNodeAddress.toProtoMessage())
.setTradeAmount(tradeAmount)
.setTradePrice(tradePrice)
.setTxFee(txFee)
.setTakerFee(takerFee)
.setIsCurrencyForTakerFeeBtc(isCurrencyForTakerFeeBtc)
.addAllRawTransactionInputs(rawTransactionInputs.stream()
.map(RawTransactionInput::toProtoMessage).collect(Collectors.toList()))
.setChangeOutputValue(changeOutputValue)
.setTakerMultiSigPubKey(ByteString.copyFrom(takerMultiSigPubKey))
.setTakerPayoutAddressString(takerPayoutAddressString)
.setTakerPubKeyRing(takerPubKeyRing.toProtoMessage())
.setTakerPaymentAccountPayload((PB.PaymentAccountPayload) takerPaymentAccountPayload.toProtoMessage())
.setTakerAccountId(takerAccountId)
.setTakerFeeTxId(takerFeeTxId)
.addAllAcceptedArbitratorNodeAddresses(acceptedArbitratorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage).collect(Collectors.toList()))
.addAllAcceptedMediatorNodeAddresses(acceptedMediatorNodeAddresses.stream()
.map(NodeAddress::toProtoMessage).collect(Collectors.toList()))
.setArbitratorNodeAddress(arbitratorNodeAddress.toProtoMessage())
.setMediatorNodeAddress(mediatorNodeAddress.toProtoMessage())
.setUid(uid);
Optional.ofNullable(changeOutputAddress).ifPresent(builder::setChangeOutputAddress);
Optional.ofNullable(accountAgeWitnessSignatureOfOfferId).ifPresent(e -> builder.setAccountAgeWitnessSignatureOfOfferId(ByteString.copyFrom(e)));
@ -156,65 +156,65 @@ public final class PayDepositRequest extends TradeMessage {
public static PayDepositRequest fromProto(PB.PayDepositRequest proto, CoreProtoResolver coreProtoResolver, int messageVersion) {
List<RawTransactionInput> rawTransactionInputs = proto.getRawTransactionInputsList().stream()
.map(rawTransactionInput -> new RawTransactionInput(rawTransactionInput.getIndex(),
rawTransactionInput.getParentTransaction().toByteArray(), rawTransactionInput.getValue()))
.collect(Collectors.toList());
.map(rawTransactionInput -> new RawTransactionInput(rawTransactionInput.getIndex(),
rawTransactionInput.getParentTransaction().toByteArray(), rawTransactionInput.getValue()))
.collect(Collectors.toList());
List<NodeAddress> acceptedArbitratorNodeAddresses = proto.getAcceptedArbitratorNodeAddressesList().stream()
.map(NodeAddress::fromProto).collect(Collectors.toList());
.map(NodeAddress::fromProto).collect(Collectors.toList());
List<NodeAddress> acceptedMediatorNodeAddresses = proto.getAcceptedMediatorNodeAddressesList().stream()
.map(NodeAddress::fromProto).collect(Collectors.toList());
.map(NodeAddress::fromProto).collect(Collectors.toList());
return new PayDepositRequest(proto.getTradeId(),
NodeAddress.fromProto(proto.getSenderNodeAddress()),
proto.getTradeAmount(),
proto.getTradePrice(),
proto.getTxFee(),
proto.getTakerFee(),
proto.getIsCurrencyForTakerFeeBtc(),
rawTransactionInputs,
proto.getChangeOutputValue(),
ProtoUtil.stringOrNullFromProto(proto.getChangeOutputAddress()),
proto.getTakerMultiSigPubKey().toByteArray(),
proto.getTakerPayoutAddressString(),
PubKeyRing.fromProto(proto.getTakerPubKeyRing()),
coreProtoResolver.fromProto(proto.getTakerPaymentAccountPayload()),
proto.getTakerAccountId(),
proto.getTakerFeeTxId(),
acceptedArbitratorNodeAddresses,
acceptedMediatorNodeAddresses,
NodeAddress.fromProto(proto.getArbitratorNodeAddress()),
NodeAddress.fromProto(proto.getMediatorNodeAddress()),
proto.getUid(),
messageVersion,
ProtoUtil.byteArrayOrNullFromProto(proto.getAccountAgeWitnessSignatureOfOfferId()),
proto.getCurrentDate());
NodeAddress.fromProto(proto.getSenderNodeAddress()),
proto.getTradeAmount(),
proto.getTradePrice(),
proto.getTxFee(),
proto.getTakerFee(),
proto.getIsCurrencyForTakerFeeBtc(),
rawTransactionInputs,
proto.getChangeOutputValue(),
ProtoUtil.stringOrNullFromProto(proto.getChangeOutputAddress()),
proto.getTakerMultiSigPubKey().toByteArray(),
proto.getTakerPayoutAddressString(),
PubKeyRing.fromProto(proto.getTakerPubKeyRing()),
coreProtoResolver.fromProto(proto.getTakerPaymentAccountPayload()),
proto.getTakerAccountId(),
proto.getTakerFeeTxId(),
acceptedArbitratorNodeAddresses,
acceptedMediatorNodeAddresses,
NodeAddress.fromProto(proto.getArbitratorNodeAddress()),
NodeAddress.fromProto(proto.getMediatorNodeAddress()),
proto.getUid(),
messageVersion,
ProtoUtil.byteArrayOrNullFromProto(proto.getAccountAgeWitnessSignatureOfOfferId()),
proto.getCurrentDate());
}
@Override
public String toString() {
return "PayDepositRequest{" +
"\n senderNodeAddress=" + senderNodeAddress +
",\n tradeAmount=" + tradeAmount +
",\n tradePrice=" + tradePrice +
",\n txFee=" + txFee +
",\n takerFee=" + takerFee +
",\n isCurrencyForTakerFeeBtc=" + isCurrencyForTakerFeeBtc +
",\n rawTransactionInputs=" + rawTransactionInputs +
",\n changeOutputValue=" + changeOutputValue +
",\n changeOutputAddress='" + changeOutputAddress + '\'' +
",\n takerMultiSigPubKey=" + Utilities.bytesAsHexString(takerMultiSigPubKey) +
",\n takerPayoutAddressString='" + takerPayoutAddressString + '\'' +
",\n takerPubKeyRing=" + takerPubKeyRing +
",\n takerPaymentAccountPayload=" + takerPaymentAccountPayload +
",\n takerAccountId='" + takerAccountId + '\'' +
",\n takerFeeTxId='" + takerFeeTxId + '\'' +
",\n acceptedArbitratorNodeAddresses=" + acceptedArbitratorNodeAddresses +
",\n acceptedMediatorNodeAddresses=" + acceptedMediatorNodeAddresses +
",\n arbitratorNodeAddress=" + arbitratorNodeAddress +
",\n mediatorNodeAddress=" + mediatorNodeAddress +
",\n uid='" + uid + '\'' +
",\n accountAgeWitnessSignatureOfOfferId=" + Utilities.bytesAsHexString(accountAgeWitnessSignatureOfOfferId) +
",\n currentDate=" + new Date(currentDate) +
"\n} " + super.toString();
"\n senderNodeAddress=" + senderNodeAddress +
",\n tradeAmount=" + tradeAmount +
",\n tradePrice=" + tradePrice +
",\n txFee=" + txFee +
",\n takerFee=" + takerFee +
",\n isCurrencyForTakerFeeBtc=" + isCurrencyForTakerFeeBtc +
",\n rawTransactionInputs=" + rawTransactionInputs +
",\n changeOutputValue=" + changeOutputValue +
",\n changeOutputAddress='" + changeOutputAddress + '\'' +
",\n takerMultiSigPubKey=" + Utilities.bytesAsHexString(takerMultiSigPubKey) +
",\n takerPayoutAddressString='" + takerPayoutAddressString + '\'' +
",\n takerPubKeyRing=" + takerPubKeyRing +
",\n takerPaymentAccountPayload=" + takerPaymentAccountPayload +
",\n takerAccountId='" + takerAccountId + '\'' +
",\n takerFeeTxId='" + takerFeeTxId + '\'' +
",\n acceptedArbitratorNodeAddresses=" + acceptedArbitratorNodeAddresses +
",\n acceptedMediatorNodeAddresses=" + acceptedMediatorNodeAddresses +
",\n arbitratorNodeAddress=" + arbitratorNodeAddress +
",\n mediatorNodeAddress=" + mediatorNodeAddress +
",\n uid='" + uid + '\'' +
",\n accountAgeWitnessSignatureOfOfferId=" + Utilities.bytesAsHexString(accountAgeWitnessSignatureOfOfferId) +
",\n currentDate=" + new Date(currentDate) +
"\n} " + super.toString();
}
}

View File

@ -73,19 +73,19 @@ public final class PublishDepositTxRequest extends TradeMessage implements Mailb
@Nullable byte[] accountAgeWitnessSignatureOfPreparedDepositTx,
long currentDate) {
this(tradeId,
makerPaymentAccountPayload,
makerAccountId,
makerMultiSigPubKey,
makerContractAsJson,
makerContractSignature,
makerPayoutAddressString,
preparedDepositTx,
makerInputs,
senderNodeAddress,
uid,
Version.getP2PMessageVersion(),
accountAgeWitnessSignatureOfPreparedDepositTx,
currentDate);
makerPaymentAccountPayload,
makerAccountId,
makerMultiSigPubKey,
makerContractAsJson,
makerContractSignature,
makerPayoutAddressString,
preparedDepositTx,
makerInputs,
senderNodeAddress,
uid,
Version.getP2PMessageVersion(),
accountAgeWitnessSignatureOfPreparedDepositTx,
currentDate);
}
@ -125,63 +125,63 @@ public final class PublishDepositTxRequest extends TradeMessage implements Mailb
@Override
public PB.NetworkEnvelope toProtoNetworkEnvelope() {
final PB.PublishDepositTxRequest.Builder builder = PB.PublishDepositTxRequest.newBuilder()
.setTradeId(tradeId)
.setMakerPaymentAccountPayload((PB.PaymentAccountPayload) makerPaymentAccountPayload.toProtoMessage())
.setMakerAccountId(makerAccountId)
.setMakerMultiSigPubKey(ByteString.copyFrom(makerMultiSigPubKey))
.setMakerContractAsJson(makerContractAsJson)
.setMakerContractSignature(makerContractSignature)
.setMakerPayoutAddressString(makerPayoutAddressString)
.setPreparedDepositTx(ByteString.copyFrom(preparedDepositTx))
.addAllMakerInputs(makerInputs.stream().map(RawTransactionInput::toProtoMessage).collect(Collectors.toList()))
.setSenderNodeAddress(senderNodeAddress.toProtoMessage())
.setUid(uid);
.setTradeId(tradeId)
.setMakerPaymentAccountPayload((PB.PaymentAccountPayload) makerPaymentAccountPayload.toProtoMessage())
.setMakerAccountId(makerAccountId)
.setMakerMultiSigPubKey(ByteString.copyFrom(makerMultiSigPubKey))
.setMakerContractAsJson(makerContractAsJson)
.setMakerContractSignature(makerContractSignature)
.setMakerPayoutAddressString(makerPayoutAddressString)
.setPreparedDepositTx(ByteString.copyFrom(preparedDepositTx))
.addAllMakerInputs(makerInputs.stream().map(RawTransactionInput::toProtoMessage).collect(Collectors.toList()))
.setSenderNodeAddress(senderNodeAddress.toProtoMessage())
.setUid(uid);
Optional.ofNullable(accountAgeWitnessSignatureOfPreparedDepositTx).ifPresent(e -> builder.setAccountAgeWitnessSignatureOfPreparedDepositTx(ByteString.copyFrom(e)));
builder.setCurrentDate(currentDate);
return getNetworkEnvelopeBuilder()
.setPublishDepositTxRequest(builder)
.build();
.setPublishDepositTxRequest(builder)
.build();
}
public static PublishDepositTxRequest fromProto(PB.PublishDepositTxRequest proto, CoreProtoResolver coreProtoResolver, int messageVersion) {
List<RawTransactionInput> makerInputs = proto.getMakerInputsList().stream()
.map(RawTransactionInput::fromProto)
.collect(Collectors.toList());
.map(RawTransactionInput::fromProto)
.collect(Collectors.toList());
return new PublishDepositTxRequest(proto.getTradeId(),
coreProtoResolver.fromProto(proto.getMakerPaymentAccountPayload()),
proto.getMakerAccountId(),
proto.getMakerMultiSigPubKey().toByteArray(),
proto.getMakerContractAsJson(),
proto.getMakerContractSignature(),
proto.getMakerPayoutAddressString(),
proto.getPreparedDepositTx().toByteArray(),
makerInputs,
NodeAddress.fromProto(proto.getSenderNodeAddress()),
proto.getUid(),
messageVersion,
ProtoUtil.byteArrayOrNullFromProto(proto.getAccountAgeWitnessSignatureOfPreparedDepositTx()),
proto.getCurrentDate());
coreProtoResolver.fromProto(proto.getMakerPaymentAccountPayload()),
proto.getMakerAccountId(),
proto.getMakerMultiSigPubKey().toByteArray(),
proto.getMakerContractAsJson(),
proto.getMakerContractSignature(),
proto.getMakerPayoutAddressString(),
proto.getPreparedDepositTx().toByteArray(),
makerInputs,
NodeAddress.fromProto(proto.getSenderNodeAddress()),
proto.getUid(),
messageVersion,
ProtoUtil.byteArrayOrNullFromProto(proto.getAccountAgeWitnessSignatureOfPreparedDepositTx()),
proto.getCurrentDate());
}
@Override
public String toString() {
return "PublishDepositTxRequest{" +
"\n makerPaymentAccountPayload=" + makerPaymentAccountPayload +
",\n makerAccountId='" + makerAccountId + '\'' +
",\n makerMultiSigPubKey=" + Utilities.bytesAsHexString(makerMultiSigPubKey) +
",\n makerContractAsJson='" + makerContractAsJson + '\'' +
",\n makerContractSignature='" + makerContractSignature + '\'' +
",\n makerPayoutAddressString='" + makerPayoutAddressString + '\'' +
",\n preparedDepositTx=" + Utilities.bytesAsHexString(preparedDepositTx) +
",\n makerInputs=" + makerInputs +
",\n senderNodeAddress=" + senderNodeAddress +
",\n uid='" + uid + '\'' +
",\n accountAgeWitnessSignatureOfPreparedDepositTx=" + Utilities.bytesAsHexString(accountAgeWitnessSignatureOfPreparedDepositTx) +
",\n currentDate=" + new Date(currentDate) +
"\n} " + super.toString();
"\n makerPaymentAccountPayload=" + makerPaymentAccountPayload +
",\n makerAccountId='" + makerAccountId + '\'' +
",\n makerMultiSigPubKey=" + Utilities.bytesAsHexString(makerMultiSigPubKey) +
",\n makerContractAsJson='" + makerContractAsJson + '\'' +
",\n makerContractSignature='" + makerContractSignature + '\'' +
",\n makerPayoutAddressString='" + makerPayoutAddressString + '\'' +
",\n preparedDepositTx=" + Utilities.bytesAsHexString(preparedDepositTx) +
",\n makerInputs=" + makerInputs +
",\n senderNodeAddress=" + senderNodeAddress +
",\n uid='" + uid + '\'' +
",\n accountAgeWitnessSignatureOfPreparedDepositTx=" + Utilities.bytesAsHexString(accountAgeWitnessSignatureOfPreparedDepositTx) +
",\n currentDate=" + new Date(currentDate) +
"\n} " + super.toString();
}
}

View File

@ -56,8 +56,8 @@ public class SellerAsMakerProtocol extends TradeProtocol implements SellerProtoc
Trade.Phase phase = trade.getState().getPhase();
if (phase == Trade.Phase.TAKER_FEE_PUBLISHED) {
TradeTaskRunner taskRunner = new TradeTaskRunner(trade,
() -> handleTaskRunnerSuccess("MakerSetupDepositTxListener"),
this::handleTaskRunnerFault);
() -> handleTaskRunnerSuccess("MakerSetupDepositTxListener"),
this::handleTaskRunnerFault);
taskRunner.addTasks(MakerSetupDepositTxListener.class);
taskRunner.run();
@ -95,24 +95,24 @@ public class SellerAsMakerProtocol extends TradeProtocol implements SellerProtoc
processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsMakerTrade,
() -> handleTaskRunnerSuccess("handleTakeOfferRequest"),
errorMessage -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
() -> handleTaskRunnerSuccess("handleTakeOfferRequest"),
errorMessage -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
taskRunner.addTasks(
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
VerifyPeersAccountAgeWitness.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
SellerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
VerifyPeersAccountAgeWitness.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
SellerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class
);
// We don't start a timeout because if we don't receive the peers DepositTxPublishedMessage we still
@ -136,10 +136,10 @@ public class SellerAsMakerProtocol extends TradeProtocol implements SellerProtoc
this::handleTaskRunnerFault);
taskRunner.addTasks(
MakerProcessDepositTxPublishedMessage.class,
MakerPublishTradeStatistics.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class
MakerProcessDepositTxPublishedMessage.class,
MakerPublishTradeStatistics.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class
);
taskRunner.run();
}
@ -154,13 +154,13 @@ public class SellerAsMakerProtocol extends TradeProtocol implements SellerProtoc
processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsMakerTrade,
() -> handleTaskRunnerSuccess("CounterCurrencyTransferStartedMessage"),
this::handleTaskRunnerFault);
() -> handleTaskRunnerSuccess("CounterCurrencyTransferStartedMessage"),
this::handleTaskRunnerFault);
taskRunner.addTasks(
SellerProcessCounterCurrencyTransferStartedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class
SellerProcessCounterCurrencyTransferStartedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class
);
taskRunner.run();
}
@ -176,45 +176,45 @@ public class SellerAsMakerProtocol extends TradeProtocol implements SellerProtoc
if (trade.getPayoutTx() == null) {
sellerAsMakerTrade.setState(Trade.State.SELLER_CONFIRMED_IN_UI_FIAT_PAYMENT_RECEIPT);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsMakerTrade,
() -> {
resultHandler.handleResult();
handleTaskRunnerSuccess("onFiatPaymentReceived 1");
},
(errorMessage) -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
() -> {
resultHandler.handleResult();
handleTaskRunnerSuccess("onFiatPaymentReceived 1");
},
(errorMessage) -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
taskRunner.addTasks(
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class
);
taskRunner.run();
} else {
// we don't set the state as we have already a later phase reached
log.info("onFiatPaymentReceived called twice. " +
"That can happen if message did not arrive first time and we send msg again.\n" +
"state=" + sellerAsMakerTrade.getState());
"That can happen if message did not arrive first time and we send msg again.\n" +
"state=" + sellerAsMakerTrade.getState());
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsMakerTrade,
() -> {
resultHandler.handleResult();
handleTaskRunnerSuccess("onFiatPaymentReceived 2");
},
(errorMessage) -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
() -> {
resultHandler.handleResult();
handleTaskRunnerSuccess("onFiatPaymentReceived 2");
},
(errorMessage) -> {
errorMessageHandler.handleErrorMessage(errorMessage);
handleTaskRunnerFault(errorMessage);
});
taskRunner.addTasks(
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSendPayoutTxPublishedMessage.class
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSendPayoutTxPublishedMessage.class
);
taskRunner.run();
}

View File

@ -81,18 +81,18 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
@Override
public void takeAvailableOffer() {
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> handleTaskRunnerSuccess("takeAvailableOffer"),
this::handleTaskRunnerFault);
() -> handleTaskRunnerSuccess("takeAvailableOffer"),
this::handleTaskRunnerFault);
taskRunner.addTasks(
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerSelectArbitrator.class,
TakerSelectMediator.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
SellerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerSelectArbitrator.class,
TakerSelectMediator.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
SellerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class
);
//TODO if peer does get an error he does not respond and all we get is the timeout now knowing why it failed.
@ -111,21 +111,21 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> {
stopTimeout();
handleTaskRunnerSuccess("PublishDepositTxRequest");
},
this::handleTaskRunnerFault);
() -> {
stopTimeout();
handleTaskRunnerSuccess("PublishDepositTxRequest");
},
this::handleTaskRunnerFault);
taskRunner.addTasks(
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
VerifyPeersAccountAgeWitness.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
SellerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
VerifyPeersAccountAgeWitness.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
SellerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class
);
taskRunner.run();
}
@ -140,13 +140,13 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> handleTaskRunnerSuccess("CounterCurrencyTransferStartedMessage"),
this::handleTaskRunnerFault);
() -> handleTaskRunnerSuccess("CounterCurrencyTransferStartedMessage"),
this::handleTaskRunnerFault);
taskRunner.addTasks(
SellerProcessCounterCurrencyTransferStartedMessage.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class
SellerProcessCounterCurrencyTransferStartedMessage.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class
);
taskRunner.run();
}

View File

@ -74,7 +74,7 @@ public final class TradingPeer implements PersistablePayload {
@Override
public Message toProtoMessage() {
final PB.TradingPeer.Builder builder = PB.TradingPeer.newBuilder()
.setChangeOutputValue(changeOutputValue);
.setChangeOutputValue(changeOutputValue);
Optional.ofNullable(accountId).ifPresent(builder::setAccountId);
Optional.ofNullable(paymentAccountPayload).ifPresent(e -> builder.setPaymentAccountPayload((PB.PaymentAccountPayload) e.toProtoMessage()));
Optional.ofNullable(payoutAddressString).ifPresent(builder::setPayoutAddressString);
@ -106,10 +106,10 @@ public final class TradingPeer implements PersistablePayload {
tradingPeer.setPubKeyRing(proto.hasPubKeyRing() ? PubKeyRing.fromProto(proto.getPubKeyRing()) : null);
tradingPeer.setMultiSigPubKey(ProtoUtil.byteArrayOrNullFromProto(proto.getMultiSigPubKey()));
List<RawTransactionInput> rawTransactionInputs = proto.getRawTransactionInputsList().isEmpty() ?
null :
proto.getRawTransactionInputsList().stream()
.map(RawTransactionInput::fromProto)
.collect(Collectors.toList());
null :
proto.getRawTransactionInputsList().stream()
.map(RawTransactionInput::fromProto)
.collect(Collectors.toList());
tradingPeer.setRawTransactionInputs(rawTransactionInputs);
tradingPeer.setChangeOutputAddress(ProtoUtil.stringOrNullFromProto(proto.getChangeOutputAddress()));
tradingPeer.setAccountAgeWitnessNonce(ProtoUtil.byteArrayOrNullFromProto(proto.getAccountAgeWitnessNonce()));

View File

@ -81,13 +81,13 @@ public class TradeStatisticsManager implements PersistedDataHost {
public void onAllServicesInitialized() {
if (dumpStatistics) {
ArrayList<CurrencyTuple> fiatCurrencyList = new ArrayList<>(CurrencyUtil.getAllSortedFiatCurrencies().stream()
.map(e -> new CurrencyTuple(e.getCode(), e.getName(), 8))
.collect(Collectors.toList()));
.map(e -> new CurrencyTuple(e.getCode(), e.getName(), 8))
.collect(Collectors.toList()));
jsonFileManager.writeToDisc(Utilities.objectToJson(fiatCurrencyList), "fiat_currency_list");
ArrayList<CurrencyTuple> cryptoCurrencyList = new ArrayList<>(CurrencyUtil.getAllSortedCryptoCurrencies().stream()
.map(e -> new CurrencyTuple(e.getCode(), e.getName(), 8))
.collect(Collectors.toList()));
.map(e -> new CurrencyTuple(e.getCode(), e.getName(), 8))
.collect(Collectors.toList()));
cryptoCurrencyList.add(0, new CurrencyTuple(Res.getBaseCurrencyCode(), Res.getBaseCurrencyName(), 8));
jsonFileManager.writeToDisc(Utilities.objectToJson(cryptoCurrencyList), "crypto_currency_list");
}
@ -159,12 +159,12 @@ public class TradeStatisticsManager implements PersistedDataHost {
});
mapByCurrencyCode.values().stream()
.filter(list -> !list.isEmpty())
.forEach(list -> {
list.sort((o1, o2) -> o1.getTradeDate().compareTo(o2.getTradeDate()));
TradeStatistics tradeStatistics = list.get(list.size() - 1);
priceFeedService.setBisqMarketPrice(tradeStatistics.getCurrencyCode(), tradeStatistics.getTradePrice());
});
.filter(list -> !list.isEmpty())
.forEach(list -> {
list.sort((o1, o2) -> o1.getTradeDate().compareTo(o2.getTradeDate()));
TradeStatistics tradeStatistics = list.get(list.size() - 1);
priceFeedService.setBisqMarketPrice(tradeStatistics.getCurrencyCode(), tradeStatistics.getTradePrice());
});
}
public void add(TradeStatistics tradeStatistics, boolean storeLocally) {
@ -222,8 +222,8 @@ public class TradeStatisticsManager implements PersistedDataHost {
StringBuilder sb1 = new StringBuilder("\nAll traded Fiat currencies:\n");
map1.entrySet().stream()
.sorted((o1, o2) -> Integer.valueOf(o2.getValue().size()).compareTo(o1.getValue().size()))
.forEach(e -> sb1.append(e.getKey()).append(": ").append(e.getValue().size()).append("\n"));
.sorted((o1, o2) -> Integer.valueOf(o2.getValue().size()).compareTo(o1.getValue().size()))
.forEach(e -> sb1.append(e.getKey()).append(": ").append(e.getValue().size()).append("\n"));
log.error(sb1.toString());
Map<String, Set<TradeStatistics>> map2 = new HashMap<>();
@ -263,30 +263,30 @@ public class TradeStatisticsManager implements PersistedDataHost {
newlyAdded.add("DEC");
CurrencyUtil.getAllSortedCryptoCurrencies().stream()
.forEach(e -> allCryptoCurrencies.add(e.getNameAndCode()));
.forEach(e -> allCryptoCurrencies.add(e.getNameAndCode()));
StringBuilder sb2 = new StringBuilder("\nAll traded Crypto currencies:\n");
StringBuilder sb3 = new StringBuilder("\nNever traded Crypto currencies:\n");
map2.entrySet().stream()
.sorted((o1, o2) -> Integer.valueOf(o2.getValue().size()).compareTo(o1.getValue().size()))
.forEach(e -> {
final String key = e.getKey();
sb2.append(key).append(": ").append(e.getValue().size()).append("\n");
// key is: USD Tether (USDT)
String code = key.substring(key.indexOf("(") + 1, key.length() - 1);
if (!coinsWithValidator.contains(code) && !newlyAdded.contains(code))
allCryptoCurrencies.remove(key);
});
.sorted((o1, o2) -> Integer.valueOf(o2.getValue().size()).compareTo(o1.getValue().size()))
.forEach(e -> {
final String key = e.getKey();
sb2.append(key).append(": ").append(e.getValue().size()).append("\n");
// key is: USD Tether (USDT)
String code = key.substring(key.indexOf("(") + 1, key.length() - 1);
if (!coinsWithValidator.contains(code) && !newlyAdded.contains(code))
allCryptoCurrencies.remove(key);
});
log.error(sb2.toString());
// Not considered age of newly added coins, so take care with removal if coin was added recently.
allCryptoCurrencies.sort(String::compareTo);
allCryptoCurrencies.stream()
.forEach(e -> {
// key is: USD Tether (USDT)
String code = e.substring(e.indexOf("(") + 1, e.length() - 1);
if (!coinsWithValidator.contains(code) && !newlyAdded.contains(code))
sb3.append(e).append("\n");
});
.forEach(e -> {
// key is: USD Tether (USDT)
String code = e.substring(e.indexOf("(") + 1, e.length() - 1);
if (!coinsWithValidator.contains(code) && !newlyAdded.contains(code))
sb3.append(e).append("\n");
});
log.error(sb3.toString());
}
}

View File

@ -35,56 +35,56 @@ import static com.google.common.base.Preconditions.checkNotNull;
public final class Preferences implements PersistedDataHost {
private static final ArrayList<BlockChainExplorer> BTC_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("Tradeblock", "https://tradeblock.com/bitcoin/tx/", "https://tradeblock.com/bitcoin/address/"),
new BlockChainExplorer("OXT", "https://oxt.me/transaction/", "https://oxt.me/address/"),
new BlockChainExplorer("Blockchain.info", "https://blockchain.info/tx/", "https://blockchain.info/address/"),
new BlockChainExplorer("Blockexplorer", "https://blockexplorer.com/tx/", "https://blockexplorer.com/address/"),
new BlockChainExplorer("Biteasy", "https://www.biteasy.com/transactions/", "https://www.biteasy.com/addresses/"),
new BlockChainExplorer("Blockonomics", "https://www.blockonomics.co/api/tx?txid=", "https://www.blockonomics.co/#/search?q="),
new BlockChainExplorer("Chainflyer", "http://chainflyer.bitflyer.jp/Transaction/", "http://chainflyer.bitflyer.jp/Address/"),
new BlockChainExplorer("Smartbit", "https://www.smartbit.com.au/tx/", "https://www.smartbit.com.au/address/"),
new BlockChainExplorer("SoChain. Wow.", "https://chain.so/tx/BTC/", "https://chain.so/address/BTC/"),
new BlockChainExplorer("Bitaps", "https://bitaps.com/", "https://bitaps.com/"),
new BlockChainExplorer("Insight", "https://insight.bitpay.com/tx/", "https://insight.bitpay.com/address/"),
new BlockChainExplorer("Bitaps", "https://bitaps.com/", "https://bitaps.com/")
new BlockChainExplorer("Tradeblock", "https://tradeblock.com/bitcoin/tx/", "https://tradeblock.com/bitcoin/address/"),
new BlockChainExplorer("OXT", "https://oxt.me/transaction/", "https://oxt.me/address/"),
new BlockChainExplorer("Blockchain.info", "https://blockchain.info/tx/", "https://blockchain.info/address/"),
new BlockChainExplorer("Blockexplorer", "https://blockexplorer.com/tx/", "https://blockexplorer.com/address/"),
new BlockChainExplorer("Biteasy", "https://www.biteasy.com/transactions/", "https://www.biteasy.com/addresses/"),
new BlockChainExplorer("Blockonomics", "https://www.blockonomics.co/api/tx?txid=", "https://www.blockonomics.co/#/search?q="),
new BlockChainExplorer("Chainflyer", "http://chainflyer.bitflyer.jp/Transaction/", "http://chainflyer.bitflyer.jp/Address/"),
new BlockChainExplorer("Smartbit", "https://www.smartbit.com.au/tx/", "https://www.smartbit.com.au/address/"),
new BlockChainExplorer("SoChain. Wow.", "https://chain.so/tx/BTC/", "https://chain.so/address/BTC/"),
new BlockChainExplorer("Bitaps", "https://bitaps.com/", "https://bitaps.com/"),
new BlockChainExplorer("Insight", "https://insight.bitpay.com/tx/", "https://insight.bitpay.com/address/"),
new BlockChainExplorer("Bitaps", "https://bitaps.com/", "https://bitaps.com/")
));
private static final ArrayList<BlockChainExplorer> BTC_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("Blocktrail", "https://www.blocktrail.com/tBTC/tx/", "https://www.blocktrail.com/tBTC/address/"),
new BlockChainExplorer("Blockexplorer", "https://blockexplorer.com/testnet/tx/", "https://blockexplorer.com/testnet/address/"),
new BlockChainExplorer("Biteasy", "https://www.biteasy.com/testnet/transactions/", "https://www.biteasy.com/testnet/addresses/"),
new BlockChainExplorer("Smartbit", "https://testnet.smartbit.com.au/tx/", "https://testnet.smartbit.com.au/address/"),
new BlockChainExplorer("SoChain. Wow.", "https://chain.so/tx/BTCTEST/", "https://chain.so/address/BTCTEST/")
new BlockChainExplorer("Blocktrail", "https://www.blocktrail.com/tBTC/tx/", "https://www.blocktrail.com/tBTC/address/"),
new BlockChainExplorer("Blockexplorer", "https://blockexplorer.com/testnet/tx/", "https://blockexplorer.com/testnet/address/"),
new BlockChainExplorer("Biteasy", "https://www.biteasy.com/testnet/transactions/", "https://www.biteasy.com/testnet/addresses/"),
new BlockChainExplorer("Smartbit", "https://testnet.smartbit.com.au/tx/", "https://testnet.smartbit.com.au/address/"),
new BlockChainExplorer("SoChain. Wow.", "https://chain.so/tx/BTCTEST/", "https://chain.so/address/BTCTEST/")
));
public static final BlockChainExplorer BSQ_MAIN_NET_EXPLORER = new BlockChainExplorer("BSQ", "https://explorer.bisq.network/tx.html?tx=",
"https://explorer.bisq.network/Address.html?addr=");
"https://explorer.bisq.network/Address.html?addr=");
public static final BlockChainExplorer BSQ_TEST_NET_EXPLORER = new BlockChainExplorer("BSQ", "https://explorer.bisq.network/testnet/tx.html?tx=",
"https://explorer.bisq.network/testnet/Address.html?addr=");
"https://explorer.bisq.network/testnet/Address.html?addr=");
private static final ArrayList<BlockChainExplorer> LTC_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("CryptoID", "https://chainz.cryptoid.info/ltc/tx.dws?", "https://chainz.cryptoid.info/ltc/address.dws?"),
new BlockChainExplorer("Abe Search", "http://explorer.litecoin.net/tx/", "http://explorer.litecoin.net/address/"),
new BlockChainExplorer("Blockcypher", "https://live.blockcypher.com/ltc/tx", "https://live.blockcypher.com/ltc/address"),
new BlockChainExplorer("SoChain", "https://chain.so/tx/LTC/", "https://chain.so/address/LTC/"),
new BlockChainExplorer("Blockr.io", "http://ltc.blockr.io/tx/info/", "http://ltc.blockr.io/address/info/")
new BlockChainExplorer("CryptoID", "https://chainz.cryptoid.info/ltc/tx.dws?", "https://chainz.cryptoid.info/ltc/address.dws?"),
new BlockChainExplorer("Abe Search", "http://explorer.litecoin.net/tx/", "http://explorer.litecoin.net/address/"),
new BlockChainExplorer("Blockcypher", "https://live.blockcypher.com/ltc/tx", "https://live.blockcypher.com/ltc/address"),
new BlockChainExplorer("SoChain", "https://chain.so/tx/LTC/", "https://chain.so/address/LTC/"),
new BlockChainExplorer("Blockr.io", "http://ltc.blockr.io/tx/info/", "http://ltc.blockr.io/address/info/")
));
private static final ArrayList<BlockChainExplorer> LTC_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("SoChain", "https://chain.so/tx/LTCTEST/", "https://chain.so/address/LTCTEST/")
new BlockChainExplorer("SoChain", "https://chain.so/tx/LTCTEST/", "https://chain.so/address/LTCTEST/")
));
private static final ArrayList<BlockChainExplorer> DOGE_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("SoChain", "https://chain.so/tx/doge/", "https://chain.so/address/doge/")
new BlockChainExplorer("SoChain", "https://chain.so/tx/doge/", "https://chain.so/address/doge/")
));
private static final ArrayList<BlockChainExplorer> DOGE_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("SoChain", "https://chain.so/tx/DOGETEST/", "https://chain.so/address/DOGETEST/")
new BlockChainExplorer("SoChain", "https://chain.so/tx/DOGETEST/", "https://chain.so/address/DOGETEST/")
));
private static final ArrayList<BlockChainExplorer> DASH_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("SoChain", "https://chain.so/tx/dash/", "https://chain.so/address/dash/")
new BlockChainExplorer("SoChain", "https://chain.so/tx/dash/", "https://chain.so/address/dash/")
));
private static final ArrayList<BlockChainExplorer> DASH_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("SoChain", "https://chain.so/tx/DASHTEST/", "https://chain.so/address/DASHTEST/")
new BlockChainExplorer("SoChain", "https://chain.so/tx/DASHTEST/", "https://chain.so/address/DASHTEST/")
));
@ -182,7 +182,7 @@ public final class Preferences implements PersistedDataHost {
prefPayload.setUserCountry(CountryUtil.getDefaultCountry());
GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code));
preferredTradeCurrency = checkNotNull(CurrencyUtil.getCurrencyByCountryCode(prefPayload.getUserCountry().code),
"preferredTradeCurrency must not be null");
"preferredTradeCurrency must not be null");
prefPayload.setPreferredTradeCurrency(preferredTradeCurrency);
setFiatCurrencies(CurrencyUtil.getMainFiatCurrencies());
setCryptoCurrencies(CurrencyUtil.getMainCryptoCurrencies());
@ -281,7 +281,7 @@ public final class Preferences implements PersistedDataHost {
fiatCurrenciesAsObservable.remove(tradeCurrency);
if (prefPayload.getPreferredTradeCurrency() != null &&
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
@ -299,7 +299,7 @@ public final class Preferences implements PersistedDataHost {
cryptoCurrenciesAsObservable.remove(tradeCurrency);
if (prefPayload.getPreferredTradeCurrency() != null &&
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
@ -435,8 +435,8 @@ public final class Preferences implements PersistedDataHost {
public void setBuyerSecurityDepositAsLong(long buyerSecurityDepositAsLong) {
prefPayload.setBuyerSecurityDepositAsLong(Math.min(Restrictions.getMaxBuyerSecurityDeposit().value,
Math.max(Restrictions.getMinBuyerSecurityDeposit().value,
buyerSecurityDepositAsLong)));
Math.max(Restrictions.getMinBuyerSecurityDeposit().value,
buyerSecurityDepositAsLong)));
persist();
}
@ -545,8 +545,8 @@ public final class Preferences implements PersistedDataHost {
// Atm we don't support onion addresses there
// This check includes localhost, so we also override useTorForBitcoinJ
if (prefPayload.getBitcoinNodes() != null && !prefPayload.getBitcoinNodes().isEmpty()
|| BisqEnvironment.getBaseCurrencyNetwork().isRegtest()
|| bisqEnvironment.isBitcoinLocalhostNodeRunning())
|| BisqEnvironment.getBaseCurrencyNetwork().isRegtest()
|| bisqEnvironment.isBitcoinLocalhostNodeRunning())
return false;
else
return prefPayload.isUseTorForBitcoinJ();

View File

@ -149,36 +149,36 @@ public final class PreferencesPayload implements PersistableEnvelope {
@Override
public Message toProtoMessage() {
PB.PreferencesPayload.Builder builder = PB.PreferencesPayload.newBuilder()
.setUserLanguage(userLanguage)
.setUserCountry((PB.Country) userCountry.toProtoMessage())
.addAllFiatCurrencies(fiatCurrencies.stream()
.map(fiatCurrency -> ((PB.TradeCurrency) fiatCurrency.toProtoMessage()))
.collect(Collectors.toList()))
.addAllCryptoCurrencies(cryptoCurrencies.stream()
.map(cryptoCurrency -> ((PB.TradeCurrency) cryptoCurrency.toProtoMessage()))
.collect(Collectors.toList()))
.setBlockChainExplorerMainNet((PB.BlockChainExplorer) blockChainExplorerMainNet.toProtoMessage())
.setBlockChainExplorerTestNet((PB.BlockChainExplorer) blockChainExplorerTestNet.toProtoMessage())
.setBsqBlockChainExplorer((PB.BlockChainExplorer) bsqBlockChainExplorer.toProtoMessage())
.setAutoSelectArbitrators(autoSelectArbitrators)
.putAllDontShowAgainMap(dontShowAgainMap)
.setTacAccepted(tacAccepted)
.setUseTorForBitcoinJ(useTorForBitcoinJ)
.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook)
.setWithdrawalTxFeeInBytes(withdrawalTxFeeInBytes)
.setUseCustomWithdrawalTxFee(useCustomWithdrawalTxFee)
.setMaxPriceDistanceInPercent(maxPriceDistanceInPercent)
.setTradeStatisticsTickUnitIndex(tradeStatisticsTickUnitIndex)
.setResyncSpvRequested(resyncSpvRequested)
.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically)
.setUsePercentageBasedPrice(usePercentageBasedPrice)
.putAllPeerTagMap(peerTagMap)
.setBitcoinNodes(bitcoinNodes)
.addAllIgnoreTradersList(ignoreTradersList)
.setDirectoryChooserPath(directoryChooserPath)
.setBuyerSecurityDepositAsLong(buyerSecurityDepositAsLong)
.setUseAnimations(useAnimations)
.setPayFeeInBtc(payFeeInBtc);
.setUserLanguage(userLanguage)
.setUserCountry((PB.Country) userCountry.toProtoMessage())
.addAllFiatCurrencies(fiatCurrencies.stream()
.map(fiatCurrency -> ((PB.TradeCurrency) fiatCurrency.toProtoMessage()))
.collect(Collectors.toList()))
.addAllCryptoCurrencies(cryptoCurrencies.stream()
.map(cryptoCurrency -> ((PB.TradeCurrency) cryptoCurrency.toProtoMessage()))
.collect(Collectors.toList()))
.setBlockChainExplorerMainNet((PB.BlockChainExplorer) blockChainExplorerMainNet.toProtoMessage())
.setBlockChainExplorerTestNet((PB.BlockChainExplorer) blockChainExplorerTestNet.toProtoMessage())
.setBsqBlockChainExplorer((PB.BlockChainExplorer) bsqBlockChainExplorer.toProtoMessage())
.setAutoSelectArbitrators(autoSelectArbitrators)
.putAllDontShowAgainMap(dontShowAgainMap)
.setTacAccepted(tacAccepted)
.setUseTorForBitcoinJ(useTorForBitcoinJ)
.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook)
.setWithdrawalTxFeeInBytes(withdrawalTxFeeInBytes)
.setUseCustomWithdrawalTxFee(useCustomWithdrawalTxFee)
.setMaxPriceDistanceInPercent(maxPriceDistanceInPercent)
.setTradeStatisticsTickUnitIndex(tradeStatisticsTickUnitIndex)
.setResyncSpvRequested(resyncSpvRequested)
.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically)
.setUsePercentageBasedPrice(usePercentageBasedPrice)
.putAllPeerTagMap(peerTagMap)
.setBitcoinNodes(bitcoinNodes)
.addAllIgnoreTradersList(ignoreTradersList)
.setDirectoryChooserPath(directoryChooserPath)
.setBuyerSecurityDepositAsLong(buyerSecurityDepositAsLong)
.setUseAnimations(useAnimations)
.setPayFeeInBtc(payFeeInBtc);
Optional.ofNullable(backupDirectory).ifPresent(builder::setBackupDirectory);
Optional.ofNullable(preferredTradeCurrency).ifPresent(e -> builder.setPreferredTradeCurrency((PB.TradeCurrency) e.toProtoMessage()));
@ -187,7 +187,7 @@ public final class PreferencesPayload implements PersistableEnvelope {
Optional.ofNullable(buyScreenCurrencyCode).ifPresent(builder::setBuyScreenCurrencyCode);
Optional.ofNullable(sellScreenCurrencyCode).ifPresent(builder::setSellScreenCurrencyCode);
Optional.ofNullable(selectedPaymentAccountForCreateOffer).ifPresent(
account -> builder.setSelectedPaymentAccountForCreateOffer(selectedPaymentAccountForCreateOffer.toProtoMessage()));
account -> builder.setSelectedPaymentAccountForCreateOffer(selectedPaymentAccountForCreateOffer.toProtoMessage()));
return PB.PersistableEnvelope.newBuilder().setPreferencesPayload(builder).build();
}
@ -199,44 +199,44 @@ public final class PreferencesPayload implements PersistableEnvelope {
paymentAccount = PaymentAccount.fromProto(proto.getSelectedPaymentAccountForCreateOffer(), coreProtoResolver);
return new PreferencesPayload(
proto.getUserLanguage(),
Country.fromProto(userCountry),
proto.getFiatCurrenciesList().isEmpty() ? new ArrayList<>() :
new ArrayList<>(proto.getFiatCurrenciesList().stream()
.map(FiatCurrency::fromProto)
.collect(Collectors.toList())),
proto.getCryptoCurrenciesList().isEmpty() ? new ArrayList<>() :
new ArrayList<>(proto.getCryptoCurrenciesList().stream()
.map(CryptoCurrency::fromProto)
.collect(Collectors.toList())),
BlockChainExplorer.fromProto(proto.getBlockChainExplorerMainNet()),
BlockChainExplorer.fromProto(proto.getBlockChainExplorerTestNet()),
BlockChainExplorer.fromProto(proto.getBsqBlockChainExplorer()),
ProtoUtil.stringOrNullFromProto(proto.getBackupDirectory()),
proto.getAutoSelectArbitrators(),
Maps.newHashMap(proto.getDontShowAgainMapMap()),
proto.getTacAccepted(),
proto.getUseTorForBitcoinJ(),
proto.getShowOwnOffersInOfferBook(),
proto.hasPreferredTradeCurrency() ? TradeCurrency.fromProto(proto.getPreferredTradeCurrency()) : null,
proto.getWithdrawalTxFeeInBytes(),
proto.getUseCustomWithdrawalTxFee(),
proto.getMaxPriceDistanceInPercent(),
ProtoUtil.stringOrNullFromProto(proto.getOfferBookChartScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getTradeChartsScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getBuyScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getSellScreenCurrencyCode()),
proto.getTradeStatisticsTickUnitIndex(),
proto.getResyncSpvRequested(),
proto.getSortMarketCurrenciesNumerically(),
proto.getUsePercentageBasedPrice(),
Maps.newHashMap(proto.getPeerTagMapMap()),
proto.getBitcoinNodes(),
proto.getIgnoreTradersListList(),
proto.getDirectoryChooserPath(),
proto.getBuyerSecurityDepositAsLong(),
proto.getUseAnimations(),
paymentAccount,
proto.getPayFeeInBtc());
proto.getUserLanguage(),
Country.fromProto(userCountry),
proto.getFiatCurrenciesList().isEmpty() ? new ArrayList<>() :
new ArrayList<>(proto.getFiatCurrenciesList().stream()
.map(FiatCurrency::fromProto)
.collect(Collectors.toList())),
proto.getCryptoCurrenciesList().isEmpty() ? new ArrayList<>() :
new ArrayList<>(proto.getCryptoCurrenciesList().stream()
.map(CryptoCurrency::fromProto)
.collect(Collectors.toList())),
BlockChainExplorer.fromProto(proto.getBlockChainExplorerMainNet()),
BlockChainExplorer.fromProto(proto.getBlockChainExplorerTestNet()),
BlockChainExplorer.fromProto(proto.getBsqBlockChainExplorer()),
ProtoUtil.stringOrNullFromProto(proto.getBackupDirectory()),
proto.getAutoSelectArbitrators(),
Maps.newHashMap(proto.getDontShowAgainMapMap()),
proto.getTacAccepted(),
proto.getUseTorForBitcoinJ(),
proto.getShowOwnOffersInOfferBook(),
proto.hasPreferredTradeCurrency() ? TradeCurrency.fromProto(proto.getPreferredTradeCurrency()) : null,
proto.getWithdrawalTxFeeInBytes(),
proto.getUseCustomWithdrawalTxFee(),
proto.getMaxPriceDistanceInPercent(),
ProtoUtil.stringOrNullFromProto(proto.getOfferBookChartScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getTradeChartsScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getBuyScreenCurrencyCode()),
ProtoUtil.stringOrNullFromProto(proto.getSellScreenCurrencyCode()),
proto.getTradeStatisticsTickUnitIndex(),
proto.getResyncSpvRequested(),
proto.getSortMarketCurrenciesNumerically(),
proto.getUsePercentageBasedPrice(),
Maps.newHashMap(proto.getPeerTagMapMap()),
proto.getBitcoinNodes(),
proto.getIgnoreTradersListList(),
proto.getDirectoryChooserPath(),
proto.getBuyerSecurityDepositAsLong(),
proto.getUseAnimations(),
paymentAccount,
proto.getPayFeeInBtc());
}
}

View File

@ -86,10 +86,10 @@ public class UserPayload implements PersistableEnvelope {
.ifPresent(developersAlert -> builder.setDevelopersAlert(developersAlert.toProtoMessage().getAlert()));
Optional.ofNullable(acceptedArbitrators)
.ifPresent(e -> builder.addAllAcceptedArbitrators(ProtoUtil.collectionToProto(acceptedArbitrators,
message -> ((PB.StoragePayload) message).getArbitrator())));
message -> ((PB.StoragePayload) message).getArbitrator())));
Optional.ofNullable(acceptedMediators)
.ifPresent(e -> builder.addAllAcceptedMediators(ProtoUtil.collectionToProto(acceptedMediators,
message -> ((PB.StoragePayload) message).getMediator())));
message -> ((PB.StoragePayload) message).getMediator())));
return PB.PersistableEnvelope.newBuilder().setUserPayload(builder).build();
}

View File

@ -42,8 +42,8 @@ public class UserPayloadModelVOTest {
vo.setAccountId("accountId");
vo.setDisplayedAlert(new Alert("message", true, "version", new byte[]{12, -64, 12}, "string", null));
vo.setDevelopersFilter(new Filter(Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(),
Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(),
"string", new byte[]{10, 0, 0}, null));
Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(),
"string", new byte[]{10, 0, 0}, null));
vo.setRegisteredArbitrator(ArbitratorTest.getArbitratorMock());
vo.setRegisteredMediator(MediatorTest.getMediatorMock());
vo.setAcceptedArbitrators(Lists.newArrayList(ArbitratorTest.getArbitratorMock()));

View File

@ -135,10 +135,10 @@ public class BisqApp extends Application {
Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
// Might come from another thread
if (throwable.getCause() != null && throwable.getCause().getCause() != null &&
throwable.getCause().getCause() instanceof BlockStoreException) {
throwable.getCause().getCause() instanceof BlockStoreException) {
log.error(throwable.getMessage());
} else if (throwable instanceof ClassCastException &&
"sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData".equals(throwable.getMessage())) {
"sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData".equals(throwable.getMessage())) {
log.warn(throwable.getMessage());
} else {
log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
@ -231,9 +231,9 @@ public class BisqApp extends Application {
Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13);
Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13);
scene.getStylesheets().setAll(
"/io/bisq/gui/bisq.css",
"/io/bisq/gui/images.css",
"/io/bisq/gui/CandleStickChart.css");
"/io/bisq/gui/bisq.css",
"/io/bisq/gui/images.css",
"/io/bisq/gui/CandleStickChart.css");
// configure the system tray
SystemTray.create(primaryStage, shutDownHandler);
@ -245,7 +245,7 @@ public class BisqApp extends Application {
scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
Utilities.isAltOrCtrlPressed(KeyCode.W, keyEvent);
if (Utilities.isCtrlPressed(KeyCode.W, keyEvent) ||
Utilities.isCtrlPressed(KeyCode.Q, keyEvent)) {
Utilities.isCtrlPressed(KeyCode.Q, keyEvent)) {
stop();
} else {
if (Utilities.isAltOrCtrlPressed(KeyCode.E, keyEvent)) {
@ -310,10 +310,10 @@ public class BisqApp extends Application {
// We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
// Needs at least more testing on different machines...
new Popup<>().warning(Res.get("popup.warning.wrongVersion",
osArchitecture,
Utilities.getJVMArchitecture(),
osArchitecture))
.show();
osArchitecture,
Utilities.getJVMArchitecture(),
osArchitecture))
.show();
}
UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN, TimeUnit.MINUTES);
} catch (Throwable throwable) {
@ -325,17 +325,17 @@ public class BisqApp extends Application {
private void showSendAlertMessagePopup() {
AlertManager alertManager = injector.getInstance(AlertManager.class);
new SendAlertMessageWindow()
.onAddAlertMessage(alertManager::addAlertMessageIfKeyIsValid)
.onRemoveAlertMessage(alertManager::removeAlertMessageIfKeyIsValid)
.show();
.onAddAlertMessage(alertManager::addAlertMessageIfKeyIsValid)
.onRemoveAlertMessage(alertManager::removeAlertMessageIfKeyIsValid)
.show();
}
private void showFilterPopup() {
FilterManager filterManager = injector.getInstance(FilterManager.class);
new FilterWindow(filterManager)
.onAddFilter(filterManager::addFilterMessageIfKeyIsValid)
.onRemoveFilter(filterManager::removeFilterMessageIfKeyIsValid)
.show();
.onAddFilter(filterManager::addFilterMessageIfKeyIsValid)
.onRemoveFilter(filterManager::removeFilterMessageIfKeyIsValid)
.show();
}
private void showEmptyWalletPopup(WalletService walletService) {
@ -350,8 +350,8 @@ public class BisqApp extends Application {
log.warn("Scene not available yet, we create a new scene. The bug might be caused by an exception in a constructor or by a circular dependency in guice. throwable=" + throwable.toString());
scene = new Scene(new StackPane(), 1000, 650);
scene.getStylesheets().setAll(
"/io/bisq/gui/bisq.css",
"/io/bisq/gui/images.css");
"/io/bisq/gui/bisq.css",
"/io/bisq/gui/images.css");
primaryStage.setScene(scene);
primaryStage.show();
}
@ -399,13 +399,13 @@ public class BisqApp extends Application {
private void showFPSWindow() {
Label label = new Label();
EventStreams.animationTicks()
.latestN(100)
.map(ticks -> {
int n = ticks.size() - 1;
return n * 1_000_000_000.0 / (ticks.get(n) - ticks.get(0));
})
.map(d -> String.format("FPS: %.3f", d)) // Don't translate, just for dev
.feedTo(label.textProperty());
.latestN(100)
.map(ticks -> {
int n = ticks.size() - 1;
return n * 1_000_000_000.0 / (ticks.get(n) - ticks.get(0));
})
.map(d -> String.format("FPS: %.3f", d)) // Don't translate, just for dev
.feedTo(label.textProperty());
Pane root = new StackPane();
root.getChildren().add(label);
@ -427,10 +427,10 @@ public class BisqApp extends Application {
public void stop() {
if (!shutDownRequested) {
new Popup<>().headLine(Res.get("popup.shutDownInProgress.headline"))
.backgroundInfo(Res.get("popup.shutDownInProgress.msg"))
.hideCloseButton()
.useAnimation(false)
.show();
.backgroundInfo(Res.get("popup.shutDownInProgress.msg"))
.hideCloseButton()
.useAnimation(false)
.show();
//noinspection CodeBlock2Expr
UserThread.runAfter(() -> {
gracefulShutDown(() -> {

View File

@ -55,12 +55,12 @@ public class PeerInfoIcon extends Group {
final boolean isFiatCurrency = CurrencyUtil.isFiatCurrency(offer.getCurrencyCode());
final long makersAccountAge = accountAgeWitnessService.getMakersAccountAge(offer, new Date());
final String accountAge = isFiatCurrency ?
makersAccountAge > -1 ? Res.get("peerInfoIcon.tooltip.age", formatter.formatAccountAge(makersAccountAge)) :
Res.get("peerInfoIcon.tooltip.unknownAge") :
"";
makersAccountAge > -1 ? Res.get("peerInfoIcon.tooltip.age", formatter.formatAccountAge(makersAccountAge)) :
Res.get("peerInfoIcon.tooltip.unknownAge") :
"";
tooltipText = hasTraded ?
Res.get("peerInfoIcon.tooltip.trade.traded", role, hostName, numTrades, accountAge) :
Res.get("peerInfoIcon.tooltip.trade.notTraded", role, hostName, accountAge);
Res.get("peerInfoIcon.tooltip.trade.traded", role, hostName, numTrades, accountAge) :
Res.get("peerInfoIcon.tooltip.trade.notTraded", role, hostName, accountAge);
// outer circle
Color ringColor;
@ -98,7 +98,7 @@ public class PeerInfoIcon extends Group {
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] bytes = md.digest(address.getBytes());
intValue = Math.abs(((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16)
| ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF));
| ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
@ -152,20 +152,20 @@ public class PeerInfoIcon extends Group {
getChildren().addAll(outerBackground, innerBackground, avatarImageView, tagPane, numTradesPane);
final String accountAgeTagEditor = isFiatCurrency ?
makersAccountAge > -1 ?
formatter.formatAccountAge(makersAccountAge) :
Res.get("peerInfo.unknownAge") :
null;
makersAccountAge > -1 ?
formatter.formatAccountAge(makersAccountAge) :
Res.get("peerInfo.unknownAge") :
null;
setOnMouseClicked(e -> new PeerInfoWithTagEditor(privateNotificationManager, offer, preferences)
.hostName(hostName)
.numTrades(numTrades)
.accountAge(accountAgeTagEditor)
.position(localToScene(new Point2D(0, 0)))
.onSave(newTag -> {
preferences.setTagForPeer(hostName, newTag);
updatePeerInfoIcon();
})
.show());
.hostName(hostName)
.numTrades(numTrades)
.accountAge(accountAgeTagEditor)
.position(localToScene(new Point2D(0, 0)))
.onSave(newTag -> {
preferences.setTagForPeer(hostName, newTag);
updatePeerInfoIcon();
})
.show());
}
private void updatePeerInfoIcon() {

View File

@ -203,7 +203,7 @@ abstract class BankForm extends PaymentMethodForm {
private final Runnable closeHandler;
private ComboBox<TradeCurrency> currencyComboBox;
BankForm(PaymentAccount paymentAccount, AccountAgeWitnessService accountAgeWitnessService,InputValidator inputValidator,
BankForm(PaymentAccount paymentAccount, AccountAgeWitnessService accountAgeWitnessService, InputValidator inputValidator,
GridPane gridPane, int gridRow, BSFormatter formatter, Runnable closeHandler) {
super(paymentAccount, accountAgeWitnessService, inputValidator, gridPane, gridRow, formatter);
this.closeHandler = closeHandler;

View File

@ -210,8 +210,8 @@ public class CashDepositForm extends PaymentMethodForm {
private boolean useHolderID;
private ComboBox<TradeCurrency> currencyComboBox;
private final EmailValidator emailValidator;
public CashDepositForm(PaymentAccount paymentAccount, AccountAgeWitnessService accountAgeWitnessService, InputValidator inputValidator,
GridPane gridPane, int gridRow, BSFormatter formatter) {
super(paymentAccount, accountAgeWitnessService, inputValidator, gridPane, gridRow, formatter);

View File

@ -91,7 +91,7 @@ public abstract class PaymentMethodForm {
protected void addAccountNameTextFieldWithAutoFillCheckBox() {
Tuple3<Label, InputTextField, CheckBox> tuple = addLabelInputTextFieldCheckBox(gridPane, ++gridRow,
Res.get("payment.account.name"), Res.get("payment.useCustomAccountName"));
Res.get("payment.account.name"), Res.get("payment.useCustomAccountName"));
accountNameTextField = tuple.second;
accountNameTextField.setPrefWidth(300);
accountNameTextField.setEditable(false);
@ -117,7 +117,7 @@ public abstract class PaymentMethodForm {
String dateFromBlocks) {
long hours = offer.getMaxTradePeriod() / 3600_000;
addLabelTextField(gridPane, gridRow, Res.get("payment.maxPeriod"),
getTimeText(hours) + " / " + dateFromBlocks);
getTimeText(hours) + " / " + dateFromBlocks);
}
protected static String getTimeText(long hours) {
@ -144,15 +144,15 @@ public abstract class PaymentMethodForm {
tradeCurrency = paymentAccount.getTradeCurrencies().get(0);
else
tradeCurrency = paymentAccount instanceof CryptoCurrencyAccount ?
CurrencyUtil.getAllSortedCryptoCurrencies().get(0) :
CurrencyUtil.getDefaultTradeCurrency();
CurrencyUtil.getAllSortedCryptoCurrencies().get(0) :
CurrencyUtil.getDefaultTradeCurrency();
final boolean isAddAccountScreen = paymentAccount.getAccountName() == null;
final long accountAge = !isAddAccountScreen ? accountAgeWitnessService.getMyAccountAge(paymentAccount.getPaymentAccountPayload()) : 0L;
addLabelTextField(gridPane, ++gridRow, Res.get("payment.limitations"), Res.get("payment.maxPeriodAndLimit",
getTimeText(hours),
formatter.formatCoinWithCode(Coin.valueOf(accountAgeWitnessService.getMyTradeLimit(paymentAccount, tradeCurrency.getCode()))),
formatter.formatAccountAge(accountAge)));
getTimeText(hours),
formatter.formatCoinWithCode(Coin.valueOf(accountAgeWitnessService.getMyTradeLimit(paymentAccount, tradeCurrency.getCode()))),
formatter.formatAccountAge(accountAge)));
if (isAddAccountScreen) {
InputTextField inputTextField = addLabelInputTextField(gridPane, ++gridRow, Res.get("payment.salt"), 0).second;
@ -174,7 +174,7 @@ public abstract class PaymentMethodForm {
} else {
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, Res.get("payment.salt",
Utilities.bytesAsHexString(paymentAccount.getPaymentAccountPayload().getSalt())),
Utilities.bytesAsHexString(paymentAccount.getPaymentAccountPayload().getSalt()));
Utilities.bytesAsHexString(paymentAccount.getPaymentAccountPayload().getSalt()));
}
}

View File

@ -192,8 +192,8 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
lockedBalanceBox.first.textProperty().bind(model.lockedBalance);
HBox rightNavPane = new HBox(marketPriceBox.second, availableBalanceBox.second,
reservedBalanceBox.second, lockedBalanceBox.second,
settingsButton, accountButton, daoButton) {{
reservedBalanceBox.second, lockedBalanceBox.second,
settingsButton, accountButton, daoButton) {{
setRightAnchor(this, 10d);
setTopAnchor(this, 0d);
}};
@ -236,11 +236,11 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
contentContainer.getChildren().setAll(view.getRoot());
navButtons.getToggles().stream()
.filter(toggle -> toggle instanceof NavButton)
.filter(button -> viewClass == ((NavButton) button).viewClass)
.findFirst()
.orElseThrow(() -> new BisqException("No button matching %s found", viewClass))
.setSelected(true);
.filter(toggle -> toggle instanceof NavButton)
.filter(button -> viewClass == ((NavButton) button).viewClass)
.findFirst()
.orElseThrow(() -> new BisqException("No button matching %s found", viewClass))
.setSelected(true);
});
VBox splashScreen = createSplashScreen();
@ -255,14 +255,14 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
if (persistedFilesCorrupted.size() > 1 || !persistedFilesCorrupted.get(0).equals("ViewPathAsString")) {
// show warning that some files has been corrupted
new Popup<>()
.warning(Res.get("popup.warning.incompatibleDB",
persistedFilesCorrupted.toString(),
model.getAppDateDir()))
.useShutDownButton()
.show();
.warning(Res.get("popup.warning.incompatibleDB",
persistedFilesCorrupted.toString(),
model.getAppDateDir()))
.useShutDownButton()
.show();
} else {
log.debug("We detected incompatible data base file for Navigation. That is a minor issue happening with refactoring of UI classes " +
"and we don't display a warning popup to the user.");
"and we don't display a warning popup to the user.");
}
}
@ -333,15 +333,15 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
btcAverageIconButton.visibleProperty().bind(model.isFiatCurrencyPriceFeedSelected);
btcAverageIconButton.managedProperty().bind(model.isFiatCurrencyPriceFeedSelected);
btcAverageIconButton.setOnMouseEntered(e -> {
String res = Res.get("mainView.marketPrice.tooltip",
"https://bitcoinaverage.com",
"",
formatter.formatTime(model.priceFeedService.getLastRequestTimeStampBtcAverage()),
model.priceFeedService.getProviderNodeAddress());
btcAverageIconButton.setTooltip(
new Tooltip(res)
);
}
String res = Res.get("mainView.marketPrice.tooltip",
"https://bitcoinaverage.com",
"",
formatter.formatTime(model.priceFeedService.getLastRequestTimeStampBtcAverage()),
model.priceFeedService.getProviderNodeAddress());
btcAverageIconButton.setTooltip(
new Tooltip(res)
);
}
);
final ImageView poloniexIcon = new ImageView();
@ -359,12 +359,12 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
poloniexIconButton.setOnMouseEntered(e -> {
String altcoinExtra = "\n" + Res.get("mainView.marketPrice.tooltip.altcoinExtra");
String res = Res.get("mainView.marketPrice.tooltip",
"https://poloniex.com",
altcoinExtra,
formatter.formatTime(model.priceFeedService.getLastRequestTimeStampPoloniex()),
model.priceFeedService.getProviderNodeAddress());
"https://poloniex.com",
altcoinExtra,
formatter.formatTime(model.priceFeedService.getLastRequestTimeStampPoloniex()),
model.priceFeedService.getProviderNodeAddress());
poloniexIconButton.setTooltip(
new Tooltip(res)
new Tooltip(res)
);
});

View File

@ -252,7 +252,7 @@ public class MainViewModel implements ViewModel {
this.formatter = formatter;
btcNetworkAsString = Res.get(BisqEnvironment.getBaseCurrencyNetwork().name()) +
(preferences.getUseTorForBitcoinJ() ? (" " + Res.get("mainView.footer.usingTor")) : "");
(preferences.getUseTorForBitcoinJ() ? (" " + Res.get("mainView.footer.usingTor")) : "");
TxIdTextField.setPreferences(preferences);
@ -285,10 +285,10 @@ public class MainViewModel implements ViewModel {
private void readMapsFromResources() {
readMapsFromResourcesBinding = EasyBind.combine(SetupUtils.readPersistableNetworkPayloadMapFromResources(p2PService),
SetupUtils.readEntryMapFromResources(p2PService),
(result1, result2) -> {
return result1 && result2;
});
SetupUtils.readEntryMapFromResources(p2PService),
(result1, result2) -> {
return result1 && result2;
});
readMapsFromResourcesBindingSubscription = readMapsFromResourcesBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue)
startBasicServices();
@ -325,12 +325,12 @@ public class MainViewModel implements ViewModel {
// need to store it to not get garbage collected
allServicesDone = EasyBind.combine(walletInitialized, p2pNetWorkReady,
(a, b) -> {
log.debug("\nwalletInitialized={}\n" +
"p2pNetWorkReady={}",
a, b);
return a && b;
});
(a, b) -> {
log.debug("\nwalletInitialized={}\n" +
"p2pNetWorkReady={}",
a, b);
return a && b;
});
allServicesDone.subscribe((observable, oldValue, newValue) -> {
if (newValue) {
startupTimeout.stop();
@ -355,8 +355,8 @@ public class MainViewModel implements ViewModel {
}
startupTimeoutPopup = new Popup<>();
startupTimeoutPopup.warning(Res.get("popup.warning.startupFailed.timeout", details))
.useShutDownButton()
.show();
.useShutDownButton()
.show();
}
@ -373,22 +373,22 @@ public class MainViewModel implements ViewModel {
BooleanProperty initialP2PNetworkDataReceived = new SimpleBooleanProperty();
p2PNetworkInfoBinding = EasyBind.combine(bootstrapState, bootstrapWarning, p2PService.getNumConnectedPeers(), hiddenServicePublished, initialP2PNetworkDataReceived,
(state, warning, numPeers, hiddenService, dataReceived) -> {
String result = "";
int peers = (int) numPeers;
if (warning != null && peers == 0) {
result = warning;
} else {
String p2pInfo = Res.get("mainView.footer.p2pInfo", numPeers);
if (dataReceived && hiddenService) {
result = p2pInfo;
} else if (peers == 0)
result = state;
else
result = state + " / " + p2pInfo;
}
return result;
});
(state, warning, numPeers, hiddenService, dataReceived) -> {
String result = "";
int peers = (int) numPeers;
if (warning != null && peers == 0) {
result = warning;
} else {
String p2pInfo = Res.get("mainView.footer.p2pInfo", numPeers);
if (dataReceived && hiddenService) {
result = p2pInfo;
} else if (peers == 0)
result = state;
else
result = state + " / " + p2pInfo;
}
return result;
});
p2PNetworkInfoBinding.subscribe((observable, oldValue, newValue) -> {
p2PNetworkInfo.set(newValue);
});
@ -405,7 +405,7 @@ public class MainViewModel implements ViewModel {
// We only check at seed nodes as they are running the latest version
// Other disconnects might be caused by peers running an older version
if (connection.getPeerType() == Connection.PeerType.SEED_NODE &&
closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason);
log.warn("RULE_VIOLATION onDisconnect connection=" + connection);
}
@ -496,99 +496,99 @@ public class MainViewModel implements ViewModel {
ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>();
btcInfoBinding = EasyBind.combine(walletsSetup.downloadPercentageProperty(), walletsSetup.numPeersProperty(), walletServiceException,
(downloadPercentage, numPeers, exception) -> {
String result = "";
if (exception == null) {
double percentage = (double) downloadPercentage;
int peers = (int) numPeers;
btcSyncProgress.set(percentage);
if (percentage == 1) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
btcNetworkAsString);
btcSplashSyncIconId.set("image-connection-synced");
(downloadPercentage, numPeers, exception) -> {
String result = "";
if (exception == null) {
double percentage = (double) downloadPercentage;
int peers = (int) numPeers;
btcSyncProgress.set(percentage);
if (percentage == 1) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
btcNetworkAsString);
btcSplashSyncIconId.set("image-connection-synced");
if (allBasicServicesInitialized)
checkForLockedUpFunds();
} else if (percentage > 0.0) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
btcNetworkAsString + ": " + formatter.formatToPercentWithSymbol(percentage));
} else {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.connectingTo"),
btcNetworkAsString);
}
} else {
result = Res.get("mainView.footer.btcInfo",
numBtcPeers,
Res.get("mainView.footer.btcInfo.connectionFailed"),
btcNetworkAsString);
log.error(exception.getMessage());
if (exception instanceof TimeoutException) {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.timeout"));
} else if (exception.getCause() instanceof BlockStoreException) {
if (exception.getCause().getCause() instanceof ChainFileLockedException) {
new Popup<>().warning(Res.get("popup.warning.startupFailed.twoInstances"))
.useShutDownButton()
.show();
if (allBasicServicesInitialized)
checkForLockedUpFunds();
} else if (percentage > 0.0) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
btcNetworkAsString + ": " + formatter.formatToPercentWithSymbol(percentage));
} else {
new Popup<>().warning(Res.get("error.spvFileCorrupted",
exception.getMessage()))
.actionButtonText(Res.get("settings.net.reSyncSPVChainButton"))
.onAction(() -> {
if (walletsSetup.reSyncSPVChain())
new Popup<>().feedback(Res.get("settings.net.reSyncSPVSuccess"))
.useShutDownButton().show();
else
new Popup<>().error(Res.get("settings.net.reSyncSPVFailed")).show();
})
.show();
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.connectingTo"),
btcNetworkAsString);
}
} else {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString()));
result = Res.get("mainView.footer.btcInfo",
numBtcPeers,
Res.get("mainView.footer.btcInfo.connectionFailed"),
btcNetworkAsString);
log.error(exception.getMessage());
if (exception instanceof TimeoutException) {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.timeout"));
} else if (exception.getCause() instanceof BlockStoreException) {
if (exception.getCause().getCause() instanceof ChainFileLockedException) {
new Popup<>().warning(Res.get("popup.warning.startupFailed.twoInstances"))
.useShutDownButton()
.show();
} else {
new Popup<>().warning(Res.get("error.spvFileCorrupted",
exception.getMessage()))
.actionButtonText(Res.get("settings.net.reSyncSPVChainButton"))
.onAction(() -> {
if (walletsSetup.reSyncSPVChain())
new Popup<>().feedback(Res.get("settings.net.reSyncSPVSuccess"))
.useShutDownButton().show();
else
new Popup<>().error(Res.get("settings.net.reSyncSPVFailed")).show();
})
.show();
}
} else {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString()));
}
}
}
return result;
return result;
});
});
btcInfoBinding.subscribe((observable, oldValue, newValue) -> {
btcInfo.set(newValue);
});
walletsSetup.initialize(null,
() -> {
log.debug("walletsSetup.onInitialized");
numBtcPeers = walletsSetup.numPeersProperty().get();
() -> {
log.debug("walletsSetup.onInitialized");
numBtcPeers = walletsSetup.numPeersProperty().get();
// We only check one as we apply encryption to all or none
if (walletsManager.areWalletsEncrypted()) {
if (p2pNetWorkReady.get())
splashP2PNetworkAnimationVisible.set(false);
// We only check one as we apply encryption to all or none
if (walletsManager.areWalletsEncrypted()) {
if (p2pNetWorkReady.get())
splashP2PNetworkAnimationVisible.set(false);
walletPasswordWindow
.onAesKey(aesKey -> {
walletsManager.setAesKey(aesKey);
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
} else {
walletInitialized.set(true);
}
})
.hideCloseButton()
.show();
} else {
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
walletPasswordWindow
.onAesKey(aesKey -> {
walletsManager.setAesKey(aesKey);
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
} else {
walletInitialized.set(true);
}
})
.hideCloseButton()
.show();
} else {
walletInitialized.set(true);
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
} else {
walletInitialized.set(true);
}
}
}
},
walletServiceException::set);
},
walletServiceException::set);
}
private void onBasicServicesInitialized() {
@ -618,8 +618,8 @@ public class MainViewModel implements ViewModel {
applyTradePeriodState();
});
tradeManager.setTakeOfferRequestErrorMessageHandler(errorMessage -> new Popup<>()
.warning(Res.get("popup.error.takeOfferRequestFailed", errorMessage))
.show());
.warning(Res.get("popup.error.takeOfferRequestFailed", errorMessage))
.show());
// walletService
btcWalletService.addBalanceListener(new BalanceListener() {
@ -681,9 +681,9 @@ public class MainViewModel implements ViewModel {
user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
if (!walletsManager.areWalletsEncrypted() && preferences.showAgain(key) && change.wasAdded()) {
new Popup<>().headLine(Res.get("popup.securityRecommendation.headline"))
.information(Res.get("popup.securityRecommendation.msg"))
.dontShowAgainId(key)
.show();
.information(Res.get("popup.securityRecommendation.msg"))
.dontShowAgainId(key)
.show();
}
});
@ -712,9 +712,9 @@ public class MainViewModel implements ViewModel {
firstPopup.hide();
preferences.setResyncSpvRequested(false);
new Popup<>().information(Res.get("settings.net.reSyncSPVAfterRestartCompleted"))
.hideCloseButton()
.useShutDownButton()
.show();
.hideCloseButton()
.useShutDownButton()
.show();
}
private void checkIfLocalHostNodeIsRunning() {
@ -726,7 +726,7 @@ public class MainViewModel implements ViewModel {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000);
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000);
log.info("Localhost peer detected.");
UserThread.execute(() -> {
bisqEnvironment.setBitcoinLocalhostNodeRunning(true);
@ -764,11 +764,11 @@ public class MainViewModel implements ViewModel {
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.getNetworkEnvelope() instanceof Ping &&
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
log.debug("Crypto test succeeded");
if (Security.getProvider("BC") != null) {
@ -784,9 +784,9 @@ public class MainViewModel implements ViewModel {
String msg = Res.get("popup.warning.cryptoTestFailed", e.getMessage());
log.error(msg);
UserThread.execute(() -> new Popup<>().warning(msg)
.useShutDownButton()
.useReportBugButton()
.show());
.useShutDownButton()
.useReportBugButton()
.show());
}
}
};
@ -795,20 +795,20 @@ public class MainViewModel implements ViewModel {
private void checkIfOpenOffersMatchTradeProtocolVersion() {
List<OpenOffer> outDatedOffers = openOfferManager.getObservableList()
.stream()
.filter(e -> e.getOffer().getProtocolVersion() != Version.TRADE_PROTOCOL_VERSION)
.collect(Collectors.toList());
.stream()
.filter(e -> e.getOffer().getProtocolVersion() != Version.TRADE_PROTOCOL_VERSION)
.collect(Collectors.toList());
if (!outDatedOffers.isEmpty()) {
String offers = outDatedOffers.stream()
.map(e -> e.getId() + "\n")
.collect(Collectors.toList()).toString()
.replace("[", "").replace("]", "");
.map(e -> e.getId() + "\n")
.collect(Collectors.toList()).toString()
.replace("[", "").replace("]", "");
new Popup<>()
.warning(Res.get("popup.warning.oldOffers.msg", offers))
.actionButtonText(Res.get("popup.warning.oldOffers.buttonText"))
.onAction(() -> openOfferManager.removeOpenOffers(outDatedOffers, null))
.useShutDownButton()
.show();
.warning(Res.get("popup.warning.oldOffers.msg", offers))
.actionButtonText(Res.get("popup.warning.oldOffers.buttonText"))
.onAction(() -> openOfferManager.removeOpenOffers(outDatedOffers, null))
.useShutDownButton()
.show();
}
}
@ -870,9 +870,9 @@ public class MainViewModel implements ViewModel {
if (DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup<>().warning(Res.get("popup.warning.tradePeriod.halfReached",
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
}
break;
case TRADE_PERIOD_OVER:
@ -880,9 +880,9 @@ public class MainViewModel implements ViewModel {
if (DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup<>().warning(Res.get("popup.warning.tradePeriod.ended",
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
}
break;
}
@ -949,11 +949,11 @@ public class MainViewModel implements ViewModel {
private void setupMarketPriceFeed() {
priceFeedService.requestPriceFeed(price -> marketPrice.set(formatter.formatMarketPrice(price, priceFeedService.getCurrencyCode())),
(errorMessage, throwable) -> marketPrice.set(Res.get("shared.na")));
(errorMessage, throwable) -> marketPrice.set(Res.get("shared.na")));
marketPriceBinding = EasyBind.combine(
marketPriceCurrencyCode, marketPrice,
(currencyCode, price) -> formatter.getCurrencyPair(currencyCode) + ": " + price);
marketPriceCurrencyCode, marketPrice,
(currencyCode, price) -> formatter.getCurrencyPair(currencyCode) + ": " + price);
marketPriceBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(oldValue)) {
@ -1009,8 +1009,8 @@ public class MainViewModel implements ViewModel {
item.setDisplayString(formatter.getCurrencyPair(currencyCode) + ": " + priceString);
final String code = item.currencyCode;
if (selectedPriceFeedComboBoxItemProperty.get()!=null&&
selectedPriceFeedComboBoxItemProperty.get().currencyCode.equals(code)) {
if (selectedPriceFeedComboBoxItemProperty.get() != null &&
selectedPriceFeedComboBoxItemProperty.get().currencyCode.equals(code)) {
isFiatCurrencyPriceFeedSelected.set(CurrencyUtil.isFiatCurrency(code) && CurrencyUtil.getFiatCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice());
isCryptoCurrencyPriceFeedSelected.set(CurrencyUtil.isCryptoCurrency(code) && CurrencyUtil.getCryptoCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice());
isExternallyProvidedPrice.set(item.isExternallyProvidedPrice());
@ -1027,26 +1027,26 @@ public class MainViewModel implements ViewModel {
selectedPriceFeedComboBoxItemProperty.set(itemOptional.get());
else
findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode())
.ifPresent(selectedPriceFeedComboBoxItemProperty::set);
.ifPresent(selectedPriceFeedComboBoxItemProperty::set);
priceFeedService.setCurrencyCode(item.currencyCode);
} else {
findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode())
.ifPresent(selectedPriceFeedComboBoxItemProperty::set);
.ifPresent(selectedPriceFeedComboBoxItemProperty::set);
}
}
private Optional<PriceFeedComboBoxItem> findPriceFeedComboBoxItem(String currencyCode) {
return priceFeedComboBoxItems.stream()
.filter(item -> item.currencyCode.equals(currencyCode))
.findAny();
.filter(item -> item.currencyCode.equals(currencyCode))
.findAny();
}
private void fillPriceFeedComboBoxItems() {
List<PriceFeedComboBoxItem> currencyItems = preferences.getTradeCurrenciesAsObservable()
.stream()
.map(tradeCurrency -> new PriceFeedComboBoxItem(tradeCurrency.getCode()))
.collect(Collectors.toList());
.stream()
.map(tradeCurrency -> new PriceFeedComboBoxItem(tradeCurrency.getCode()))
.collect(Collectors.toList());
priceFeedComboBoxItems.setAll(currencyItems);
}
@ -1065,20 +1065,20 @@ public class MainViewModel implements ViewModel {
private void displayPrivateNotification(PrivateNotificationPayload privateNotification) {
new Popup<>().headLine(Res.get("popup.privateNotification.headline"))
.attention(privateNotification.getMessage())
.setHeadlineStyle("-fx-text-fill: -bs-error-red; -fx-font-weight: bold; -fx-font-size: 16;")
.onClose(privateNotificationManager::removePrivateNotification)
.useIUnderstandButton()
.show();
.attention(privateNotification.getMessage())
.setHeadlineStyle("-fx-text-fill: -bs-error-red; -fx-font-weight: bold; -fx-font-size: 16;")
.onClose(privateNotificationManager::removePrivateNotification)
.useIUnderstandButton()
.show();
}
private void swapPendingOfferFundingEntries() {
tradeManager.getAddressEntriesForAvailableBalanceStream()
.filter(addressEntry -> addressEntry.getOfferId() != null)
.forEach(addressEntry -> {
log.debug("swapPendingOfferFundingEntries, offerId={}, OFFER_FUNDING", addressEntry.getOfferId());
btcWalletService.swapTradeEntryToAvailableEntry(addressEntry.getOfferId(), AddressEntry.Context.OFFER_FUNDING);
});
.filter(addressEntry -> addressEntry.getOfferId() != null)
.forEach(addressEntry -> {
log.debug("swapPendingOfferFundingEntries, offerId={}, OFFER_FUNDING", addressEntry.getOfferId());
btcWalletService.swapTradeEntryToAvailableEntry(addressEntry.getOfferId(), AddressEntry.Context.OFFER_FUNDING);
});
}
private void updateBalance() {
@ -1093,8 +1093,8 @@ public class MainViewModel implements ViewModel {
private void updateAvailableBalance() {
Coin totalAvailableBalance = Coin.valueOf(tradeManager.getAddressEntriesForAvailableBalanceStream()
.mapToLong(addressEntry -> btcWalletService.getBalanceForAddress(addressEntry.getAddress()).getValue())
.sum());
.mapToLong(addressEntry -> btcWalletService.getBalanceForAddress(addressEntry.getAddress()).getValue())
.sum());
String value = formatter.formatCoinWithCode(totalAvailableBalance);
// If we get full precision the BTC postfix breaks layout so we omit it
if (value.length() > 11)
@ -1104,18 +1104,18 @@ public class MainViewModel implements ViewModel {
private void updateReservedBalance() {
Coin sum = Coin.valueOf(openOfferManager.getObservableList().stream()
.map(openOffer -> {
final Optional<AddressEntry> addressEntryOptional = btcWalletService.getAddressEntry(openOffer.getId(), AddressEntry.Context.RESERVED_FOR_TRADE);
if (addressEntryOptional.isPresent()) {
Address address = addressEntryOptional.get().getAddress();
return btcWalletService.getBalanceForAddress(address);
} else {
return null;
}
})
.filter(e -> e != null)
.mapToLong(Coin::getValue)
.sum());
.map(openOffer -> {
final Optional<AddressEntry> addressEntryOptional = btcWalletService.getAddressEntry(openOffer.getId(), AddressEntry.Context.RESERVED_FOR_TRADE);
if (addressEntryOptional.isPresent()) {
Address address = addressEntryOptional.get().getAddress();
return btcWalletService.getBalanceForAddress(address);
} else {
return null;
}
})
.filter(e -> e != null)
.mapToLong(Coin::getValue)
.sum());
reservedBalance.set(formatter.formatCoinWithCode(sum));
}
@ -1124,42 +1124,42 @@ public class MainViewModel implements ViewModel {
Stream<Trade> lockedTrades = Stream.concat(closedTradableManager.getLockedTradesStream(), failedTradesManager.getLockedTradesStream());
lockedTrades = Stream.concat(lockedTrades, tradeManager.getLockedTradesStream());
Coin sum = Coin.valueOf(lockedTrades
.mapToLong(trade -> {
final Optional<AddressEntry> addressEntryOptional = btcWalletService.getAddressEntry(trade.getId(), AddressEntry.Context.MULTI_SIG);
if (addressEntryOptional.isPresent())
return addressEntryOptional.get().getCoinLockedInMultiSig().getValue();
else
return 0;
})
.sum());
.mapToLong(trade -> {
final Optional<AddressEntry> addressEntryOptional = btcWalletService.getAddressEntry(trade.getId(), AddressEntry.Context.MULTI_SIG);
if (addressEntryOptional.isPresent())
return addressEntryOptional.get().getCoinLockedInMultiSig().getValue();
else
return 0;
})
.sum());
lockedBalance.set(formatter.formatCoinWithCode(sum));
}
private void checkForLockedUpFunds() {
Set<String> tradesIdSet = tradeManager.getLockedTradesStream()
.filter(Trade::hasFailed)
.map(Trade::getId)
.collect(Collectors.toSet());
.filter(Trade::hasFailed)
.map(Trade::getId)
.collect(Collectors.toSet());
tradesIdSet.addAll(failedTradesManager.getLockedTradesStream()
.map(Trade::getId)
.collect(Collectors.toSet()));
.map(Trade::getId)
.collect(Collectors.toSet()));
tradesIdSet.addAll(closedTradableManager.getLockedTradesStream()
.map(e -> {
log.warn("We found a closed trade with locked up funds. " +
"That should never happen. trade ID=" + e.getId());
return e.getId();
})
.collect(Collectors.toSet()));
.map(e -> {
log.warn("We found a closed trade with locked up funds. " +
"That should never happen. trade ID=" + e.getId());
return e.getId();
})
.collect(Collectors.toSet()));
btcWalletService.getAddressEntriesForTrade().stream()
.filter(e -> tradesIdSet.contains(e.getOfferId()) && e.getContext() == AddressEntry.Context.MULTI_SIG)
.forEach(e -> {
final Coin balance = e.getCoinLockedInMultiSig();
final String message = Res.get("popup.warning.lockedUpFunds",
formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId());
log.warn(message);
new Popup<>().warning(message).show();
});
.filter(e -> tradesIdSet.contains(e.getOfferId()) && e.getContext() == AddressEntry.Context.MULTI_SIG)
.forEach(e -> {
final Coin balance = e.getCoinLockedInMultiSig();
final String message = Res.get("popup.warning.lockedUpFunds",
formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId());
log.warn(message);
new Popup<>().warning(message).show();
});
}
@ -1176,20 +1176,20 @@ public class MainViewModel implements ViewModel {
addedList.stream().forEach(dispute -> {
String id = dispute.getId();
Subscription disputeStateSubscription = EasyBind.subscribe(dispute.isClosedProperty(),
isClosed -> {
// We get event before list gets updated, so we execute on next frame
UserThread.execute(() -> {
int openDisputes = disputeManager.getDisputesAsObservableList().stream()
.filter(e -> !e.isClosed())
.collect(Collectors.toList()).size();
if (openDisputes > 0)
numOpenDisputesAsString.set(String.valueOf(openDisputes));
if (openDisputes > 9)
numOpenDisputesAsString.set("");
isClosed -> {
// We get event before list gets updated, so we execute on next frame
UserThread.execute(() -> {
int openDisputes = disputeManager.getDisputesAsObservableList().stream()
.filter(e -> !e.isClosed())
.collect(Collectors.toList()).size();
if (openDisputes > 0)
numOpenDisputesAsString.set(String.valueOf(openDisputes));
if (openDisputes > 9)
numOpenDisputesAsString.set("");
showOpenDisputesNotification.set(openDisputes > 0);
showOpenDisputesNotification.set(openDisputes > 0);
});
});
});
disputeIsClosedSubscriptionsMap.put(id, disputeStateSubscription);
});
}
@ -1207,21 +1207,21 @@ public class MainViewModel implements ViewModel {
private void removeOffersWithoutAccountAgeWitness() {
if (new Date().after(AccountAgeWitnessService.FULL_ACTIVATION)) {
openOfferManager.getObservableList().stream()
.filter(e -> CurrencyUtil.isFiatCurrency(e.getOffer().getCurrencyCode()))
.filter(e -> !e.getOffer().getAccountAgeWitnessHashAsHex().isPresent())
.forEach(e -> {
new Popup<>().warning(Res.get("popup.warning.offerWithoutAccountAgeWitness", e.getId()))
.actionButtonText(Res.get("popup.warning.offerWithoutAccountAgeWitness.confirm"))
.onAction(() -> {
openOfferManager.removeOffer(e.getOffer(),
() -> {
log.info("Offer with ID {} is removed", e.getId());
},
log::error);
})
.hideCloseButton()
.show();
});
.filter(e -> CurrencyUtil.isFiatCurrency(e.getOffer().getCurrencyCode()))
.filter(e -> !e.getOffer().getAccountAgeWitnessHashAsHex().isPresent())
.forEach(e -> {
new Popup<>().warning(Res.get("popup.warning.offerWithoutAccountAgeWitness", e.getId()))
.actionButtonText(Res.get("popup.warning.offerWithoutAccountAgeWitness.confirm"))
.onAction(() -> {
openOfferManager.removeOffer(e.getOffer(),
() -> {
log.info("Offer with ID {} is removed", e.getId());
},
log::error);
})
.hideCloseButton()
.show();
});
}
}

View File

@ -70,127 +70,127 @@ public class DebugView extends InitializableView<GridPane, Void> {
addGroup("OfferAvailabilityProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
SendOfferAvailabilityRequest.class,
ProcessOfferAvailabilityResponse.class)
SendOfferAvailabilityRequest.class,
ProcessOfferAvailabilityResponse.class)
));
addGroup("PlaceOfferProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
ValidateOffer.class,
CreateMakerFeeTx.class,
AddOfferToRemoteOfferBook.class,
BroadcastMakerFeeTx.class)
ValidateOffer.class,
CreateMakerFeeTx.class,
AddOfferToRemoteOfferBook.class,
BroadcastMakerFeeTx.class)
));
addGroup("BuyerAsMakerProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
BuyerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class,
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
BuyerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class,
MakerProcessDepositTxPublishedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerPublishTradeStatistics.class,
MakerProcessDepositTxPublishedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerPublishTradeStatistics.class,
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
BuyerAsMakerSignPayoutTx.class,
BuyerSendCounterCurrencyTransferStartedMessage.class,
BuyerSetupPayoutTxListener.class)
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
BuyerAsMakerSignPayoutTx.class,
BuyerSendCounterCurrencyTransferStartedMessage.class,
BuyerSetupPayoutTxListener.class)
));
addGroup("SellerAsTakerProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerSelectArbitrator.class,
TakerSelectMediator.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
SellerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerSelectArbitrator.class,
TakerSelectMediator.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
SellerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class,
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
SellerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class,
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
SellerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class,
SellerProcessCounterCurrencyTransferStartedMessage.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
SellerProcessCounterCurrencyTransferStartedMessage.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class)
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class)
));
addGroup("BuyerAsTakerProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
TakerSelectArbitrator.class,
TakerSelectMediator.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
BuyerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class,
TakerSelectArbitrator.class,
TakerSelectMediator.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
CreateTakerFeeTx.class,
TakerPublishTakerFeeTx.class,
BuyerAsTakerCreatesDepositTxInputs.class,
TakerSendPayDepositRequest.class,
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
BuyerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class,
TakerProcessPublishDepositTxRequest.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
TakerVerifyAndSignContract.class,
BuyerAsTakerSignAndPublishDepositTx.class,
TakerSendDepositTxPublishedMessage.class,
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
BuyerAsMakerSignPayoutTx.class,
BuyerSendCounterCurrencyTransferStartedMessage.class,
BuyerSetupPayoutTxListener.class)
CheckIfPeerIsBanned.class,
TakerVerifyMakerAccount.class,
TakerVerifyMakerFeePayment.class,
BuyerAsMakerSignPayoutTx.class,
BuyerSendCounterCurrencyTransferStartedMessage.class,
BuyerSetupPayoutTxListener.class)
));
addGroup("SellerAsMakerProtocol: ",
FXCollections.observableArrayList(Arrays.asList(
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
SellerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class,
MakerProcessPayDepositRequest.class,
CheckIfPeerIsBanned.class,
MakerVerifyArbitratorSelection.class,
MakerVerifyMediatorSelection.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerCreateAndSignContract.class,
SellerAsMakerCreatesAndSignsDepositTx.class,
MakerSetupDepositTxListener.class,
MakerSendPublishDepositTxRequest.class,
MakerProcessDepositTxPublishedMessage.class,
MakerPublishTradeStatistics.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
MakerProcessDepositTxPublishedMessage.class,
MakerPublishTradeStatistics.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerProcessCounterCurrencyTransferStartedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerProcessCounterCurrencyTransferStartedMessage.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class)
CheckIfPeerIsBanned.class,
MakerVerifyTakerAccount.class,
MakerVerifyTakerFeePayment.class,
SellerSignAndFinalizePayoutTx.class,
SellerBroadcastPayoutTx.class,
SellerSendPayoutTxPublishedMessage.class)
));
}

View File

@ -100,9 +100,9 @@ public class Candle extends Group {
style = "empty";
highLowLine.getStyleClass().setAll("candlestick-line", seriesStyleClass, dataStyleClass,
style);
style);
bar.getStyleClass().setAll("candlestick-bar", seriesStyleClass, dataStyleClass,
style);
style);
}
}
}

View File

@ -146,11 +146,11 @@ public class BuyerStep2View extends TradeStepView {
PaymentAccountPayload paymentAccountPayload = model.dataModel.getSellersPaymentAccountPayload();
String paymentMethodId = paymentAccountPayload != null ? paymentAccountPayload.getPaymentMethodId() : "";
TitledGroupBg accountTitledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 1,
Res.get("portfolio.pending.step2_buyer.startPaymentUsing", Res.get(paymentMethodId)),
Layout.GROUP_DISTANCE);
Res.get("portfolio.pending.step2_buyer.startPaymentUsing", Res.get(paymentMethodId)),
Layout.GROUP_DISTANCE);
TextFieldWithCopyIcon field = addLabelTextFieldWithCopyIcon(gridPane, gridRow, Res.get("portfolio.pending.step2_buyer.amountToTransfer"),
model.getFiatVolume(),
Layout.FIRST_ROW_AND_GROUP_DISTANCE).second;
model.getFiatVolume(),
Layout.FIRST_ROW_AND_GROUP_DISTANCE).second;
field.setCopyWithoutCurrencyPostFix(true);
switch (paymentMethodId) {
@ -198,7 +198,7 @@ public class BuyerStep2View extends TradeStepView {
break;
case PaymentMethod.BLOCK_CHAINS_ID:
String labelTitle = Res.get("portfolio.pending.step2_buyer.sellersAddress",
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode()));
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode()));
gridRow = CryptoCurrencyForm.addFormForBuyer(gridPane, gridRow, paymentAccountPayload, labelTitle);
break;
default:
@ -207,12 +207,12 @@ public class BuyerStep2View extends TradeStepView {
if (!(paymentAccountPayload instanceof CryptoCurrencyAccountPayload))
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow,
Res.getWithCol("shared.reasonForPayment"), model.dataModel.getReference());
Res.getWithCol("shared.reasonForPayment"), model.dataModel.getReference());
GridPane.setRowSpan(accountTitledGroupBg, gridRow - 3);
Tuple3<Button, BusyAnimation, Label> tuple3 = addButtonBusyAnimationLabelAfterGroup(gridPane, ++gridRow,
Res.get("portfolio.pending.step2_buyer.paymentStarted"));
Res.get("portfolio.pending.step2_buyer.paymentStarted"));
confirmButton = tuple3.first;
confirmButton.setOnAction(e -> onPaymentStarted());
busyAnimation = tuple3.second;
@ -228,8 +228,8 @@ public class BuyerStep2View extends TradeStepView {
protected String getWarningText() {
setWarningHeadline();
return Res.get("portfolio.pending.step2_buyer.warn",
model.dataModel.getCurrencyCode(),
model.getDateForOpenDispute());
model.dataModel.getCurrencyCode(),
model.getDateForOpenDispute());
}
@ -262,12 +262,12 @@ public class BuyerStep2View extends TradeStepView {
if (!DevEnv.DEV_MODE && DontShowAgainLookup.showAgain(key)) {
Popup popup = new Popup<>();
popup.headLine(Res.get("portfolio.pending.step2_buyer.paperReceipt.headline"))
.feedback(Res.get("portfolio.pending.step2_buyer.paperReceipt.msg"))
.onAction(this::showConfirmPaymentStartedPopup)
.closeButtonText(Res.get("shared.no"))
.onClose(popup::hide)
.dontShowAgainId(key)
.show();
.feedback(Res.get("portfolio.pending.step2_buyer.paperReceipt.msg"))
.onAction(this::showConfirmPaymentStartedPopup)
.closeButtonText(Res.get("shared.no"))
.onClose(popup::hide)
.dontShowAgainId(key)
.show();
} else {
showConfirmPaymentStartedPopup();
}
@ -287,15 +287,15 @@ public class BuyerStep2View extends TradeStepView {
if (!DevEnv.DEV_MODE && DontShowAgainLookup.showAgain(key)) {
Popup popup = new Popup<>();
popup.headLine(Res.get("portfolio.pending.step2_buyer.confirmStart.headline"))
.confirmation(Res.get("portfolio.pending.step2_buyer.confirmStart.msg",
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode())))
.width(700)
.actionButtonText(Res.get("portfolio.pending.step2_buyer.confirmStart.yes"))
.onAction(this::confirmPaymentStarted)
.closeButtonText(Res.get("shared.no"))
.onClose(popup::hide)
.dontShowAgainId(key)
.show();
.confirmation(Res.get("portfolio.pending.step2_buyer.confirmStart.msg",
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode())))
.width(700)
.actionButtonText(Res.get("portfolio.pending.step2_buyer.confirmStart.yes"))
.onAction(this::confirmPaymentStarted)
.closeButtonText(Res.get("shared.no"))
.onClose(popup::hide)
.dontShowAgainId(key)
.show();
} else {
confirmPaymentStarted();
}
@ -339,42 +339,42 @@ public class BuyerStep2View extends TradeStepView {
if (paymentAccountPayload instanceof CryptoCurrencyAccountPayload)
//noinspection UnusedAssignment
message += Res.get("portfolio.pending.step2_buyer.altcoin",
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode()),
amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n\n" +
copyPaste;
CurrencyUtil.getNameByCode(trade.getOffer().getCurrencyCode()),
amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n\n" +
copyPaste;
else if (paymentAccountPayload instanceof CashDepositAccountPayload)
//noinspection UnusedAssignment
message += Res.get("portfolio.pending.step2_buyer.cash",
amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn + "\n\n" +
fees + "\n\n" +
Res.get("portfolio.pending.step2_buyer.cash.extra");
amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn + "\n\n" +
fees + "\n\n" +
Res.get("portfolio.pending.step2_buyer.cash.extra");
else if (paymentAccountPayload instanceof USPostalMoneyOrderAccountPayload)
//noinspection UnusedAssignment
message += Res.get("portfolio.pending.step2_buyer.postal", amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn;
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn;
else
//noinspection UnusedAssignment
message += Res.get("portfolio.pending.step2_buyer.bank", amount) +
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn + "\n\n" +
fees;
accountDetails +
paymentDetailsForTradePopup + ".\n" +
copyPaste + "\n\n" +
tradeId + paddedId +
assign +
refTextWarn + "\n\n" +
fees;
//noinspection ConstantConditions,UnusedAssignment
String key = "startPayment" + trade.getId();
@ -382,8 +382,8 @@ public class BuyerStep2View extends TradeStepView {
if (!DevEnv.DEV_MODE && DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup<>().headLine(Res.get("popup.attention.forTradeWithId", id))
.attention(message)
.show();
.attention(message)
.show();
}
}
}

View File

@ -55,8 +55,8 @@ public class BuyerStep3View extends TradeStepView {
protected String getWarningText() {
setInformationHeadline();
String substitute = model.isBlockChainMethod() ?
Res.get("portfolio.pending.step3_buyer.warn.part1a", model.dataModel.getCurrencyCode()) :
Res.get("portfolio.pending.step3_buyer.warn.part1b");
Res.get("portfolio.pending.step3_buyer.warn.part1a", model.dataModel.getCurrencyCode()) :
Res.get("portfolio.pending.step3_buyer.warn.part1b");
return Res.get("portfolio.pending.step3_buyer.warn.part2", substitute, model.getDateForOpenDispute());
}

View File

@ -152,9 +152,9 @@ public class BuyerStep4View extends TradeStepView {
if (!DevEnv.DEV_MODE && DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Notification().headLine(Res.get("notification.tradeCompleted.headline"))
.notification(Res.get("notification.tradeCompleted.msg"))
.autoClose()
.show();
.notification(Res.get("notification.tradeCompleted.msg"))
.autoClose()
.show();
}
}
}
@ -192,22 +192,22 @@ public class BuyerStep4View extends TradeStepView {
double kb = txSize / 1000d;
String recAmount = formatter.formatCoinWithCode(receiverAmount);
new Popup<>().headLine(Res.get("portfolio.pending.step5_buyer.confirmWithdrawal"))
.confirmation(Res.get("shared.sendFundsDetailsWithFee",
formatter.formatCoinWithCode(amount),
fromAddresses,
toAddresses,
formatter.formatCoinWithCode(fee),
feePerByte,
kb,
recAmount))
.actionButtonText(Res.get("shared.yes"))
.onAction(() -> doWithdrawal(amount, fee))
.closeButtonText(Res.get("shared.cancel"))
.onClose(() -> {
useSavingsWalletButton.setDisable(false);
withdrawToExternalWalletButton.setDisable(false);
})
.show();
.confirmation(Res.get("shared.sendFundsDetailsWithFee",
formatter.formatCoinWithCode(amount),
fromAddresses,
toAddresses,
formatter.formatCoinWithCode(fee),
feePerByte,
kb,
recAmount))
.actionButtonText(Res.get("shared.yes"))
.onAction(() -> doWithdrawal(amount, fee))
.closeButtonText(Res.get("shared.cancel"))
.onClose(() -> {
useSavingsWalletButton.setDisable(false);
withdrawToExternalWalletButton.setDisable(false);
})
.show();
} else {
doWithdrawal(amount, fee);
}
@ -243,8 +243,8 @@ public class BuyerStep4View extends TradeStepView {
};
if (model.dataModel.btcWalletService.isEncrypted()) {
UserThread.runAfter(() -> model.dataModel.walletPasswordWindow.onAesKey(aesKey ->
doWithdrawRequest(toAddress, amount, fee, aesKey, resultHandler, faultHandler))
.show(), 300, TimeUnit.MILLISECONDS);
doWithdrawRequest(toAddress, amount, fee, aesKey, resultHandler, faultHandler))
.show(), 300, TimeUnit.MILLISECONDS);
} else
doWithdrawRequest(toAddress, amount, fee, null, resultHandler, faultHandler);
}
@ -253,11 +253,11 @@ public class BuyerStep4View extends TradeStepView {
useSavingsWalletButton.setDisable(true);
withdrawToExternalWalletButton.setDisable(true);
model.dataModel.onWithdrawRequest(toAddress,
amount,
fee,
aesKey,
resultHandler,
faultHandler);
amount,
fee,
aesKey,
resultHandler,
faultHandler);
}
@SuppressWarnings("PointlessBooleanExpression")
@ -266,11 +266,11 @@ public class BuyerStep4View extends TradeStepView {
String key = "tradeCompleteWithdrawCompletedInfo";
//noinspection unchecked
new Popup<>().headLine(Res.get("portfolio.pending.step5_buyer.withdrawalCompleted.headline"))
.feedback(Res.get("portfolio.pending.step5_buyer.withdrawalCompleted.msg"))
.actionButtonTextWithGoTo("navigation.funds.transactions")
.onAction(() -> model.dataModel.navigation.navigateTo(MainView.class, FundsView.class, TransactionsView.class))
.dontShowAgainId(key)
.show();
.feedback(Res.get("portfolio.pending.step5_buyer.withdrawalCompleted.msg"))
.actionButtonTextWithGoTo("navigation.funds.transactions")
.onAction(() -> model.dataModel.navigation.navigateTo(MainView.class, FundsView.class, TransactionsView.class))
.dontShowAgainId(key)
.show();
}
useSavingsWalletButton.setDisable(true);
withdrawToExternalWalletButton.setDisable(true);

View File

@ -55,8 +55,8 @@ public class SellerStep2View extends TradeStepView {
protected String getWarningText() {
setInformationHeadline();
return Res.get("portfolio.pending.step2_seller.warn",
model.dataModel.getCurrencyCode(),
model.getDateForOpenDispute());
model.dataModel.getCurrencyCode(),
model.getDateForOpenDispute());
}
///////////////////////////////////////////////////////////////////////////////////////////

View File

@ -98,9 +98,9 @@ public class GUIUtil {
//noinspection ConstantConditions,ConstantConditions
if (!DevEnv.DEV_MODE && DontShowAgainLookup.showAgain(key) && BisqEnvironment.getBaseCurrencyNetwork().isBitcoin()) {
new Popup<>().attention(Res.get("guiUtil.miningFeeInfo", String.valueOf(GUIUtil.feeService.getTxFeePerByte().value)))
.onClose(runnable::run)
.useIUnderstandButton()
.show();
.onClose(runnable::run)
.useIUnderstandButton()
.show();
DontShowAgainLookup.dontShowAgain(key, true);
} else {
runnable.run();
@ -168,15 +168,15 @@ public class GUIUtil {
if (file != null) {
try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, false), Charsets.UTF_8)) {
CSVWriter<T> headerWriter = new CSVWriterBuilder<T>(outputStreamWriter)
.strategy(CSVStrategy.UK_DEFAULT)
.entryConverter(headerConverter)
.build();
.strategy(CSVStrategy.UK_DEFAULT)
.entryConverter(headerConverter)
.build();
headerWriter.write(emptyItem);
CSVWriter<T> contentWriter = new CSVWriterBuilder<T>(outputStreamWriter)
.strategy(CSVStrategy.UK_DEFAULT)
.entryConverter(contentConverter)
.build();
.strategy(CSVStrategy.UK_DEFAULT)
.entryConverter(contentConverter)
.build();
contentWriter.writeAll(list);
} catch (RuntimeException | IOException e) {
e.printStackTrace();
@ -260,13 +260,13 @@ public class GUIUtil {
});
List<CurrencyListItem> list = tradeCurrencySet.stream()
.filter(e -> CurrencyUtil.isFiatCurrency(e.getCode()))
.map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode())))
.collect(Collectors.toList());
.filter(e -> CurrencyUtil.isFiatCurrency(e.getCode()))
.map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode())))
.collect(Collectors.toList());
List<CurrencyListItem> cryptoList = tradeCurrencySet.stream()
.filter(e -> CurrencyUtil.isCryptoCurrency(e.getCode()))
.map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode())))
.collect(Collectors.toList());
.filter(e -> CurrencyUtil.isCryptoCurrency(e.getCode()))
.map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode())))
.collect(Collectors.toList());
if (preferences.isSortMarketCurrenciesNumerically()) {
list.sort((o1, o2) -> new Integer(o2.numTrades).compareTo(o1.numTrades));
@ -314,14 +314,14 @@ public class GUIUtil {
String key = "warnOpenURLWhenTorEnabled";
if (DontShowAgainLookup.showAgain(key)) {
new Popup<>().information(Res.get("guiUtil.openWebBrowser.warning", target))
.actionButtonText(Res.get("guiUtil.openWebBrowser.doOpen"))
.onAction(() -> {
DontShowAgainLookup.dontShowAgain(key, true);
doOpenWebPage(target);
})
.closeButtonText(Res.get("guiUtil.openWebBrowser.copyUrl"))
.onClose(() -> Utilities.copyToClipboard(target))
.show();
.actionButtonText(Res.get("guiUtil.openWebBrowser.doOpen"))
.onAction(() -> {
DontShowAgainLookup.dontShowAgain(key, true);
doOpenWebPage(target);
})
.closeButtonText(Res.get("guiUtil.openWebBrowser.copyUrl"))
.onClose(() -> Utilities.copyToClipboard(target))
.show();
} else {
doOpenWebPage(target);
}
@ -349,7 +349,7 @@ public class GUIUtil {
public static String getPercentageOfTradeAmount(Coin fee, Coin tradeAmount, BSFormatter formatter) {
return " (" + formatter.formatToPercentWithSymbol((double) fee.value / (double) tradeAmount.value) +
" " + Res.get("guiUtil.ofTradeAmount") + ")";
" " + Res.get("guiUtil.ofTradeAmount") + ")";
}
@SuppressWarnings({"UnusedParameters", "SameReturnValue"})
@ -379,10 +379,10 @@ public class GUIUtil {
String key = "confirmClearXchangeRequirements";
final String currencyName = BisqEnvironment.getBaseCurrencyNetwork().getCurrencyName();
new Popup<>().information(Res.get("payment.clearXchange.info", currencyName, currencyName))
.width(900)
.closeButtonText(Res.get("shared.iConfirm"))
.dontShowAgainId(key)
.show();
.width(900)
.closeButtonText(Res.get("shared.iConfirm"))
.dontShowAgainId(key)
.show();
}
public static void fillAvailableHeight(Pane container, Region component, DoubleProperty initialOccupiedHeight) {
@ -403,8 +403,8 @@ public class GUIUtil {
public static String getBitcoinURI(String address, Coin amount, String label) {
return address != null ?
BitcoinURI.convertToBitcoinURI(Address.fromBase58(BisqEnvironment.getParameters(),
address), amount, label, null) :
"";
BitcoinURI.convertToBitcoinURI(Address.fromBase58(BisqEnvironment.getParameters(),
address), amount, label, null) :
"";
}
}

View File

@ -291,7 +291,7 @@ public final class AltCoinAddressValidator extends InputValidator {
case "ZEN":
try {
// Get the non Base58 form of the address and the bytecode of the first two bytes
byte [] byteAddress = Base58.decodeChecked(input);
byte[] byteAddress = Base58.decodeChecked(input);
int version0 = byteAddress[0] & 0xFF;
int version1 = byteAddress[1] & 0xFF;
@ -302,54 +302,48 @@ public final class AltCoinAddressValidator extends InputValidator {
if (version0 == 0x16 && version1 == 0x9A) {
// Address starts with "zc"
return new ValidationResult(false, Res.get("validation.altcoin.zAddressesNotSupported"));
}
else if (version0 == 0x1C && (version1 == 0xB8 || version1 == 0xBD)) {
} else if (version0 == 0x1C && (version1 == 0xB8 || version1 == 0xBD)) {
// "t1" or "t3" address
return new ValidationResult(true);
}
else if (version0 == 0x20 && (version1 == 0x89 || version1 == 0x96)) {
} else if (version0 == 0x20 && (version1 == 0x89 || version1 == 0x96)) {
// "zn" or "zs" address
return new ValidationResult(true);
}
else {
} else {
// Unknown Type
return new ValidationResult(false);
}
}
catch (AddressFormatException e) {
} catch (AddressFormatException e) {
// Unhandled Exception (probably a checksum error)
return new ValidationResult(false);
}
case "WAC":
try {
Address.fromBase58(WACoinsParams.get(), input);
}
catch (AddressFormatException e) {
} catch (AddressFormatException e) {
return new ValidationResult(false, getErrorMessage(e));
}
return new ValidationResult(true);
case "DCT":
case "DCT":
if (input.matches("^(?=.{5,63}$)([a-z][a-z0-9-]+[a-z0-9])(\\.[a-z][a-z0-9-]+[a-z0-9])*$"))
return new ValidationResult(true);
else
return regexTestFailed;
case "ELLA":
case "ELLA":
// https://github.com/ethereum/web3.js/blob/master/lib/utils/utils.js#L403
if (!input.matches("^(0x)?[0-9a-fA-F]{40}$"))
return regexTestFailed;
else
return new ValidationResult(true);
case "XCN": // https://bitcointalk.org/index.php?topic=1801595
return XCNAddressValidator.ValidateAddress(input);
case "XCN": // https://bitcointalk.org/index.php?topic=1801595
return XCNAddressValidator.ValidateAddress(input);
case "TRC":
try {
Address.fromBase58(TerracoinParams.get(), input);
}
catch (AddressFormatException e) {
} catch (AddressFormatException e) {
return new ValidationResult(false, getErrorMessage(e));
}
return new ValidationResult(true);
case "INXT":
case "INXT":
if (!input.matches("^(0x)?[0-9a-fA-F]{40}$"))
return regexTestFailed;
else

View File

@ -59,12 +59,12 @@ public class BtcValidator extends NumberValidator {
if (result.isValid) {
result = validateIfNotZero(input)
.and(validateIfNotNegative(input))
.and(validateIfNotFractionalBtcValue(input))
.and(validateIfNotExceedsMaxBtcValue(input))
.and(validateIfNotExceedsMaxTradeLimit(input))
.and(validateIfNotUnderMinValue(input))
.and(validateIfAboveDust(input));
.and(validateIfNotNegative(input))
.and(validateIfNotFractionalBtcValue(input))
.and(validateIfNotExceedsMaxBtcValue(input))
.and(validateIfNotExceedsMaxTradeLimit(input))
.and(validateIfNotUnderMinValue(input))
.and(validateIfAboveDust(input));
}
return result;

View File

@ -31,9 +31,9 @@ public class BSFormatterTest {
BSFormatter formatter = new BSFormatter();
Res.setBaseCurrencyCode("BTC");
Res.setBaseCurrencyName("Bitcoin");
assertEquals("0 days",formatter.formatAccountAge(TimeUnit.HOURS.toMillis(23)));
assertEquals("0 days",formatter.formatAccountAge(0));
assertEquals("0 days",formatter.formatAccountAge(-1));
assertEquals("0 days", formatter.formatAccountAge(TimeUnit.HOURS.toMillis(23)));
assertEquals("0 days", formatter.formatAccountAge(0));
assertEquals("0 days", formatter.formatAccountAge(-1));
assertEquals("1 day", formatter.formatAccountAge(TimeUnit.DAYS.toMillis(1)));
assertEquals("2 days", formatter.formatAccountAge(TimeUnit.DAYS.toMillis(2)));
assertEquals("30 days", formatter.formatAccountAge(TimeUnit.DAYS.toMillis(30)));

View File

@ -190,14 +190,14 @@ public class AltCoinAddressValidatorTest {
assertTrue(validator.validate("ud6910c2790bda53bcc53cb131f8fa3bf").isValid);
assertTrue(validator.validate("decent-account123").isValid);
assertTrue(validator.validate("decent.acc-123").isValid);
assertTrue(validator.validate("decent.acc-123").isValid);
assertFalse(validator.validate("my.acc123").isValid);
assertFalse(validator.validate("123decent").isValid);
assertFalse(validator.validate("decent_acc").isValid);
assertFalse(validator.validate("dEcent").isValid);
assertFalse(validator.validate("dct1").isValid);
assertFalse(validator.validate("decent-").isValid);
assertFalse(validator.validate("dct1").isValid);
assertFalse(validator.validate("decent-").isValid);
assertFalse(validator.validate("").isValid);
}
@ -215,7 +215,7 @@ public class AltCoinAddressValidatorTest {
assertFalse(validator.validate("").isValid);
}
@Test
@Test
public void testXCN() {
AltCoinAddressValidator validator = new AltCoinAddressValidator();
validator.setCurrencyCode("XCN");

View File

@ -33,13 +33,13 @@ public class NetworkNodeProvider implements Provider<NetworkNode> {
private final NetworkNode networkNode;
@Inject
public NetworkNodeProvider( NetworkProtoResolver networkProtoResolver,
@Named(NetworkOptionKeys.USE_LOCALHOST_FOR_P2P) boolean useLocalhostForP2P,
@Named(NetworkOptionKeys.PORT_KEY) int port,
@Named(NetworkOptionKeys.TOR_DIR) File torDir) {
public NetworkNodeProvider(NetworkProtoResolver networkProtoResolver,
@Named(NetworkOptionKeys.USE_LOCALHOST_FOR_P2P) boolean useLocalhostForP2P,
@Named(NetworkOptionKeys.PORT_KEY) int port,
@Named(NetworkOptionKeys.TOR_DIR) File torDir) {
networkNode = useLocalhostForP2P ?
new LocalhostNetworkNode(port, networkProtoResolver) :
new TorNetworkNode(port, torDir, networkProtoResolver);
new LocalhostNetworkNode(port, networkProtoResolver) :
new TorNetworkNode(port, torDir, networkProtoResolver);
}
@Override

View File

@ -48,7 +48,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class P2PService implements SetupListener, MessageListener, ConnectionListener, RequestDataManager.Listener,
HashMapChangedListener, PersistedDataHost {
HashMapChangedListener, PersistedDataHost {
private static final Logger log = LoggerFactory.getLogger(P2PService.class);
public static final int MAX_CONNECTIONS_DEFAULT = 12;
@ -99,7 +99,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
SeedNodesRepository seedNodesRepository,
Socks5ProxyProvider socks5ProxyProvider,
EncryptionService encryptionService,
KeyRing keyRing ) {
KeyRing keyRing) {
this.networkNode = networkNode;
this.peerManager = peerManager;
this.p2PDataStorage = p2PDataStorage;
@ -119,8 +119,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
// We need to have both the initial data delivered and the hidden service published
networkReadyBinding = EasyBind.combine(hiddenServicePublished, preliminaryDataReceived,
(hiddenServicePublished, preliminaryDataReceived)
-> hiddenServicePublished && preliminaryDataReceived);
(hiddenServicePublished, preliminaryDataReceived)
-> hiddenServicePublished && preliminaryDataReceived);
networkReadySubscription = networkReadyBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue)
onNetworkReady();
@ -279,7 +279,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
Optional<NodeAddress> seedNodeOfPreliminaryDataRequest = requestDataManager.getNodeAddressOfPreliminaryDataRequest();
checkArgument(seedNodeOfPreliminaryDataRequest.isPresent(),
"seedNodeOfPreliminaryDataRequest must be present");
"seedNodeOfPreliminaryDataRequest must be present");
requestDataManager.requestUpdateData();
}
@ -299,7 +299,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
public void onUpdatedDataReceived() {
Optional<NodeAddress> seedNodeOfPreliminaryDataRequest = requestDataManager.getNodeAddressOfPreliminaryDataRequest();
checkArgument(seedNodeOfPreliminaryDataRequest.isPresent(),
"seedNodeOfPreliminaryDataRequest must be present");
"seedNodeOfPreliminaryDataRequest must be present");
peerExchangeManager.requestReportedPeersFromSeedNodes(seedNodeOfPreliminaryDataRequest.get());
if (!isBootstrapped) {
@ -367,14 +367,14 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
log.debug("Try to decrypt...");
DecryptedMessageWithPubKey decryptedMessageWithPubKey = encryptionService.decryptAndVerify(
prefixedSealedAndSignedMessage.getSealedAndSigned());
prefixedSealedAndSignedMessage.getSealedAndSigned());
log.debug("\n\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n" +
"Decrypted SealedAndSignedMessage:\ndecryptedMsgWithPubKey={}"
+ "\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n", decryptedMessageWithPubKey);
"Decrypted SealedAndSignedMessage:\ndecryptedMsgWithPubKey={}"
+ "\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n", decryptedMessageWithPubKey);
if (connection.getPeersNodeAddressOptional().isPresent())
decryptedDirectMessageListeners.stream().forEach(
e -> e.onDirectMessage(decryptedMessageWithPubKey, connection.getPeersNodeAddressOptional().get()));
e -> e.onDirectMessage(decryptedMessageWithPubKey, connection.getPeersNodeAddressOptional().get()));
else
log.error("peersNodeAddress is not available at onMessage.");
} else {
@ -384,7 +384,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
log.debug(networkEnvelop.toString());
log.debug(e.toString());
log.debug("Decryption of prefixedSealedAndSignedMessage.sealedAndSigned failed. " +
"That is expected if the message is not intended for us.");
"That is expected if the message is not intended for us.");
}
}
}
@ -427,13 +427,13 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
checkNotNull(networkNode.getNodeAddress(), "My node address must not be null at doSendEncryptedDirectMessage");
try {
log.debug("\n\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" +
"Encrypt message:\nmessage={}"
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
"Encrypt message:\nmessage={}"
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = new PrefixedSealedAndSignedMessage(
networkNode.getNodeAddress(),
encryptionService.encryptAndSign(pubKeyRing, message),
peersNodeAddress.getAddressPrefixHash(),
UUID.randomUUID().toString());
networkNode.getNodeAddress(),
encryptionService.encryptAndSign(pubKeyRing, message),
peersNodeAddress.getAddressPrefixHash(),
UUID.randomUUID().toString());
SettableFuture<Connection> future = networkNode.sendMessage(peersNodeAddress, prefixedSealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
@ -471,7 +471,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
if (verifyAddressPrefixHash(prefixedSealedAndSignedMessage)) {
try {
DecryptedMessageWithPubKey decryptedMessageWithPubKey = encryptionService.decryptAndVerify(
prefixedSealedAndSignedMessage.getSealedAndSigned());
prefixedSealedAndSignedMessage.getSealedAndSigned());
if (decryptedMessageWithPubKey.getNetworkEnvelope() instanceof MailboxMessage) {
MailboxMessage mailboxMessage = (MailboxMessage) decryptedMessageWithPubKey.getNetworkEnvelope();
NodeAddress senderNodeAddress = mailboxMessage.getSenderNodeAddress();
@ -479,17 +479,17 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
mailboxMap.put(mailboxMessage.getUid(), protectedMailboxStorageEntry);
log.trace("Decryption of SealedAndSignedMessage succeeded. senderAddress="
+ senderNodeAddress + " / my address=" + getAddress());
+ senderNodeAddress + " / my address=" + getAddress());
decryptedMailboxListeners.stream().forEach(
e -> e.onMailboxMessageAdded(decryptedMessageWithPubKey, senderNodeAddress));
e -> e.onMailboxMessageAdded(decryptedMessageWithPubKey, senderNodeAddress));
} else {
log.warn("tryDecryptMailboxData: Expected MailboxMessage but got other type. " +
"decryptedMsgWithPubKey.message=", decryptedMessageWithPubKey.getNetworkEnvelope());
"decryptedMsgWithPubKey.message=", decryptedMessageWithPubKey.getNetworkEnvelope());
}
} catch (CryptoException e) {
log.debug(e.toString());
log.debug("Decryption of prefixedSealedAndSignedMessage.sealedAndSigned failed. " +
"That is expected if the message is not intended for us.");
"That is expected if the message is not intended for us.");
}
} else {
log.debug("Wrong blurredAddressHash. The message is not intended for us.");
@ -502,23 +502,23 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
SendMailboxMessageListener sendMailboxMessageListener) {
Log.traceCall("message " + message);
checkNotNull(peersNodeAddress,
"PeerAddress must not be null (sendEncryptedMailboxMessage)");
"PeerAddress must not be null (sendEncryptedMailboxMessage)");
checkNotNull(networkNode.getNodeAddress(),
"My node address must not be null at sendEncryptedMailboxMessage");
"My node address must not be null at sendEncryptedMailboxMessage");
checkArgument(!keyRing.getPubKeyRing().equals(peersPubKeyRing),
"We got own keyring instead of that from peer");
"We got own keyring instead of that from peer");
if (isBootstrapped()) {
if (!networkNode.getAllConnections().isEmpty()) {
try {
log.debug("\n\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" +
"Encrypt message:\nmessage={}"
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
"Encrypt message:\nmessage={}"
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = new PrefixedSealedAndSignedMessage(
networkNode.getNodeAddress(),
encryptionService.encryptAndSign(peersPubKeyRing, message),
peersNodeAddress.getAddressPrefixHash(),
UUID.randomUUID().toString());
networkNode.getNodeAddress(),
encryptionService.encryptAndSign(peersPubKeyRing, message),
peersNodeAddress.getAddressPrefixHash(),
UUID.randomUUID().toString());
SettableFuture<Connection> future = networkNode.sendMessage(peersNodeAddress, prefixedSealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
@ -535,10 +535,10 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
log.trace("create MailboxEntry with peerAddress " + peersNodeAddress);
PublicKey receiverStoragePublicKey = peersPubKeyRing.getSignaturePubKey();
addMailboxData(new MailboxStoragePayload(prefixedSealedAndSignedMessage,
keyRing.getSignatureKeyPair().getPublic(),
receiverStoragePublicKey),
receiverStoragePublicKey,
sendMailboxMessageListener);
keyRing.getSignatureKeyPair().getPublic(),
receiverStoragePublicKey),
receiverStoragePublicKey,
sendMailboxMessageListener);
}
});
} catch (CryptoException e) {
@ -548,7 +548,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
}
} else {
sendMailboxMessageListener.onFault("There are no P2P network nodes connected. " +
"Please check your internet connection.");
"Please check your internet connection.");
}
} else {
throw new NetworkNotReadyException();
@ -565,9 +565,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
if (!networkNode.getAllConnections().isEmpty()) {
try {
ProtectedMailboxStorageEntry protectedMailboxStorageEntry = p2PDataStorage.getMailboxDataWithSignedSeqNr(
expirableMailboxStoragePayload,
keyRing.getSignatureKeyPair(),
receiversPublicKey);
expirableMailboxStoragePayload,
keyRing.getSignatureKeyPair(),
receiversPublicKey);
BroadcastHandler.Listener listener = new BroadcastHandler.Listener() {
@Override
@ -579,7 +579,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
// The reason for that check was to separate different callback for different send calls.
// We only want to notify our sendMailboxMessageListener for the calls he is interested in.
if (message instanceof AddDataMessage &&
((AddDataMessage) message).getProtectedStorageEntry().equals(protectedMailboxStorageEntry)) {
((AddDataMessage) message).getProtectedStorageEntry().equals(protectedMailboxStorageEntry)) {
// We delay a bit to give more time for sufficient propagation in the P2P network.
// This should help to avoid situations where a user closes the app too early and the msg
// does not arrive.
@ -597,7 +597,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
@Override
public void onBroadcastCompleted(BroadcastMessage message, int numOfCompletedBroadcasts, int numOfFailedBroadcasts) {
log.info("Broadcast completed: Sent to {} peers (failed: {}). Message = {}",
numOfCompletedBroadcasts, numOfFailedBroadcasts, Utilities.toTruncatedString(message));
numOfCompletedBroadcasts, numOfFailedBroadcasts, Utilities.toTruncatedString(message));
if (numOfCompletedBroadcasts == 0)
sendMailboxMessageListener.onFault("Broadcast completed without any successful broadcast");
}
@ -622,7 +622,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
}
} else {
sendMailboxMessageListener.onFault("There are no P2P network nodes connected. " +
"Please check your internet connection.");
"Please check your internet connection.");
}
} else {
throw new NetworkNotReadyException();
@ -649,12 +649,12 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
MailboxStoragePayload expirableMailboxStoragePayload = (MailboxStoragePayload) mailboxData.getProtectedStoragePayload();
PublicKey receiversPubKey = mailboxData.getReceiversPubKey();
checkArgument(receiversPubKey.equals(keyRing.getSignatureKeyPair().getPublic()),
"receiversPubKey is not matching with our key. That must not happen.");
"receiversPubKey is not matching with our key. That must not happen.");
try {
ProtectedMailboxStorageEntry protectedMailboxStorageEntry = p2PDataStorage.getMailboxDataWithSignedSeqNr(
expirableMailboxStoragePayload,
keyRing.getSignatureKeyPair(),
receiversPubKey);
expirableMailboxStoragePayload,
keyRing.getSignatureKeyPair(),
receiversPubKey);
p2PDataStorage.removeMailboxData(protectedMailboxStorageEntry, networkNode.getNodeAddress(), true);
} catch (CryptoException e) {
log.error("Signing at getDataWithSignedSeqNr failed. That should never happen.");
@ -665,7 +665,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
}
} else {
log.warn("uid for mailbox entry not found in mailboxMap. That should never happen." +
"\n\tuid={}\n\tmailboxMap={}\n\tmailboxMessage={}", uid, mailboxMap, mailboxMessage);
"\n\tuid={}\n\tmailboxMap={}\n\tmailboxMessage={}", uid, mailboxMap, mailboxMessage);
}
} else {
throw new NetworkNotReadyException();
@ -809,7 +809,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
if (networkNode.getNodeAddress() != null) {
byte[] blurredAddressHash = networkNode.getNodeAddress().getAddressPrefixHash();
return blurredAddressHash != null &&
Arrays.equals(blurredAddressHash, prefixedSealedAndSignedMessage.getAddressPrefixHash());
Arrays.equals(blurredAddressHash, prefixedSealedAndSignedMessage.getAddressPrefixHash());
} else {
log.debug("myOnionAddress is null at verifyAddressPrefixHash. That is expected at startup.");
return false;

View File

@ -39,22 +39,22 @@ public final class GetPeersResponse extends NetworkEnvelope implements PeerExcha
@Override
public PB.NetworkEnvelope toProtoNetworkEnvelope() {
return getNetworkEnvelopeBuilder()
.setGetPeersResponse(PB.GetPeersResponse.newBuilder()
.setRequestNonce(requestNonce)
.addAllReportedPeers(reportedPeers.stream()
.map(Peer::toProtoMessage)
.collect(Collectors.toList()))
.addAllSupportedCapabilities(supportedCapabilities))
.build();
.setGetPeersResponse(PB.GetPeersResponse.newBuilder()
.setRequestNonce(requestNonce)
.addAllReportedPeers(reportedPeers.stream()
.map(Peer::toProtoMessage)
.collect(Collectors.toList()))
.addAllSupportedCapabilities(supportedCapabilities))
.build();
}
public static GetPeersResponse fromProto(PB.GetPeersResponse getPeersResponse, int messageVersion) {
HashSet<Peer> reportedPeers = new HashSet<>(
getPeersResponse.getReportedPeersList()
.stream()
.map(peer -> new Peer(new NodeAddress(peer.getNodeAddress().getHostName(),
peer.getNodeAddress().getPort())))
.collect(Collectors.toList()));
getPeersResponse.getReportedPeersList()
.stream()
.map(peer -> new Peer(new NodeAddress(peer.getNodeAddress().getHostName(),
peer.getNodeAddress().getPort())))
.collect(Collectors.toList()));
return new GetPeersResponse(getPeersResponse.getRequestNonce(), reportedPeers, messageVersion);
}
}

View File

@ -184,7 +184,7 @@ public class DummySeedNode {
if (torDir.mkdirs())
log.debug("Created torDir at " + torDir.getAbsolutePath());
// seedNodesRepository.setNodeAddressToExclude(mySeedNodeAddress);
// seedNodesRepository.setNodeAddressToExclude(mySeedNodeAddress);
/* seedNodeP2PService = new P2PService(seedNodesRepository, mySeedNodeAddress.getPort(), maxConnections,
torDir, useLocalhostForP2P, networkId, storageDir, null, null, null, new Clock(), null, null,
null, TestUtils.getNetworkProtoResolver(), TestUtils.getPersistenceProtoResolver());

View File

@ -86,56 +86,56 @@ public class TestUtils {
return seedNode;
}
/* public static P2PService getAndAuthenticateP2PService(int port, EncryptionService encryptionService, KeyRing keyRing,
boolean useLocalhostForP2P, Set<NodeAddress> seedNodes)
throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
SeedNodesRepository seedNodesRepository = new SeedNodesRepository();
if (seedNodes != null && !seedNodes.isEmpty()) {
if (useLocalhostForP2P)
seedNodesRepository.setLocalhostSeedNodeAddresses(seedNodes);
else
seedNodesRepository.setTorSeedNodeAddresses(seedNodes);
}
/* public static P2PService getAndAuthenticateP2PService(int port, EncryptionService encryptionService, KeyRing keyRing,
boolean useLocalhostForP2P, Set<NodeAddress> seedNodes)
throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
SeedNodesRepository seedNodesRepository = new SeedNodesRepository();
if (seedNodes != null && !seedNodes.isEmpty()) {
if (useLocalhostForP2P)
seedNodesRepository.setLocalhostSeedNodeAddresses(seedNodes);
else
seedNodesRepository.setTorSeedNodeAddresses(seedNodes);
}
P2PService p2PService = new P2PService(seedNodesRepository, port, new File("seed_node_" + port), useLocalhostForP2P,
2, P2PService.MAX_CONNECTIONS_DEFAULT, new File("dummy"), null, null, null,
new Clock(), null, encryptionService, keyRing, getNetworkProtoResolver(), getPersistenceProtoResolver());
p2PService.start(new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
}
P2PService p2PService = new P2PService(seedNodesRepository, port, new File("seed_node_" + port), useLocalhostForP2P,
2, P2PService.MAX_CONNECTIONS_DEFAULT, new File("dummy"), null, null, null,
new Clock(), null, encryptionService, keyRing, getNetworkProtoResolver(), getPersistenceProtoResolver());
p2PService.start(new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
}
@Override
public void onNoSeedNodeAvailable() {
}
@Override
public void onNoSeedNodeAvailable() {
}
@Override
public void onNoPeersAvailable() {
}
@Override
public void onNoPeersAvailable() {
}
@Override
public void onTorNodeReady() {
}
@Override
public void onTorNodeReady() {
}
@Override
public void onBootstrapComplete() {
latch.countDown();
}
@Override
public void onBootstrapComplete() {
latch.countDown();
}
@Override
public void onHiddenServicePublished() {
}
@Override
public void onHiddenServicePublished() {
}
@Override
public void onSetupFailed(Throwable throwable) {
}
});
latch.await();
Thread.sleep(2000);
return p2PService;
}
*/
@Override
public void onSetupFailed(Throwable throwable) {
}
});
latch.await();
Thread.sleep(2000);
return p2PService;
}
*/
public static NetworkProtoResolver getNetworkProtoResolver() {
return new NetworkProtoResolver() {
@Override

View File

@ -55,7 +55,7 @@ public class StatisticsMain extends BisqExecutable {
Utilities.removeCryptographyRestrictions();
}
public static void main(String[] args) throws Exception {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("Statistics")