/
Config.java
1045 lines (877 loc) · 43.2 KB
/
Config.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bisq.common.config;
import bisq.common.util.Utilities;
import org.bitcoinj.core.NetworkParameters;
import joptsimple.AbstractOptionSpec;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.HelpFormatter;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.OptionSpecBuilder;
import joptsimple.util.PathConverter;
import joptsimple.util.PathProperties;
import joptsimple.util.RegexMatcher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import ch.qos.logback.classic.Level;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
public class Config {
// option name constants typically used for @Named parameter injection
public static final String APP_NAME = "appName";
private static final String APP_DATA_DIR = "appDataDir";
public static final String BASE_CURRENCY_NETWORK = "baseCurrencyNetwork";
public static final String REFERRAL_ID = "referralId";
public static final String USE_DEV_MODE = "useDevMode";
public static final String TOR_DIR = "torDir";
public static final String STORAGE_DIR = "storageDir";
public static final String KEY_STORAGE_DIR = "keyStorageDir";
public static final String WALLET_DIR = "walletDir";
public static final String USE_DEV_PRIVILEGE_KEYS = "useDevPrivilegeKeys";
public static final String DUMP_STATISTICS = "dumpStatistics";
public static final String IGNORE_DEV_MSG = "ignoreDevMsg";
public static final String PROVIDERS = "providers";
public static final String LOG_LEVEL = "logLevel";
public static final String SEED_NODES = "seedNodes";
public static final String BAN_LIST = "banList";
public static final String NODE_PORT = "nodePort";
public static final String USE_LOCALHOST_FOR_P2P = "useLocalhostForP2P";
public static final String MAX_CONNECTIONS = "maxConnections";
public static final String SOCKS_5_PROXY_BTC_ADDRESS = "socks5ProxyBtcAddress";
public static final String SOCKS_5_PROXY_HTTP_ADDRESS = "socks5ProxyHttpAddress";
public static final String TORRC_FILE = "torrcFile";
public static final String TORRC_OPTIONS = "torrcOptions";
public static final String TOR_CONTROL_PORT = "torControlPort";
public static final String TOR_CONTROL_PASSWORD = "torControlPassword";
public static final String TOR_CONTROL_COOKIE_FILE = "torControlCookieFile";
public static final String TOR_CONTROL_USE_SAFE_COOKIE_AUTH = "torControlUseSafeCookieAuth";
public static final String TOR_STREAM_ISOLATION = "torStreamIsolation";
public static final String IGNORE_LOCAL_BTC_NODE = "ignoreLocalBtcNode";
public static final String BTC_NODES = "btcNodes";
public static final String SOCKS5_DISCOVER_MODE = "socks5DiscoverMode";
public static final String USE_ALL_PROVIDED_NODES = "useAllProvidedNodes";
public static final String USER_AGENT = "userAgent";
public static final String NUM_CONNECTIONS_FOR_BTC = "numConnectionsForBtc";
public static final String RPC_USER = "rpcUser";
public static final String RPC_PASSWORD = "rpcPassword";
public static final String RPC_HOST = "rpcHost";
public static final String RPC_PORT = "rpcPort";
public static final String RPC_BLOCK_NOTIFICATION_PORT = "rpcBlockNotificationPort";
public static final String RPC_BLOCK_NOTIFICATION_HOST = "rpcBlockNotificationHost";
public static final String DUMP_BLOCKCHAIN_DATA = "dumpBlockchainData";
public static final String FULL_DAO_NODE = "fullDaoNode";
public static final String GENESIS_TX_ID = "genesisTxId";
public static final String GENESIS_BLOCK_HEIGHT = "genesisBlockHeight";
public static final String GENESIS_TOTAL_SUPPLY = "genesisTotalSupply";
public static final String DAO_ACTIVATED = "daoActivated";
// default values for certain options
public static final int UNSPECIFIED_PORT = -1;
public static final String DEFAULT_REGTEST_HOST = "localhost";
public static final int DEFAULT_NUM_CONNECTIONS_FOR_BTC = 9; // down from BitcoinJ default of 12
public static final boolean DEFAULT_FULL_DAO_NODE = false;
static final String DEFAULT_CONFIG_FILE_NAME = "bisq.properties";
private static File APP_DATA_DIR_VALUE;
private static BaseCurrencyNetwork BASE_CURRENCY_NETWORK_VALUE = BaseCurrencyNetwork.BTC_MAINNET;
// default data dir properties
private final String defaultAppName;
private final File defaultUserDataDir;
private final File defaultAppDataDir;
private final File defaultConfigFile;
// options supported only in the cli
private final boolean helpRequested;
private final File configFile;
// options supported in the cli and config file
private final String appName;
private final File userDataDir;
private final File appDataDir;
private final int nodePort;
private final List<String> bannedBtcNodes;
private final List<String> bannedPriceRelayNodes;
private final List<String> bannedSeedNodes;
private final BaseCurrencyNetwork baseCurrencyNetwork;
private final NetworkParameters baseCurrencyNetworkParameters;
private final boolean ignoreLocalBtcNode;
private final String bitcoinRegtestHost;
private final boolean daoActivated;
private final String logLevel;
private final String referralId;
private final boolean useDevMode;
private final boolean useDevPrivilegeKeys;
private final boolean dumpStatistics;
private final int maxMemory;
private final boolean ignoreDevMsg;
private final List<String> providers;
private final List<String> seedNodes;
private final List<String> banList;
private final boolean useLocalhostForP2P;
private final int maxConnections;
private final String socks5ProxyBtcAddress;
private final String socks5ProxyHttpAddress;
private final File torrcFile;
private final String torrcOptions;
private final int torControlPort;
private final String torControlPassword;
private final File torControlCookieFile;
private final boolean useTorControlSafeCookieAuth;
private final boolean torStreamIsolation;
private final int msgThrottlePerSec;
private final int msgThrottlePer10Sec;
private final int sendMsgThrottleTrigger;
private final int sendMsgThrottleSleep;
private final String btcNodes;
private final boolean useTorForBtc;
private final boolean useTorForBtcOptionSetExplicitly;
private final String socks5DiscoverMode;
private final boolean useAllProvidedNodes;
private final String userAgent;
private final int numConnectionsForBtc;
private final String rpcUser;
private final String rpcPassword;
private final String rpcHost;
private final int rpcPort;
private final int rpcBlockNotificationPort;
private final String rpcBlockNotificationHost;
private final boolean dumpBlockchainData;
private final boolean fullDaoNode;
private final boolean fullDaoNodeOptionSetExplicitly;
private final String genesisTxId;
private final int genesisBlockHeight;
private final long genesisTotalSupply;
private final File torDir;
private final File walletDir;
private final File storageDir;
private final File keyStorageDir;
private final OptionParser parser = new OptionParser();
public Config(String... args) {
this(tempAppName(), tempUserDataDir(), args);
}
public Config(String defaultAppName, File defaultUserDataDir, String... args) {
this.defaultAppName = defaultAppName;
this.defaultUserDataDir = defaultUserDataDir;
this.defaultAppDataDir = new File(this.defaultUserDataDir, this.defaultAppName);
this.defaultConfigFile = new File(this.defaultAppDataDir, DEFAULT_CONFIG_FILE_NAME);
AbstractOptionSpec<Void> helpOpt =
parser.accepts("help", "Print this help text")
.forHelp();
ArgumentAcceptingOptionSpec<String> configFileOpt =
parser.accepts("configFile", format("Specify configuration file. " +
"Relative paths will be prefixed by %s location.", APP_DATA_DIR))
.withRequiredArg()
.ofType(String.class)
.defaultsTo(DEFAULT_CONFIG_FILE_NAME);
ArgumentAcceptingOptionSpec<File> userDataDirOpt =
parser.accepts("userDataDir", "User data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(this.defaultUserDataDir);
ArgumentAcceptingOptionSpec<String> appNameOpt =
parser.accepts(APP_NAME, "Application name")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(this.defaultAppName);
ArgumentAcceptingOptionSpec<File> appDataDirOpt =
parser.accepts(APP_DATA_DIR, "Application data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultAppDataDir);
ArgumentAcceptingOptionSpec<Integer> nodePortOpt =
parser.accepts(NODE_PORT, "Port to listen on")
.withRequiredArg()
.ofType(Integer.class)
.defaultsTo(9999);
ArgumentAcceptingOptionSpec<String> bannedBtcNodesOpt =
parser.accepts("bannedBtcNodes", "List Bitcoin nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedPriceRelayNodesOpt =
parser.accepts("bannedPriceRelayNodes", "List Bisq price nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedSeedNodesOpt =
parser.accepts("bannedSeedNodes", "List Bisq seed nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
//noinspection rawtypes
ArgumentAcceptingOptionSpec<Enum> baseCurrencyNetworkOpt =
parser.accepts(BASE_CURRENCY_NETWORK, "Base currency network")
.withRequiredArg()
.ofType(BaseCurrencyNetwork.class)
.withValuesConvertedBy(new EnumValueConverter(BaseCurrencyNetwork.class))
.defaultsTo(BaseCurrencyNetwork.BTC_MAINNET);
ArgumentAcceptingOptionSpec<Boolean> ignoreLocalBtcNodeOpt =
parser.accepts(IGNORE_LOCAL_BTC_NODE,
"If set to true a Bitcoin Core node running locally will be ignored")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> bitcoinRegtestHostOpt =
parser.accepts("bitcoinRegtestHost", "Bitcoin Core node when using BTC_REGTEST network")
.withRequiredArg()
.ofType(String.class)
.describedAs("host[:port]")
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> logLevelOpt =
parser.accepts(LOG_LEVEL, "Set logging level")
.withRequiredArg()
.ofType(String.class)
.describedAs("OFF|ALL|ERROR|WARN|INFO|DEBUG|TRACE")
.defaultsTo(Level.INFO.levelStr);
ArgumentAcceptingOptionSpec<String> referralIdOpt =
parser.accepts(REFERRAL_ID, "Optional Referral ID (e.g. for API users or pro market makers)")
.withRequiredArg()
.ofType(String.class)
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> useDevModeOpt =
parser.accepts(USE_DEV_MODE,
"Enables dev mode which is used for convenience for developer testing")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> useDevPrivilegeKeysOpt =
parser.accepts(USE_DEV_PRIVILEGE_KEYS, "If set to true all privileged features requiring a private " +
"key to be enabled are overridden by a dev key pair (This is for developers only!)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> dumpStatisticsOpt =
parser.accepts(DUMP_STATISTICS, "If set to true dump trade statistics to a json file in appDataDir")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Integer> maxMemoryOpt =
parser.accepts("maxMemory", "Max. permitted memory (used only by headless versions)")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(1200);
ArgumentAcceptingOptionSpec<Boolean> ignoreDevMsgOpt =
parser.accepts(IGNORE_DEV_MSG, "If set to true all signed " +
"network_messages from bisq developers are ignored (Global " +
"alert, Version update alert, Filters for offers, nodes or " +
"trading account data)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> providersOpt =
parser.accepts(PROVIDERS, "List custom providers")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> seedNodesOpt =
parser.accepts(SEED_NODES, "Override hard coded seed nodes as comma separated list e.g. " +
"'rxdkppp3vicnbgqt.onion:8002,mfla72c4igh5ta2t.onion:8002'")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> banListOpt =
parser.accepts(BAN_LIST, "Nodes to exclude from network connections.")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<Boolean> useLocalhostForP2POpt =
parser.accepts(USE_LOCALHOST_FOR_P2P, "Use localhost P2P network for development")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Integer> maxConnectionsOpt =
parser.accepts(MAX_CONNECTIONS, "Max. connections a peer will try to keep")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(12);
ArgumentAcceptingOptionSpec<String> socks5ProxyBtcAddressOpt =
parser.accepts(SOCKS_5_PROXY_BTC_ADDRESS, "A proxy address to be used for Bitcoin network.")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> socks5ProxyHttpAddressOpt =
parser.accepts(SOCKS_5_PROXY_HTTP_ADDRESS,
"A proxy address to be used for Http requests (should be non-Tor)")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torrcFileOpt =
parser.accepts(TORRC_FILE, "An existing torrc-file to be sourced for Tor. Note that torrc-entries, " +
"which are critical to Bisq's correct operation, cannot be overwritten.")
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
ArgumentAcceptingOptionSpec<String> torrcOptionsOpt =
parser.accepts(TORRC_OPTIONS, "A list of torrc-entries to amend to Bisq's torrc. Note that " +
"torrc-entries, which are critical to Bisq's flawless operation, cannot be overwritten. " +
"[torrc options line, torrc option, ...]")
.withRequiredArg()
.withValuesConvertedBy(RegexMatcher.regex("^([^\\s,]+\\s[^,]+,?\\s*)+$"))
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> torControlPortOpt =
parser.accepts(TOR_CONTROL_PORT,
"The control port of an already running Tor service to be used by Bisq.")
.availableUnless(TORRC_FILE, TORRC_OPTIONS)
.withRequiredArg()
.ofType(int.class)
.describedAs("port")
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<String> torControlPasswordOpt =
parser.accepts(TOR_CONTROL_PASSWORD, "The password for controlling the already running Tor service.")
.availableIf(TOR_CONTROL_PORT)
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torControlCookieFileOpt =
parser.accepts(TOR_CONTROL_COOKIE_FILE, "The cookie file for authenticating against the already " +
"running Tor service. Use in conjunction with --" + TOR_CONTROL_USE_SAFE_COOKIE_AUTH)
.availableIf(TOR_CONTROL_PORT)
.availableUnless(TOR_CONTROL_PASSWORD)
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
OptionSpecBuilder torControlUseSafeCookieAuthOpt =
parser.accepts(TOR_CONTROL_USE_SAFE_COOKIE_AUTH,
"Use the SafeCookie method when authenticating to the already running Tor service.")
.availableIf(TOR_CONTROL_COOKIE_FILE);
OptionSpecBuilder torStreamIsolationOpt =
parser.accepts(TOR_STREAM_ISOLATION, "Use stream isolation for Tor [experimental!].");
ArgumentAcceptingOptionSpec<Integer> msgThrottlePerSecOpt =
parser.accepts("msgThrottlePerSec", "Message throttle per sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 40MB/sec or 5 mbit/sec
.defaultsTo(200);
ArgumentAcceptingOptionSpec<Integer> msgThrottlePer10SecOpt =
parser.accepts("msgThrottlePer10Sec", "Message throttle per 10 sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 20MB/sec or 2.5 mbit/sec
.defaultsTo(1000);
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleTriggerOpt =
parser.accepts("sendMsgThrottleTrigger", "Time in ms when we trigger a sleep if 2 messages are sent")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(20); // Time in ms when we trigger a sleep if 2 messages are sent
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleSleepOpt =
parser.accepts("sendMsgThrottleSleep", "Pause in ms to sleep if we get too many messages to send")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(50); // Pause in ms to sleep if we get too many messages to send
ArgumentAcceptingOptionSpec<String> btcNodesOpt =
parser.accepts(BTC_NODES, "Custom nodes used for BitcoinJ as comma separated IP addresses.")
.withRequiredArg()
.describedAs("ip[,...]")
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> useTorForBtcOpt =
parser.accepts("useTorForBtc", "If set to true BitcoinJ is routed over tor (socks 5 proxy).")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> socks5DiscoverModeOpt =
parser.accepts(SOCKS5_DISCOVER_MODE, "Specify discovery mode for Bitcoin nodes. " +
"One or more of: [ADDR, DNS, ONION, ALL] (comma separated, they get OR'd together).")
.withRequiredArg()
.describedAs("mode[,...]")
.defaultsTo("ALL");
ArgumentAcceptingOptionSpec<Boolean> useAllProvidedNodesOpt =
parser.accepts(USE_ALL_PROVIDED_NODES,
"Set to true if connection of bitcoin nodes should include clear net nodes")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> userAgentOpt =
parser.accepts(USER_AGENT,
"User agent at btc node connections")
.withRequiredArg()
.defaultsTo("Bisq");
ArgumentAcceptingOptionSpec<Integer> numConnectionsForBtcOpt =
parser.accepts(NUM_CONNECTIONS_FOR_BTC, "Number of connections to the Bitcoin network")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(DEFAULT_NUM_CONNECTIONS_FOR_BTC);
ArgumentAcceptingOptionSpec<String> rpcUserOpt =
parser.accepts(RPC_USER, "Bitcoind rpc username")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> rpcPasswordOpt =
parser.accepts(RPC_PASSWORD, "Bitcoind rpc password")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> rpcHostOpt =
parser.accepts(RPC_HOST, "Bitcoind rpc host")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> rpcPortOpt =
parser.accepts(RPC_PORT, "Bitcoind rpc port")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<Integer> rpcBlockNotificationPortOpt =
parser.accepts(RPC_BLOCK_NOTIFICATION_PORT, "Bitcoind rpc port for block notifications")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<String> rpcBlockNotificationHostOpt =
parser.accepts(RPC_BLOCK_NOTIFICATION_HOST,
"Bitcoind rpc accepted incoming host for block notifications")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> dumpBlockchainDataOpt =
parser.accepts(DUMP_BLOCKCHAIN_DATA, "If set to true the blockchain data " +
"from RPC requests to Bitcoin Core are stored as json file in the data dir.")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> fullDaoNodeOpt =
parser.accepts(FULL_DAO_NODE, "If set to true the node requests the blockchain data via RPC requests " +
"from Bitcoin Core and provide the validated BSQ txs to the network. It requires that the " +
"other RPC properties are set as well.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(DEFAULT_FULL_DAO_NODE);
ArgumentAcceptingOptionSpec<String> genesisTxIdOpt =
parser.accepts(GENESIS_TX_ID, "Genesis transaction ID when not using the hard coded one")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> genesisBlockHeightOpt =
parser.accepts(GENESIS_BLOCK_HEIGHT,
"Genesis transaction block height when not using the hard coded one")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(-1);
ArgumentAcceptingOptionSpec<Long> genesisTotalSupplyOpt =
parser.accepts(GENESIS_TOTAL_SUPPLY, "Genesis total supply when not using the hard coded one")
.withRequiredArg()
.ofType(long.class)
.defaultsTo(-1L);
ArgumentAcceptingOptionSpec<Boolean> daoActivatedOpt =
parser.accepts(DAO_ACTIVATED, "Developer flag. If true it enables dao phase 2 features.")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(true);
try {
CompositeOptionSet options = new CompositeOptionSet();
OptionSet cliOpts = parser.parse(args);
options.addOptionSet(cliOpts);
File configFile = null;
final boolean cliHasConfigFileOpt = cliOpts.has(configFileOpt);
boolean configFileHasBeenProcessed = false;
if (cliHasConfigFileOpt) {
configFile = new File(cliOpts.valueOf(configFileOpt));
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
if (configFileOpts.isPresent()) {
options.addOptionSet(configFileOpts.get());
configFileHasBeenProcessed = true;
}
}
this.appName = options.valueOf(appNameOpt);
this.userDataDir = options.valueOf(userDataDirOpt);
this.appDataDir = mkAppDataDir(options.has(appDataDirOpt) ?
options.valueOf(appDataDirOpt) :
new File(this.userDataDir, this.appName));
if (!configFileHasBeenProcessed) {
configFile = cliHasConfigFileOpt && !configFile.isAbsolute() ?
new File(this.appDataDir, configFile.getPath()) : // TODO: test
new File(this.appDataDir, DEFAULT_CONFIG_FILE_NAME);
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
configFileOpts.ifPresent(options::addOptionSet);
}
this.helpRequested = options.has(helpOpt);
this.configFile = configFile;
this.nodePort = options.valueOf(nodePortOpt);
this.bannedBtcNodes = options.valuesOf(bannedBtcNodesOpt);
this.bannedPriceRelayNodes = options.valuesOf(bannedPriceRelayNodesOpt);
this.bannedSeedNodes = options.valuesOf(bannedSeedNodesOpt);
this.baseCurrencyNetwork = (BaseCurrencyNetwork) options.valueOf(baseCurrencyNetworkOpt);
this.baseCurrencyNetworkParameters = baseCurrencyNetwork.getParameters();
this.ignoreLocalBtcNode = options.valueOf(ignoreLocalBtcNodeOpt);
this.bitcoinRegtestHost = options.valueOf(bitcoinRegtestHostOpt);
this.logLevel = options.valueOf(logLevelOpt);
this.torrcFile = options.has(torrcFileOpt) ? options.valueOf(torrcFileOpt).toFile() : null;
this.torrcOptions = options.valueOf(torrcOptionsOpt);
this.torControlPort = options.valueOf(torControlPortOpt);
this.torControlPassword = options.valueOf(torControlPasswordOpt);
this.torControlCookieFile = options.has(torControlCookieFileOpt) ?
options.valueOf(torControlCookieFileOpt).toFile() : null;
this.useTorControlSafeCookieAuth = options.has(torControlUseSafeCookieAuthOpt);
this.torStreamIsolation = options.has(torStreamIsolationOpt);
this.referralId = options.valueOf(referralIdOpt);
this.useDevMode = options.valueOf(useDevModeOpt);
this.useDevPrivilegeKeys = options.valueOf(useDevPrivilegeKeysOpt);
this.dumpStatistics = options.valueOf(dumpStatisticsOpt);
this.maxMemory = options.valueOf(maxMemoryOpt);
this.ignoreDevMsg = options.valueOf(ignoreDevMsgOpt);
this.providers = options.valuesOf(providersOpt);
this.seedNodes = options.valuesOf(seedNodesOpt);
this.banList = options.valuesOf(banListOpt);
this.useLocalhostForP2P = options.valueOf(useLocalhostForP2POpt);
this.maxConnections = options.valueOf(maxConnectionsOpt);
this.socks5ProxyBtcAddress = options.valueOf(socks5ProxyBtcAddressOpt);
this.socks5ProxyHttpAddress = options.valueOf(socks5ProxyHttpAddressOpt);
this.msgThrottlePerSec = options.valueOf(msgThrottlePerSecOpt);
this.msgThrottlePer10Sec = options.valueOf(msgThrottlePer10SecOpt);
this.sendMsgThrottleTrigger = options.valueOf(sendMsgThrottleTriggerOpt);
this.sendMsgThrottleSleep = options.valueOf(sendMsgThrottleSleepOpt);
this.btcNodes = options.valueOf(btcNodesOpt);
this.useTorForBtc = options.valueOf(useTorForBtcOpt);
this.useTorForBtcOptionSetExplicitly = options.has(useTorForBtcOpt);
this.socks5DiscoverMode = options.valueOf(socks5DiscoverModeOpt);
this.useAllProvidedNodes = options.valueOf(useAllProvidedNodesOpt);
this.userAgent = options.valueOf(userAgentOpt);
this.numConnectionsForBtc = options.valueOf(numConnectionsForBtcOpt);
this.rpcUser = options.valueOf(rpcUserOpt);
this.rpcPassword = options.valueOf(rpcPasswordOpt);
this.rpcHost = options.valueOf(rpcHostOpt);
this.rpcPort = options.valueOf(rpcPortOpt);
this.rpcBlockNotificationPort = options.valueOf(rpcBlockNotificationPortOpt);
this.rpcBlockNotificationHost = options.valueOf(rpcBlockNotificationHostOpt);
this.dumpBlockchainData = options.valueOf(dumpBlockchainDataOpt);
this.fullDaoNode = options.valueOf(fullDaoNodeOpt);
this.fullDaoNodeOptionSetExplicitly = options.has(fullDaoNodeOpt);
this.genesisTxId = options.valueOf(genesisTxIdOpt);
this.genesisBlockHeight = options.valueOf(genesisBlockHeightOpt);
this.genesisTotalSupply = options.valueOf(genesisTotalSupplyOpt);
this.daoActivated = options.valueOf(daoActivatedOpt) || !baseCurrencyNetwork.isMainnet();
} catch (OptionException ex) {
throw new ConfigException("problem parsing option '%s': %s",
ex.options().get(0),
ex.getCause() != null ?
ex.getCause().getMessage() :
ex.getMessage());
}
// properties derived from options but not exposed as options themselves
File btcNetworkDir = mkdir(appDataDir, baseCurrencyNetwork.name().toLowerCase());
this.keyStorageDir = mkdir(btcNetworkDir, "keys");
this.storageDir = mkdir(btcNetworkDir, "db");
this.torDir = mkdir(btcNetworkDir, "tor");
this.walletDir = mkdir(btcNetworkDir, "wallet");
APP_DATA_DIR_VALUE = appDataDir;
BASE_CURRENCY_NETWORK_VALUE = baseCurrencyNetwork;
}
private Optional<OptionSet> parseOptionsFrom(File file, OptionParser parser, OptionSpec<?>... disallowedOpts) {
if (!file.isAbsolute() || !file.exists())
return Optional.empty();
ConfigFileReader configFileReader = new ConfigFileReader(file);
String[] optionLines = configFileReader.getOptionLines().stream()
.map(o -> "--" + o) // prepend dashes expected by jopt parser below
.collect(toList())
.toArray(new String[]{});
OptionSet configFileOpts = parser.parse(optionLines);
for (OptionSpec<?> disallowedOpt : disallowedOpts)
if (configFileOpts.has(disallowedOpt))
throw new ConfigException("The '%s' option is disallowed in config files",
disallowedOpt.options().get(0));
return Optional.of(configFileOpts);
}
public void printHelp(OutputStream sink, HelpFormatter formatter) {
try {
parser.formatHelpWith(formatter);
parser.printHelpOn(sink);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
// == STATIC UTILS ===================================================================
public static File getOsUserDataDir() {
if (Utilities.isWindows())
return new File(System.getenv("APPDATA"));
if (Utilities.isOSX())
return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toFile();
// *nix
return Paths.get(System.getProperty("user.home"), ".local", "share").toFile();
}
private static File tempUserDataDir() {
try {
return Files.createTempDirectory("BisqTempUserData").toFile();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private static String tempAppName() {
try {
File file = Files.createTempFile("Bisq", "Temp").toFile();
file.delete();
return file.toPath().getFileName().toString();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Creates {@value APP_DATA_DIR} including any nonexistent parent directories.
* Does nothing if the directory already exists.
* @return the given directory, now guaranteed to exist
*/
private static File mkAppDataDir(File appDataDir) {
Path path = appDataDir.toPath();
try {
Files.createDirectories(path);
} catch (IOException ex) {
throw new ConfigException(ex, "Application data directory '%s' could not be created", path);
}
return appDataDir;
}
/**
* Creates child directory assuming parent directories already exist.
* Does nothing if the directory already exists.
* @return the child directory, now guaranteed to exist
*/
private static File mkdir(File parent, String child) {
File dir = new File(parent, child);
if (!dir.exists()) {
Path path = dir.toPath();
try {
Files.createDirectory(path);
} catch (IOException ex) {
throw new ConfigException(ex, "Directory '%s' could not be created", path);
}
}
return dir;
}
// == STATIC ACCESSORS ======================================================================
/**
* Static accessor that returns the same value as the non-static
* {@link #getAppDataDir()} method. For use only in the {@code Overlay} class, where
* because of its large number of subclasses, injecting the Guice-managed
* {@link Config} class is not worth the effort. {@link #getAppDataDir()} should be
* favored in all other cases.
* @throws NullPointerException if the static value has not yet been assigned, i.e. if
* the Guice-managed {@link Config} class has not yet been instantiated elsewhere.
* This should never be the case, as Guice wiring always happens before any
* {@code Overlay} class is instantiated.
*/
public static File appDataDir() {
return checkNotNull(APP_DATA_DIR_VALUE, "The static appDataDir has not yet " +
"been assigned. A Config instance must be instantiated (usually by " +
"Guice) before calling this method.");
}
/**
* Static accessor that returns either the default base currency network value of
* {@link BaseCurrencyNetwork#BTC_MAINNET} or the value assigned via the
* {@value BASE_CURRENCY_NETWORK} option. The non-static
* {@link #getBaseCurrencyNetwork()} accessor should be favored whenever possible and
* this static accessor should be used only in code locations where it is infeasible
* or too cumbersome to inject the normal Guice-managed singleton {@link Config}
* instance.
*/
public static BaseCurrencyNetwork baseCurrencyNetwork() {
return BASE_CURRENCY_NETWORK_VALUE;
}
/**
* Static accessor that returns the value of
* {@code baseCurrencyNetwork().getParameters()} for convenience and to avoid violating
* the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>. The
* non-static {@link #getBaseCurrencyNetwork()} method should be favored whenever
* possible.
* @see #baseCurrencyNetwork()
*/
public static NetworkParameters baseCurrencyNetworkParameters() {
return BASE_CURRENCY_NETWORK_VALUE.getParameters();
}
// == ACCESSORS ======================================================================
public String getDefaultAppName() {
return defaultAppName;
}
public File getDefaultUserDataDir() {
return defaultUserDataDir;
}
public File getDefaultAppDataDir() {
return defaultAppDataDir;
}
public File getDefaultConfigFile() {
return defaultConfigFile;
}
public boolean isHelpRequested() {
return helpRequested;
}
public File getConfigFile() {
return configFile;
}
public String getAppName() {
return appName;
}
public File getUserDataDir() {
return userDataDir;
}
public File getAppDataDir() {
return appDataDir;
}
public int getNodePort() {
return nodePort;
}
public List<String> getBannedBtcNodes() {
return bannedBtcNodes;
}
public List<String> getBannedPriceRelayNodes() {
return bannedPriceRelayNodes;
}
public List<String> getBannedSeedNodes() {
return bannedSeedNodes;
}
public BaseCurrencyNetwork getBaseCurrencyNetwork() {
return baseCurrencyNetwork;
}
public NetworkParameters getBaseCurrencyNetworkParameters() {
return baseCurrencyNetworkParameters;
}
public boolean isIgnoreLocalBtcNode() {
return ignoreLocalBtcNode;
}
public String getBitcoinRegtestHost() {
return bitcoinRegtestHost;
}
public String getLogLevel() {
return logLevel;
}
public String getReferralId() {
return referralId;
}
public boolean isUseDevMode() {
return useDevMode;
}
public File getTorDir() {
return torDir;
}
public File getWalletDir() {
return walletDir;
}
public File getStorageDir() {
return storageDir;
}
public File getKeyStorageDir() {
return keyStorageDir;
}
public boolean isUseDevPrivilegeKeys() {
return useDevPrivilegeKeys;
}
public boolean isDumpStatistics() {
return dumpStatistics;
}
public int getMaxMemory() {
return maxMemory;
}
public boolean isIgnoreDevMsg() {
return ignoreDevMsg;
}
public List<String> getProviders() {
return providers;
}
public List<String> getSeedNodes() {
return seedNodes;
}
public List<String> getBanList() {
return banList;
}
public boolean isUseLocalhostForP2P() {
return useLocalhostForP2P;
}
public int getMaxConnections() {
return maxConnections;
}
public String getSocks5ProxyBtcAddress() {
return socks5ProxyBtcAddress;
}
public String getSocks5ProxyHttpAddress() {
return socks5ProxyHttpAddress;
}
public File getTorrcFile() {
return torrcFile;
}
public String getTorrcOptions() {
return torrcOptions;
}
public int getTorControlPort() {
return torControlPort;
}
public String getTorControlPassword() {
return torControlPassword;
}
public File getTorControlCookieFile() {
return torControlCookieFile;
}
public boolean isUseTorControlSafeCookieAuth() {
return useTorControlSafeCookieAuth;
}
public boolean isTorStreamIsolation() {
return torStreamIsolation;
}
public int getMsgThrottlePerSec() {
return msgThrottlePerSec;
}
public int getMsgThrottlePer10Sec() {
return msgThrottlePer10Sec;
}
public int getSendMsgThrottleTrigger() {
return sendMsgThrottleTrigger;
}
public int getSendMsgThrottleSleep() {
return sendMsgThrottleSleep;
}
public String getBtcNodes() {
return btcNodes;
}
public boolean isUseTorForBtc() {
return useTorForBtc;
}
public boolean isUseTorForBtcOptionSetExplicitly() {
return useTorForBtcOptionSetExplicitly;
}
public String getSocks5DiscoverMode() {
return socks5DiscoverMode;
}
public boolean isUseAllProvidedNodes() {
return useAllProvidedNodes;
}
public String getUserAgent() {
return userAgent;
}
public int getNumConnectionsForBtc() {
return numConnectionsForBtc;
}
public String getRpcUser() {
return rpcUser;
}
public String getRpcPassword() {
return rpcPassword;
}