use of org.berndpruenster.netlayer.tor.Tor in project bitcoin-spring-boot-starter by theborakompanioni.
the class DefaultTorHiddenServiceSocketFactoryTest method itShouldCreateHiddenService.
@Test
void itShouldCreateHiddenService() throws InterruptedException {
// create a hidden service in directory 'test' inside the tor installation directory
HiddenServiceSocketCreateContext context = HiddenServiceSocketCreateContext.builder().hostPort(port).hiddenServiceDir("test").build();
HiddenServiceSocket hiddenServiceSocket = this.sut.createReady(context).blockOptional(Duration.ofMinutes(3)).orElseThrow(() -> new IllegalStateException("Could not create hidden service on port " + port));
log.info("Hidden Service {} is ready", hiddenServiceSocket);
Flux<Socket> socketFlux = Flux.<Socket>create(fluxSink -> {
try {
fluxSink.next(hiddenServiceSocket.accept());
} catch (IOException e) {
fluxSink.error(e);
}
}).onErrorContinue((e, target) -> {
log.warn("Error while accepting socket connections: {}", e.getMessage());
});
CountDownLatch countDownLatch = new CountDownLatch(1);
new Thread(() -> {
log.info("trying to connect to the hidden service {}", hiddenServiceSocket);
try (TorSocket s1 = new TorSocket(hiddenServiceSocket.getSocketAddress(), "foo")) {
log.info("Successfully connected to {}", hiddenServiceSocket);
log.info("Closing socket now...");
IOUtils.closeQuietly(hiddenServiceSocket);
} catch (IOException e) {
log.error("Exception while handling socket connection", e);
}
// retry connecting
try (TorSocket s2 = new TorSocket(hiddenServiceSocket.getServiceName(), hiddenServiceSocket.getHiddenServicePort(), "foo")) {
// do nothing on purpose
log.error("expected an error when opening connection to closed hidden service socket");
} catch (IOException e) {
log.debug("As expected, connection to {} failed with: {}", hiddenServiceSocket, e.getMessage());
}
countDownLatch.countDown();
}).start();
Socket incomingSocket = socketFlux.blockFirst(Duration.ofSeconds(10));
log.info("Got an incoming connection to socket {}: {}", hiddenServiceSocket, incomingSocket);
boolean await = countDownLatch.await(90, TimeUnit.SECONDS);
assertThat("socket has been accepted", await, is(true));
IOUtils.closeQuietly(incomingSocket);
}
use of org.berndpruenster.netlayer.tor.Tor in project bitcoin-spring-boot-starter by theborakompanioni.
the class TorExampleApplication method torInfoRunner.
@Bean
@Profile("!test")
public ApplicationRunner torInfoRunner() {
String successPhrase = "Congratulations. This browser is configured to use Tor.";
String errorPhraseIgnoreCase = "not using Tor";
return args -> {
HttpGet req = new HttpGet("https://check.torproject.org/");
HttpResponse rsp = torHttpClient.execute(req);
String body = EntityUtils.toString(rsp.getEntity(), StandardCharsets.UTF_8);
boolean containsErrorPhrase = body.toLowerCase().contains(errorPhraseIgnoreCase.toLowerCase());
boolean containsSuccessPhrase = body.contains(successPhrase);
boolean torEnabled = containsSuccessPhrase && !containsErrorPhrase;
log.info("=================================================");
if (torEnabled) {
log.info("Tor is enabled.");
} else {
log.warn("Tor is NOT enabled.");
}
log.info("=================================================");
};
}
use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.
the class PriceNodeStats method execute.
@Override
protected void execute() {
try {
// fetch proxy
Tor tor = Tor.getDefault();
checkNotNull(tor, "tor must not be null");
Socks5Proxy proxy = tor.getProxy();
String[] hosts = configuration.getProperty(HOSTS, "").split(",");
Collections.shuffle(Arrays.asList(hosts));
// for each configured host
for (String current : hosts) {
Map<String, String> result = new HashMap<>();
// parse Url
NodeAddress tmp = OnionParser.getNodeAddress(current);
// connect
try {
SocksSocket socket = new SocksSocket(proxy, tmp.getHostName(), tmp.getPort());
// prepare to receive data
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// ask for fee data
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.println("GET /getFees/");
out.println();
out.flush();
// sift through the received lines and see if we got something json-like
String line;
while ((line = in.readLine()) != null) {
Matcher matcher = stringNumberPattern.matcher(line);
if (matcher.find())
if (!IGNORE.contains(matcher.group(1)))
result.put("fees." + matcher.group(1), matcher.group(2));
}
in.close();
out.close();
socket.close();
// connect
socket = new SocksSocket(proxy, tmp.getHostName(), tmp.getPort());
// prepare to receive data
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// ask for exchange rate data
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.println("GET /getAllMarketPrices/");
out.println();
out.flush();
String currencyCode = "";
while ((line = in.readLine()) != null) {
Matcher currencyCodeMatcher = currencyCodePattern.matcher(line);
Matcher priceMatcher = pricePattern.matcher(line);
if (currencyCodeMatcher.find()) {
currencyCode = currencyCodeMatcher.group(1);
if (!assets.contains(currencyCode))
currencyCode = "";
} else if (!"".equals(currencyCode) && priceMatcher.find())
result.put("price." + currencyCode, priceMatcher.group(1));
}
// close all the things
in.close();
out.close();
socket.close();
// report
reporter.report(result, getName());
// only ask for data as long as we got none
if (!result.isEmpty())
break;
} catch (IOException e) {
log.error("{} seems to be down. Trying next configured price node.", tmp.getHostName());
e.printStackTrace();
}
}
} catch (TorCtlException | IOException e) {
e.printStackTrace();
}
}
use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.
the class TorNetworkNode method createTorAndHiddenService.
// /////////////////////////////////////////////////////////////////////////////////////////
// create tor
// /////////////////////////////////////////////////////////////////////////////////////////
private void createTorAndHiddenService(int localPort, int servicePort) {
torStartupFuture = executorService.submit(() -> {
try {
// get tor
Tor.setDefault(torMode.getTor());
// start hidden service
long ts2 = new Date().getTime();
hiddenServiceSocket = new HiddenServiceSocket(localPort, torMode.getHiddenServiceDirectory(), servicePort);
nodeAddressProperty.set(new NodeAddress(hiddenServiceSocket.getServiceName() + ":" + hiddenServiceSocket.getHiddenServicePort()));
UserThread.execute(() -> setupListeners.forEach(SetupListener::onTorNodeReady));
hiddenServiceSocket.addReadyListener(socket -> {
try {
log.info("\n################################################################\n" + "Tor hidden service published after {} ms. Socket={}\n" + "################################################################", (new Date().getTime() - ts2), // takes usually 30-40 sec
socket);
new Thread() {
@Override
public void run() {
try {
nodeAddressProperty.set(new NodeAddress(hiddenServiceSocket.getServiceName() + ":" + hiddenServiceSocket.getHiddenServicePort()));
startServer(socket);
UserThread.execute(() -> setupListeners.forEach(SetupListener::onHiddenServicePublished));
} catch (final Exception e1) {
log.error(e1.toString());
e1.printStackTrace();
}
}
}.start();
} catch (final Exception e) {
log.error(e.toString());
e.printStackTrace();
}
return null;
});
} catch (TorCtlException e) {
String msg = e.getCause() != null ? e.getCause().toString() : e.toString();
log.error("Tor node creation failed: {}", msg);
if (e.getCause() instanceof IOException) {
// Since we cannot connect to Tor, we cannot do nothing.
// Furthermore, we have no hidden services started yet, so there is no graceful
// shutdown needed either
UserThread.execute(() -> setupListeners.forEach(s -> s.onSetupFailed(new RuntimeException(msg))));
} else {
restartTor(e.getMessage());
}
} catch (IOException e) {
log.error("Could not connect to running Tor: {}", e.getMessage());
// Since we cannot connect to Tor, we cannot do nothing.
// Furthermore, we have no hidden services started yet, so there is no graceful
// shutdown needed either
UserThread.execute(() -> setupListeners.forEach(s -> s.onSetupFailed(new RuntimeException(e.getMessage()))));
} catch (Throwable ignore) {
}
return null;
});
Futures.addCallback(torStartupFuture, Utilities.failureCallback(throwable -> UserThread.execute(() -> log.error("Hidden service creation failed: " + throwable))), MoreExecutors.directExecutor());
}
use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.
the class P2PNetworkLoadTests method cleanup.
@AfterAll
static void cleanup() {
Tor tor = Tor.getDefault();
checkNotNull(tor, "tor must not be null");
tor.shutdown();
}
Aggregations