+
diff --git a/frontend/src/app/status/status.component.scss b/frontend/src/app/status/status.component.scss
new file mode 100644
index 0000000..845b915
--- /dev/null
+++ b/frontend/src/app/status/status.component.scss
@@ -0,0 +1,4 @@
+:host {
+ margin: 2em;
+ display: block;
+}
diff --git a/frontend/src/app/status/status.component.spec.ts b/frontend/src/app/status/status.component.spec.ts
new file mode 100644
index 0000000..ddf4f67
--- /dev/null
+++ b/frontend/src/app/status/status.component.spec.ts
@@ -0,0 +1,25 @@
+import { async, ComponentFixture, TestBed } from '@angular/core/testing';
+
+import { StatusComponent } from './status.component';
+
+describe('StatusComponent', () => {
+ let component: StatusComponent;
+ let fixture: ComponentFixture;
+
+ beforeEach(async(() => {
+ TestBed.configureTestingModule({
+ declarations: [ StatusComponent ]
+ })
+ .compileComponents();
+ }));
+
+ beforeEach(() => {
+ fixture = TestBed.createComponent(StatusComponent);
+ component = fixture.componentInstance;
+ fixture.detectChanges();
+ });
+
+ it('should create', () => {
+ expect(component).toBeTruthy();
+ });
+});
diff --git a/frontend/src/app/status/status.component.ts b/frontend/src/app/status/status.component.ts
new file mode 100644
index 0000000..2781b71
--- /dev/null
+++ b/frontend/src/app/status/status.component.ts
@@ -0,0 +1,22 @@
+import {Component, OnInit} from '@angular/core';
+import {HttpClient} from '@angular/common/http';
+
+@Component({
+ selector: 'app-status',
+ templateUrl: './status.component.html',
+ styleUrls: ['./status.component.scss']
+})
+export class StatusComponent implements OnInit {
+
+ status: string;
+
+ constructor(private http: HttpClient) {
+ }
+
+ ngOnInit() {
+ this.http.get('http://localhost:8080/status').subscribe(data => {
+ this.status = JSON.stringify(data, null, 2);
+ });
+ }
+
+}
diff --git a/frontend/src/assets/.gitkeep b/frontend/src/assets/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/frontend/src/environments/environment.prod.ts b/frontend/src/environments/environment.prod.ts
new file mode 100644
index 0000000..3612073
--- /dev/null
+++ b/frontend/src/environments/environment.prod.ts
@@ -0,0 +1,3 @@
+export const environment = {
+ production: true
+};
diff --git a/frontend/src/environments/environment.ts b/frontend/src/environments/environment.ts
new file mode 100644
index 0000000..b7f639a
--- /dev/null
+++ b/frontend/src/environments/environment.ts
@@ -0,0 +1,8 @@
+// The file contents for the current environment will overwrite these during build.
+// The build system defaults to the dev environment which uses `environment.ts`, but if you do
+// `ng build --env=prod` then `environment.prod.ts` will be used instead.
+// The list of which env maps to which file can be found in `.angular-cli.json`.
+
+export const environment = {
+ production: false
+};
diff --git a/frontend/src/favicon.ico b/frontend/src/favicon.ico
new file mode 100644
index 0000000..8081c7c
Binary files /dev/null and b/frontend/src/favicon.ico differ
diff --git a/frontend/src/index.html b/frontend/src/index.html
new file mode 100644
index 0000000..6f20921
--- /dev/null
+++ b/frontend/src/index.html
@@ -0,0 +1,16 @@
+
+
+
+
+ JabitServer
+
+
+
+
+
+
+
+
+ Loading...
+
+
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
new file mode 100644
index 0000000..a9ca1ca
--- /dev/null
+++ b/frontend/src/main.ts
@@ -0,0 +1,11 @@
+import { enableProdMode } from '@angular/core';
+import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
+
+import { AppModule } from './app/app.module';
+import { environment } from './environments/environment';
+
+if (environment.production) {
+ enableProdMode();
+}
+
+platformBrowserDynamic().bootstrapModule(AppModule);
diff --git a/frontend/src/polyfills.ts b/frontend/src/polyfills.ts
new file mode 100644
index 0000000..bc94e7a
--- /dev/null
+++ b/frontend/src/polyfills.ts
@@ -0,0 +1,72 @@
+/**
+ * This file includes polyfills needed by Angular and is loaded before the app.
+ * You can add your own extra polyfills to this file.
+ *
+ * This file is divided into 2 sections:
+ * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
+ * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
+ * file.
+ *
+ * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
+ * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
+ * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
+ *
+ * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
+ */
+
+/***************************************************************************************************
+ * BROWSER POLYFILLS
+ */
+
+/** IE9, IE10 and IE11 requires all of the following polyfills. **/
+// import 'core-js/es6/symbol';
+// import 'core-js/es6/object';
+// import 'core-js/es6/function';
+// import 'core-js/es6/parse-int';
+// import 'core-js/es6/parse-float';
+// import 'core-js/es6/number';
+// import 'core-js/es6/math';
+// import 'core-js/es6/string';
+// import 'core-js/es6/date';
+// import 'core-js/es6/array';
+// import 'core-js/es6/regexp';
+// import 'core-js/es6/map';
+// import 'core-js/es6/set';
+
+/** IE10 and IE11 requires the following for NgClass support on SVG elements */
+// import 'classlist.js'; // Run `npm install --save classlist.js`.
+
+/** IE10 and IE11 requires the following to support `@angular/animation`. */
+// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
+
+
+/** Evergreen browsers require these. **/
+import 'core-js/es6/reflect';
+import 'core-js/es7/reflect';
+
+
+/** ALL Firefox browsers require the following to support `@angular/animation`. **/
+// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
+
+
+
+/***************************************************************************************************
+ * Zone JS is required by Angular itself.
+ */
+import 'zone.js/dist/zone'; // Included with Angular CLI.
+
+
+
+/***************************************************************************************************
+ * APPLICATION IMPORTS
+ */
+
+/**
+ * Date, currency, decimal and percent pipes.
+ * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
+ */
+// import 'intl'; // Run `npm install --save intl`.
+/**
+ * Need to import at least one locale-data with intl.
+ */
+// import 'intl/locale-data/jsonp/en';
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
new file mode 100644
index 0000000..7a81e04
--- /dev/null
+++ b/frontend/src/styles.css
@@ -0,0 +1,6 @@
+/* You can add global styles to this file, and also import other style files */
+@import "~@angular/material/prebuilt-themes/indigo-pink.css";
+
+body {
+ margin: 0;
+}
diff --git a/frontend/src/test.ts b/frontend/src/test.ts
new file mode 100644
index 0000000..9bf7226
--- /dev/null
+++ b/frontend/src/test.ts
@@ -0,0 +1,32 @@
+// This file is required by karma.conf.js and loads recursively all the .spec and framework files
+
+import 'zone.js/dist/long-stack-trace-zone';
+import 'zone.js/dist/proxy.js';
+import 'zone.js/dist/sync-test';
+import 'zone.js/dist/jasmine-patch';
+import 'zone.js/dist/async-test';
+import 'zone.js/dist/fake-async-test';
+import { getTestBed } from '@angular/core/testing';
+import {
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting
+} from '@angular/platform-browser-dynamic/testing';
+
+// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
+declare var __karma__: any;
+declare var require: any;
+
+// Prevent Karma from running prematurely.
+__karma__.loaded = function () {};
+
+// First, initialize the Angular testing environment.
+getTestBed().initTestEnvironment(
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting()
+);
+// Then we find all the tests.
+const context = require.context('./', true, /\.spec\.ts$/);
+// And load the modules.
+context.keys().map(context);
+// Finally, start Karma to run the tests.
+__karma__.start();
diff --git a/frontend/src/tsconfig.app.json b/frontend/src/tsconfig.app.json
new file mode 100644
index 0000000..5e2507d
--- /dev/null
+++ b/frontend/src/tsconfig.app.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "outDir": "../out-tsc/app",
+ "module": "es2015",
+ "baseUrl": "",
+ "types": []
+ },
+ "exclude": [
+ "test.ts",
+ "**/*.spec.ts"
+ ]
+}
diff --git a/frontend/src/tsconfig.spec.json b/frontend/src/tsconfig.spec.json
new file mode 100644
index 0000000..510e3f1
--- /dev/null
+++ b/frontend/src/tsconfig.spec.json
@@ -0,0 +1,20 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "outDir": "../out-tsc/spec",
+ "module": "commonjs",
+ "target": "es5",
+ "baseUrl": "",
+ "types": [
+ "jasmine",
+ "node"
+ ]
+ },
+ "files": [
+ "test.ts"
+ ],
+ "include": [
+ "**/*.spec.ts",
+ "**/*.d.ts"
+ ]
+}
diff --git a/frontend/src/typings.d.ts b/frontend/src/typings.d.ts
new file mode 100644
index 0000000..ef5c7bd
--- /dev/null
+++ b/frontend/src/typings.d.ts
@@ -0,0 +1,5 @@
+/* SystemJS module definition */
+declare var module: NodeModule;
+interface NodeModule {
+ id: string;
+}
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
new file mode 100644
index 0000000..a35a8ee
--- /dev/null
+++ b/frontend/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compileOnSave": false,
+ "compilerOptions": {
+ "outDir": "./dist/out-tsc",
+ "baseUrl": "src",
+ "sourceMap": true,
+ "declaration": false,
+ "moduleResolution": "node",
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "target": "es5",
+ "typeRoots": [
+ "node_modules/@types"
+ ],
+ "lib": [
+ "es2016",
+ "dom"
+ ]
+ }
+}
diff --git a/frontend/tslint.json b/frontend/tslint.json
new file mode 100644
index 0000000..97adaa5
--- /dev/null
+++ b/frontend/tslint.json
@@ -0,0 +1,130 @@
+{
+ "rulesDirectory": [
+ "node_modules/codelyzer"
+ ],
+ "rules": {
+ "callable-types": true,
+ "class-name": true,
+ "comment-format": [
+ true,
+ "check-space"
+ ],
+ "curly": true,
+ "eofline": true,
+ "forin": true,
+ "import-blacklist": [
+ true,
+ "rxjs"
+ ],
+ "import-spacing": true,
+ "indent": [
+ true,
+ "spaces"
+ ],
+ "interface-over-type-literal": true,
+ "label-position": true,
+ "max-line-length": [
+ true,
+ 140
+ ],
+ "member-access": false,
+ "member-ordering": [
+ true,
+ "static-before-instance",
+ "variables-before-functions"
+ ],
+ "no-arg": true,
+ "no-bitwise": true,
+ "no-console": [
+ true,
+ "debug",
+ "info",
+ "time",
+ "timeEnd",
+ "trace"
+ ],
+ "no-construct": true,
+ "no-debugger": true,
+ "no-empty": false,
+ "no-empty-interface": true,
+ "no-eval": true,
+ "no-inferrable-types": [
+ true,
+ "ignore-params"
+ ],
+ "no-shadowed-variable": true,
+ "no-string-literal": false,
+ "no-string-throw": true,
+ "no-switch-case-fall-through": true,
+ "no-trailing-whitespace": true,
+ "no-unused-expression": true,
+ "no-use-before-declare": true,
+ "no-var-keyword": true,
+ "object-literal-sort-keys": false,
+ "one-line": [
+ true,
+ "check-open-brace",
+ "check-catch",
+ "check-else",
+ "check-whitespace"
+ ],
+ "prefer-const": true,
+ "quotemark": [
+ true,
+ "single"
+ ],
+ "radix": true,
+ "semicolon": [
+ "always"
+ ],
+ "triple-equals": [
+ true,
+ "allow-null-check"
+ ],
+ "typedef-whitespace": [
+ true,
+ {
+ "call-signature": "nospace",
+ "index-signature": "nospace",
+ "parameter": "nospace",
+ "property-declaration": "nospace",
+ "variable-declaration": "nospace"
+ }
+ ],
+ "typeof-compare": true,
+ "unified-signatures": true,
+ "variable-name": false,
+ "whitespace": [
+ true,
+ "check-branch",
+ "check-decl",
+ "check-operator",
+ "check-separator",
+ "check-type"
+ ],
+ "directive-selector": [
+ true,
+ "attribute",
+ "app",
+ "camelCase"
+ ],
+ "component-selector": [
+ true,
+ "element",
+ "app",
+ "kebab-case"
+ ],
+ "use-input-property-decorator": true,
+ "use-output-property-decorator": true,
+ "use-host-property-decorator": true,
+ "no-input-rename": true,
+ "no-output-rename": true,
+ "use-life-cycle-interface": true,
+ "use-pipe-transform-interface": true,
+ "component-class-suffix": true,
+ "directive-class-suffix": true,
+ "no-access-missing-member": true,
+ "templates-use-public": true,
+ "invoke-injectable": true
+ }
+}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 3d0dee6..05ef575 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 94f382d..a156802 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Mon Mar 16 20:59:34 CET 2015
+#Thu Oct 19 11:25:29 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip
diff --git a/gradlew b/gradlew
index 91a7e26..9d82f78 100755
--- a/gradlew
+++ b/gradlew
@@ -42,11 +42,6 @@ case "`uname`" in
;;
esac
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -61,9 +56,9 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
+cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
+cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -114,6 +109,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
diff --git a/settings.gradle b/settings.gradle
index b13e282..5557193 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1 +1,3 @@
-include 'webapp'
\ No newline at end of file
+include 'frontend'
+
+rootProject.name = 'jabit-server'
\ No newline at end of file
diff --git a/src/main/docker/Dockerfile b/src/main/docker/Dockerfile
new file mode 100644
index 0000000..fb58667
--- /dev/null
+++ b/src/main/docker/Dockerfile
@@ -0,0 +1,6 @@
+FROM frolvlad/alpine-oraclejdk8:slim
+VOLUME /tmp
+ADD jabit-server.jar app.jar
+RUN sh -c 'touch /app.jar'
+ENV JAVA_OPTS=""
+ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
diff --git a/src/main/java/ch/dissem/bitmessage/server/Constants.java b/src/main/java/ch/dissem/bitmessage/server/Constants.java
deleted file mode 100644
index a25f019..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/Constants.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package ch.dissem.bitmessage.server;
-
-/**
- * Created by chrigu on 22.11.15.
- */
-public interface Constants {
- String ADMIN_LIST = "admins.conf";
- String CLIENT_LIST = "clients.conf";
-
- String WHITELIST = "whitelist.conf";
- String SHORTLIST = "shortlist.conf";
- String BLACKLIST = "blacklist.conf";
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/Converter.java b/src/main/java/ch/dissem/bitmessage/server/Converter.java
deleted file mode 100644
index 364831a..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/Converter.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.Plaintext;
-import ch.dissem.bitmessage.server.entities.Broadcasts;
-import ch.dissem.bitmessage.server.entities.Message;
-import ch.dissem.bitmessage.server.entities.Sender;
-import ch.dissem.bitmessage.utils.UnixTime;
-
-import java.util.Collection;
-
-public class Converter {
- public static Broadcasts broadcasts(BitmessageAddress sender, Collection messages) {
- Broadcasts result = new Broadcasts();
- result.sender = sender(sender);
- result.messages = new Message[messages.size()];
- int i = 0;
- for (Plaintext msg : messages) {
- result.messages[i] = message(msg);
- i++;
- }
- return result;
- }
-
- public static Broadcasts broadcasts(BitmessageAddress sender, Message... messages) {
- Broadcasts result = new Broadcasts();
- result.sender = sender(sender);
- result.messages = messages;
- return result;
- }
-
- public static Sender sender(BitmessageAddress sender) {
- Sender result = new Sender();
- result.address = sender.getAddress();
- result.alias = sender.toString();
- return result;
- }
-
- public static Message message(String subject, String body) {
- Message result = new Message();
- result.id = 0;
- result.received = UnixTime.now();
- result.subject = subject;
- result.body = body;
- return result;
- }
-
- public static Message message(Plaintext plaintext) {
- Message result = new Message();
- result.id = plaintext.getId();
- result.received = plaintext.getReceived();
- result.subject = plaintext.getSubject();
- result.body = plaintext.getText();
- return result;
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/JabitServerConfig.java b/src/main/java/ch/dissem/bitmessage/server/JabitServerConfig.java
deleted file mode 100644
index 6c7c52a..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/JabitServerConfig.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.BitmessageContext;
-import ch.dissem.bitmessage.cryptography.bc.BouncyCryptography;
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.payload.Pubkey;
-import ch.dissem.bitmessage.networking.nio.NioNetworkHandler;
-import ch.dissem.bitmessage.ports.*;
-import ch.dissem.bitmessage.repository.*;
-import ch.dissem.bitmessage.server.repository.ServerProofOfWorkRepository;
-import ch.dissem.bitmessage.utils.Singleton;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spring.web.plugins.Docket;
-
-import java.util.List;
-import java.util.Set;
-
-import static ch.dissem.bitmessage.server.Constants.*;
-import static java.util.stream.Collectors.toSet;
-
-@Configuration
-public class JabitServerConfig {
- private static final Logger LOG = LoggerFactory.getLogger(JabitServerConfig.class);
-
- public static final int SHORTLIST_SIZE = 5;
-
- @Value("${bitmessage.port}")
- private int port;
- @Value("${bitmessage.connection.ttl.hours}")
- private int connectionTTL;
- @Value("${bitmessage.connection.limit}")
- private int connectionLimit;
-
- @Value("${database.url}")
- private String dbUrl;
- @Value("${database.user}")
- private String dbUser;
- @Value("${database.password}")
- private String dbPassword;
-
- @Bean
- public JdbcConfig jdbcConfig() {
- return new JdbcConfig(dbUrl, dbUser, dbPassword);
- }
-
- @Bean
- public AddressRepository addressRepo() {
- return new JdbcAddressRepository(jdbcConfig());
- }
-
- @Bean
- public Inventory inventory() {
- return new JdbcInventory(jdbcConfig());
- }
-
- @Bean
- public MessageRepository messageRepo() {
- return new JdbcMessageRepository(jdbcConfig());
- }
-
- @Bean
- public ProofOfWorkRepository proofOfWorkRepo() {
- return new JdbcProofOfWorkRepository(jdbcConfig());
- }
-
- @Bean
- public NodeRegistry nodeRegistry() {
- return new JdbcNodeRegistry(jdbcConfig());
- }
-
- @Bean
- public NetworkHandler networkHandler() {
- return new NioNetworkHandler();
- }
-
- @Bean
- public Cryptography cryptography() {
- Cryptography cryptography = new BouncyCryptography();
- Singleton.initialize(cryptography); // needed for admins and clients
- return cryptography;
- }
-
- @Bean
- public BitmessageContext.Listener serverListener() {
- return new ServerListener(admins(), clients(), whitelist(), shortlist(), blacklist());
- }
-
- @Bean
- public ServerProofOfWorkRepository serverProofOfWorkRepository() {
- return new ServerProofOfWorkRepository(jdbcConfig());
- }
-
- @Bean
- public CustomCommandHandler commandHandler() {
- return new ProofOfWorkRequestHandler(serverProofOfWorkRepository(), clients());
- }
-
- @Bean
- public BitmessageContext bitmessageContext() {
- return new BitmessageContext.Builder()
- .addressRepo(addressRepo())
- .inventory(inventory())
- .messageRepo(messageRepo())
- .nodeRegistry(nodeRegistry())
- .powRepo(proofOfWorkRepo())
- .networkHandler(networkHandler())
- .listener(serverListener())
- .customCommandHandler(commandHandler())
- .cryptography(cryptography())
- .port(port)
- .connectionLimit(connectionLimit)
- .connectionTTL(connectionTTL)
- .build();
- }
-
- @Bean
- public Set admins() {
- cryptography();
- return Utils.readOrCreateList(
- ADMIN_LIST,
- "# Admins can send commands to the server.\n"
- ).stream().map(BitmessageAddress::new).collect(toSet());
- }
-
- @Bean
- public Set clients() {
- cryptography();
- return Utils.readOrCreateList(
- CLIENT_LIST,
- "# Clients may send incomplete objects for proof of work.\n"
- ).stream().map(BitmessageAddress::new).collect(toSet());
- }
-
- @Bean
- public Set whitelist() {
- return Utils.readOrCreateList(
- WHITELIST,
- "# If there are any Bitmessage addresses in the whitelist, only those will be shown.\n" +
- "# blacklist.conf will be ignored, but shortlist.conf will be applied to whitelisted addresses.\n"
- );
- }
-
- @Bean
- public Set shortlist() {
- return Utils.readOrCreateList(
- SHORTLIST,
- "# Broadcasts of these addresses will be restricted to the last " + SHORTLIST_SIZE + " entries.\n\n" +
- "# Time Service:\n" +
- "BM-BcbRqcFFSQUUmXFKsPJgVQPSiFA3Xash\n\n" +
- "# Q's Aktivlist:\n" +
- "BM-GtT7NLCCAu3HrT7dNTUTY9iDns92Z2ND\n"
- );
- }
-
- @Bean
- public Set blacklist() {
- return Utils.readOrCreateList(
- BLACKLIST,
- "# Bitmessage addresses in this file are being ignored and their broadcasts won't be returned.\n"
- );
- }
-
- @Bean
- public Docket api() {
- return new Docket(DocumentationType.SWAGGER_2)
- .select()
- .build();
- }
-
- @Bean
- public BitmessageAddress identity() {
- List identities = bitmessageContext().addresses().getIdentities();
- BitmessageAddress identity;
- if (identities.isEmpty()) {
- LOG.info("Creating new identity...");
- identity = bitmessageContext().createIdentity(false, Pubkey.Feature.DOES_ACK);
- LOG.info("Identity " + identity.getAddress() + " created.");
- } else {
- LOG.info("Identities:");
- identities.stream().map(BitmessageAddress::getAddress).forEach(LOG::info);
- identity = identities.get(0);
- if (identities.size() > 1) {
- LOG.info("Using " + identity);
- }
- }
- LOG.info("QR Code:\n" + Utils.qrCode(identity));
- return identity;
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/JabitServerController.java b/src/main/java/ch/dissem/bitmessage/server/JabitServerController.java
deleted file mode 100644
index 3812cc4..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/JabitServerController.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.BitmessageContext;
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.Plaintext;
-import ch.dissem.bitmessage.server.entities.Broadcasts;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.web.bind.annotation.CrossOrigin;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-import javax.inject.Inject;
-import java.util.List;
-import java.util.Set;
-
-import static ch.dissem.bitmessage.server.Converter.broadcasts;
-import static ch.dissem.bitmessage.server.Converter.message;
-import static org.springframework.web.bind.annotation.RequestMethod.GET;
-
-/**
- * @author Christian Basler
- */
-@CrossOrigin
-@RestController
-public class JabitServerController {
- private static final Logger LOG = LoggerFactory.getLogger(JabitServerController.class);
-
- private static final long HOUR = 60 * 60 * 1000l; // in ms
-
- private static final String CONFIG_FILE = "config.properties";
- private static final String PROPERTY_PORT = "port";
-
- private static final int SHORTLIST_SIZE = 5;
-
- @Resource
- private Set whitelist;
- @Resource
- private Set shortlist;
- @Resource
- private Set blacklist;
- @Inject
- private BitmessageAddress identity;
- @Inject
- private BitmessageContext ctx;
-
- @RequestMapping(value = "status", method = GET, produces = "application/json")
- public String status() {
- return ctx.status().toString();
- }
-
- @RequestMapping(value = "read/{broadcastAddress}", method = GET)
- public Broadcasts read(@PathVariable String broadcastAddress) {
- if ("test".equalsIgnoreCase(broadcastAddress)) {
- return broadcasts(
- new BitmessageAddress("BM-2cWhyaPxydemCeM8dWJUBmEo8iu7v2JptK"),
- message("Test", "This is a test message. The rest service is running."),
- message("Another Test", "And because it's such fun, a second message.")
- );
- }
-
- BitmessageAddress broadcaster = ctx.addresses().getAddress(broadcastAddress);
- if (broadcaster == null) {
- broadcaster = new BitmessageAddress(broadcastAddress);
- }
-
- if (!whitelist.isEmpty() && !whitelist.contains(broadcaster.getAddress())) {
- return broadcasts(broadcaster, message("Not Whitelisted", "Messages for " + broadcaster +
- " can't be shown, as the sender isn't on the whitelist."));
- }
- if (blacklist.contains(broadcaster.getAddress())) {
- return broadcasts(broadcaster, message("Blacklisted", "Unfortunately, " + broadcaster +
- " is on the blacklist, so it's messages can't be shown."));
- }
-
- if (!broadcaster.isSubscribed()) {
- ctx.addSubscribtion(broadcaster);
- }
- List messages = ctx.messages().findMessages(broadcaster);
- if (shortlist.contains(broadcaster.getAddress())) {
- while (messages.size() > SHORTLIST_SIZE) {
- ctx.messages().remove(messages.get(messages.size() - 1));
- messages.remove(messages.size() - 1);
- }
- }
- return broadcasts(broadcaster, messages);
- }
-
- @Scheduled(cron = "0 0 0 * * *")
- public void broadcastStatus() {
- ctx.broadcast(identity, "Status", ctx.status().toString());
- }
-
- @Scheduled(cron = "0 0 2 * * *")
- public void cleanup() {
- ctx.cleanup();
- }
-
- @PostConstruct
- public void setUp() {
- ctx.startup();
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.java b/src/main/java/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.java
deleted file mode 100644
index 79ff004..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.InternalContext;
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.CustomMessage;
-import ch.dissem.bitmessage.entity.MessagePayload;
-import ch.dissem.bitmessage.entity.valueobject.PrivateKey;
-import ch.dissem.bitmessage.exception.DecryptionFailedException;
-import ch.dissem.bitmessage.extensions.CryptoCustomMessage;
-import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest;
-import ch.dissem.bitmessage.ports.CustomCommandHandler;
-import ch.dissem.bitmessage.ports.ProofOfWorkEngine;
-import ch.dissem.bitmessage.server.repository.ServerProofOfWorkRepository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.stream.Collectors;
-
-import static ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest.Request.CALCULATING;
-import static ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest.Request.COMPLETE;
-import static ch.dissem.bitmessage.utils.UnixTime.DAY;
-
-/**
- * @author Christian Basler
- */
-public class ProofOfWorkRequestHandler implements CustomCommandHandler, InternalContext.ContextHolder {
- private final static Logger LOG = LoggerFactory.getLogger(ProofOfWorkRequestHandler.class);
-
- private final List decryptionKeys;
- private final ServerProofOfWorkRepository repo;
- private BitmessageAddress serverIdentity;
- private ProofOfWorkEngine engine;
- private InternalContext context;
-
- public ProofOfWorkRequestHandler(ServerProofOfWorkRepository repo, Collection clients) {
- this.repo = repo;
- decryptionKeys = clients.stream().map(BitmessageAddress::getPublicDecryptionKey).collect(Collectors.toList());
- new Timer().schedule(new TimerTask() {
- @Override
- public void run() {
- doMissingProofOfWork();
- }
- }, 15_000); // After 15 seconds
- new Timer().schedule(new TimerTask() {
- @Override
- public void run() {
- repo.cleanupTasks(7 * DAY);
- }
- }, 60_000, DAY * 1000); // First time after 1 minute, then daily
- }
-
- public void doMissingProofOfWork() {
- List incompleteTasks = repo.getIncompleteTasks();
- LOG.info("Doing POW for " + incompleteTasks.size() + " tasks.");
- for (ServerProofOfWorkRepository.Task task : incompleteTasks) {
- engine.calculateNonce(task.initialHash, task.target, repo::updateTask);
- }
- }
-
- @Override
- public MessagePayload handle(CustomMessage message) {
- CryptoCustomMessage cryptoMessage = CryptoCustomMessage.read(message,
- ProofOfWorkRequest::read);
- ProofOfWorkRequest request = decrypt(cryptoMessage);
- if (request == null) {
- return CustomMessage.error(
- "Unknown sender. Please ask the server's administrator to add you as a client. " +
- "For this he'll need your identity."
- );
- }
- switch (request.getRequest()) {
- case CALCULATE:
- if (!repo.hasTask(request.getInitialHash())) {
- repo.storeTask(request);
- // TODO: This is probably the place to do some book-keeping
- // if we want to bill our customers.
- engine.calculateNonce(request.getInitialHash(), request.getData(), repo::updateTask);
- return new CryptoCustomMessage<>(
- new ProofOfWorkRequest(getIdentity(), request.getInitialHash(), CALCULATING, new byte[0])
- );
- } else {
- byte[] nonce = repo.getNonce(request);
- CryptoCustomMessage response;
- if (nonce != null) {
- response = new CryptoCustomMessage<>(
- new ProofOfWorkRequest(getIdentity(), request.getInitialHash(), COMPLETE, nonce)
- );
- } else {
- response = new CryptoCustomMessage<>(
- new ProofOfWorkRequest(getIdentity(), request.getInitialHash(), CALCULATING, new byte[0])
- );
- }
- response.signAndEncrypt(serverIdentity, request.getSender().getPubkey().getEncryptionKey());
- return response;
- }
- }
- return null;
- }
-
- private BitmessageAddress getIdentity() {
- if (serverIdentity == null) {
- synchronized (this) {
- if (serverIdentity == null) {
- serverIdentity = context.getAddressRepository().getIdentities().stream().findFirst().orElseGet(() -> {
- final BitmessageAddress identity = new BitmessageAddress(new PrivateKey(
- false,
- context.getStreams()[0],
- InternalContext.NETWORK_NONCE_TRIALS_PER_BYTE,
- InternalContext.NETWORK_EXTRA_BYTES
- ));
- context.getAddressRepository().save(identity);
- return identity;
- });
- }
- }
- }
- return serverIdentity;
- }
-
- private ProofOfWorkRequest decrypt(CryptoCustomMessage cryptoMessage) {
- for (byte[] key : decryptionKeys) {
- try {
- return cryptoMessage.decrypt(key);
- } catch (DecryptionFailedException ignore) {
- }
- }
- return null;
- }
-
- @Override
- public void setContext(InternalContext context) {
- this.context = context;
- this.engine = context.getProofOfWorkEngine();
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/ServerListener.java b/src/main/java/ch/dissem/bitmessage/server/ServerListener.java
deleted file mode 100644
index 4959965..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/ServerListener.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.BitmessageContext;
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.Plaintext;
-import ch.dissem.bitmessage.entity.valueobject.extended.Message;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Scanner;
-
-import static ch.dissem.bitmessage.entity.Plaintext.Encoding.EXTENDED;
-import static ch.dissem.bitmessage.entity.Plaintext.Type.MSG;
-import static ch.dissem.bitmessage.server.Constants.*;
-
-/**
- * @author Christian Basler
- */
-public class ServerListener implements BitmessageContext.Listener.WithContext {
- private final static Logger LOG = LoggerFactory.getLogger(ServerListener.class);
-
- private final Collection admins;
- private final Collection clients;
-
- private final Collection whitelist;
- private final Collection shortlist;
- private final Collection blacklist;
-
- private BitmessageContext ctx;
- private BitmessageAddress identity;
-
- public ServerListener(Collection admins,
- Collection clients,
- Collection whitelist,
- Collection shortlist,
- Collection blacklist) {
- this.admins = admins;
- this.clients = clients;
- this.whitelist = whitelist;
- this.shortlist = shortlist;
- this.blacklist = blacklist;
- }
-
- @Override
- public void setContext(BitmessageContext ctx) {
- this.ctx = ctx;
- }
-
- private BitmessageAddress getIdentity() {
- if (identity == null) {
- List identities = ctx.addresses().getIdentities();
- if (!identities.isEmpty()) {
- identity = identities.get(0);
- }
- }
- return identity;
- }
-
- @Override
- public void receive(Plaintext message) {
- if (admins.contains(message.getFrom())) {
- String[] command = message.getSubject().trim().toLowerCase().split("\\s+");
- String data = message.getText();
- if (command.length == 1) {
- switch (command[0].toLowerCase()) {
- case "status":
- Plaintext.Builder response = new Plaintext.Builder(MSG);
- response.from(getIdentity());
- response.to(message.getFrom());
- if (message.getEncoding() == EXTENDED) {
- response.message(
- new Message.Builder()
- .subject("RE: status")
- .body(ctx.status().toString())
- .addParent(message)
- .build()
- );
- } else {
- response.message("RE: status", ctx.status().toString());
- }
- ctx.send(response.build());
- break;
- default:
- LOG.info("ignoring unknown command " + message.getSubject());
- }
- } else if (command.length == 2) {
- switch (command[1].toLowerCase()) {
- case "client":
- case "clients":
- updateUserList(CLIENT_LIST, clients, command[0], data);
- break;
- case "admin":
- case "admins":
- case "administrator":
- case "administrators":
- updateUserList(ADMIN_LIST, admins, command[0], data);
- break;
- case "whitelist":
- updateList(WHITELIST, whitelist, command[0], data);
- break;
- case "shortlist":
- updateList(SHORTLIST, shortlist, command[0], data);
- break;
- case "blacklist":
- updateList(BLACKLIST, blacklist, command[0], data);
- break;
- default:
- LOG.info("ignoring unknown command " + message.getSubject());
- }
- }
- }
- }
-
- private void updateUserList(String file, Collection list, String command, String data) {
- switch (command.toLowerCase()) {
- case "set":
- list.clear();
- case "add":
- Scanner scanner = new Scanner(data);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- try {
- list.add(new BitmessageAddress(line));
- } catch (Exception e) {
- LOG.info(command + " " + file + ": ignoring line: " + line);
- }
- }
- Utils.saveList(file, list.stream().map(BitmessageAddress::getAddress));
- break;
- case "remove":
- list.removeIf(address -> data.contains(address.getAddress()));
- Utils.saveList(file, list.stream().map(BitmessageAddress::getAddress));
- break;
- default:
- LOG.info("unknown command " + command + " on list " + file);
- }
- }
-
- private void updateList(String file, Collection list, String command, String data) {
- switch (command.toLowerCase()) {
- case "set":
- list.clear();
- case "add":
- Scanner scanner = new Scanner(data);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- try {
- list.add(new BitmessageAddress(line).getAddress());
- } catch (Exception e) {
- LOG.info(command + " " + file + ": ignoring line: " + line);
- }
- }
- Utils.saveList(file, list.stream());
- break;
- case "remove":
- list.removeIf(data::contains);
- Utils.saveList(file, list.stream());
- break;
- default:
- LOG.info("unknown command " + command + " on list " + file);
- }
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/Utils.java b/src/main/java/ch/dissem/bitmessage/server/Utils.java
deleted file mode 100644
index 8b9e0cd..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/Utils.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server;
-
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import com.google.zxing.WriterException;
-import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
-import com.google.zxing.qrcode.encoder.ByteMatrix;
-import com.google.zxing.qrcode.encoder.Encoder;
-import com.google.zxing.qrcode.encoder.QRCode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Scanner;
-import java.util.Set;
-import java.util.stream.Stream;
-
-public class Utils {
- private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
-
- public static Set readOrCreateList(String filename, String content) {
- try {
- File file = new File(filename);
- if (!file.exists()) {
- if (file.createNewFile()) {
- try (FileWriter fw = new FileWriter(file)) {
- fw.write(content);
- }
- }
- }
- return readList(file);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void saveList(String filename, Stream content) {
- try {
- File file = new File(filename);
- try (FileWriter fw = new FileWriter(file)) {
- content.forEach(l -> {
- try {
- fw.write(l);
- fw.write(System.lineSeparator());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- });
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static Set readList(File file) {
- Set result = new HashSet<>();
- try {
- Scanner scanner = new Scanner(file);
- while (scanner.hasNextLine()) {
- String line = scanner.nextLine().trim();
- if (line.startsWith("BM-")) {
- result.add(line);
- }
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- return result;
- }
-
- public static String qrCode(BitmessageAddress address) {
- StringBuilder link = new StringBuilder();
- link.append("bitmessage:");
- link.append(address.getAddress());
- if (address.getAlias() != null) {
- link.append("?label=").append(address.getAlias());
- }
- // This makes the QR code quite big, so it's not active. But sometimes it might be useful:
-// if (address.getPubkey() != null) {
-// link.append(address.getAlias() == null ? '?' : '&');
-// ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
-// address.getPubkey().writeUnencrypted(pubkey);
-// link.append("pubkey=").append(Base64.getUrlEncoder().encodeToString(pubkey.toByteArray()));
-// }
- QRCode code;
- try {
- code = Encoder.encode(link.toString(), ErrorCorrectionLevel.L, null);
- } catch (WriterException e) {
- LOG.error(e.getMessage(), e);
- return "";
- }
- ByteMatrix matrix = code.getMatrix();
- StringBuilder result = new StringBuilder();
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < matrix.getWidth() + 8; j++) {
- result.append('â–ˆ');
- }
- result.append('\n');
- }
- for (int i = 0; i < matrix.getHeight(); i += 2) {
- result.append("████");
- for (int j = 0; j < matrix.getWidth(); j++) {
- if (matrix.get(i, j) > 0) {
- if (matrix.getHeight() > i + 1 && matrix.get(i + 1, j) > 0) {
- result.append(' ');
- } else {
- result.append('â–„');
- }
- } else {
- if (matrix.getHeight() > i + 1 && matrix.get(i + 1, j) > 0) {
- result.append('â–€');
- } else {
- result.append('â–ˆ');
- }
- }
- }
- result.append("████\n");
- }
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < matrix.getWidth() + 8; j++) {
- result.append('â–ˆ');
- }
- result.append('\n');
- }
- return result.toString();
- }
-
- public static boolean zero(byte[] nonce) {
- for (byte b : nonce) {
- if (b != 0) return false;
- }
- return true;
- }
-}
diff --git a/src/main/java/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.java b/src/main/java/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.java
deleted file mode 100644
index 5e1c3f7..0000000
--- a/src/main/java/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright 2015 Christian Basler
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package ch.dissem.bitmessage.server.repository;
-
-import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest;
-import ch.dissem.bitmessage.repository.JdbcConfig;
-import ch.dissem.bitmessage.repository.JdbcHelper;
-import ch.dissem.bitmessage.utils.UnixTime;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * @author Christian Basler
- */
-public class ServerProofOfWorkRepository extends JdbcHelper {
-
- public ServerProofOfWorkRepository(JdbcConfig config) {
- super(config);
- }
-
- /**
- * client (can be removed once the new IV is returned)
- * IV (without nonce)
- * IV (with nonce, can be removed once the new IV is returned)
- * status: calculating, finished, confirmed
- * data (can be removed once POW calculation is done)
- */
- public void storeTask(ProofOfWorkRequest request) {
- try (Connection connection = config.getConnection()) {
- PreparedStatement ps = connection.prepareStatement(
- "INSERT INTO ProofOfWorkTask (initial_hash, client, target, timestamp) VALUES (?, ?, ?, ?)");
- ps.setBytes(1, request.getInitialHash());
- ps.setString(2, request.getSender().getAddress());
- ps.setBytes(3, request.getData());
- ps.setLong(4, UnixTime.now());
- ps.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void updateTask(byte[] initalHash, byte[] nonce) {
- try (Connection connection = config.getConnection()) {
- PreparedStatement ps = connection.prepareStatement(
- "UPDATE ProofOfWorkTask SET nonce = ? WHERE initial_hash = ?");
- ps.setBytes(1, nonce);
- ps.setBytes(2, initalHash);
- ps.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public byte[] getNonce(ProofOfWorkRequest request) {
- try (Connection connection = config.getConnection()) {
- PreparedStatement ps = connection.prepareStatement("SELECT nonce FROM ProofOfWorkTask WHERE initial_hash = ?");
- ps.setBytes(1, request.getInitialHash());
- ResultSet rs = ps.executeQuery();
- if (rs.next()) {
- return rs.getBytes(1);
- } else {
- return null;
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public boolean hasTask(byte[] initialHash) {
- try (Connection connection = config.getConnection()) {
- PreparedStatement ps = connection.prepareStatement("SELECT count(1) FROM ProofOfWorkTask WHERE initial_hash = ?");
- ps.setBytes(1, initialHash);
- ResultSet rs = ps.executeQuery();
- rs.next();
- return rs.getInt(1) > 0;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public List getIncompleteTasks() {
- try (Connection connection = config.getConnection()) {
- List result = new LinkedList<>();
- ResultSet rs = connection.createStatement().executeQuery(
- "SELECT initial_hash, target FROM ProofOfWorkTask WHERE nonce IS NULL");
- while (rs.next()) {
- result.add(new Task(
- rs.getBytes(1),
- rs.getBytes(2)
- ));
- }
- return result;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void cleanupTasks(long ageInSeconds) {
- try (Connection connection = config.getConnection()) {
- PreparedStatement ps = connection.prepareStatement(
- "DELETE FROM ProofOfWorkTask WHERE timestamp < ?");
- ps.setLong(1, UnixTime.now() - ageInSeconds);
- ps.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static class Task {
- public final byte[] initialHash;
- public final byte[] target;
-
- private Task(byte[] initialHash, byte[] target) {
- this.initialHash = initialHash;
- this.target = target;
- }
- }
-}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/Constants.kt b/src/main/kotlin/ch/dissem/bitmessage/server/Constants.kt
new file mode 100644
index 0000000..ad5a7ae
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/Constants.kt
@@ -0,0 +1,13 @@
+package ch.dissem.bitmessage.server
+
+/**
+ * Created by chrigu on 22.11.15.
+ */
+object Constants {
+ val ADMIN_LIST = "admins.conf"
+ val CLIENT_LIST = "clients.conf"
+
+ val WHITELIST = "whitelist.conf"
+ val SHORTLIST = "shortlist.conf"
+ val BLACKLIST = "blacklist.conf"
+}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/Converter.kt b/src/main/kotlin/ch/dissem/bitmessage/server/Converter.kt
new file mode 100644
index 0000000..500d329
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/Converter.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import ch.dissem.bitmessage.entity.Plaintext
+import ch.dissem.bitmessage.server.entities.Broadcasts
+import ch.dissem.bitmessage.server.entities.Message
+import ch.dissem.bitmessage.server.entities.Sender
+import ch.dissem.bitmessage.utils.UnixTime
+
+object Converter {
+ fun broadcasts(sender: BitmessageAddress, messages: Collection) = Broadcasts().also {
+ it.sender = sender(sender)
+ it.messages = messages.map { message(it) }.toTypedArray()
+ }
+
+ fun broadcasts(sender: BitmessageAddress, vararg messages: Message) = Broadcasts().also {
+ it.sender = sender(sender)
+ it.messages = arrayOf(*messages)
+ }
+
+ fun sender(sender: BitmessageAddress) = Sender().apply {
+ address = sender.address
+ alias = sender.toString()
+ }
+
+ fun message(subject: String, body: String) = Message().also {
+ it.id = 0
+ it.received = UnixTime.now
+ it.subject = subject
+ it.body = body
+ }
+
+ fun message(plaintext: Plaintext) = Message().apply {
+ id = plaintext.id
+ received = plaintext.sent
+ subject = plaintext.subject
+ body = plaintext.text
+ }
+}
diff --git a/src/main/java/ch/dissem/bitmessage/server/JabitServerApplication.java b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerApplication.kt
similarity index 60%
rename from src/main/java/ch/dissem/bitmessage/server/JabitServerApplication.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/JabitServerApplication.kt
index 740d90f..93406c5 100644
--- a/src/main/java/ch/dissem/bitmessage/server/JabitServerApplication.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerApplication.kt
@@ -14,19 +14,25 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server;
+package ch.dissem.bitmessage.server
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.annotation.ComponentScan;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
+import org.springframework.boot.SpringApplication
+import org.springframework.boot.autoconfigure.SpringBootApplication
+import org.springframework.context.annotation.ComponentScan
+import org.springframework.scheduling.annotation.EnableScheduling
+import springfox.documentation.swagger2.annotations.EnableSwagger2
-@SpringBootApplication
@EnableSwagger2
-@ComponentScan(basePackageClasses = JabitServerApplication.class)
-public class JabitServerApplication {
+@EnableScheduling
+@SpringBootApplication
+@ComponentScan(basePackageClasses = [JabitServerApplication::class])
+class JabitServerApplication {
- public static void main(String[] args) {
- SpringApplication.run(JabitServerApplication.class, args);
+ companion object {
+ @JvmStatic
+ fun main(args: Array) {
+ SpringApplication.run(JabitServerApplication::class.java, *args)
+ }
}
+
}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerConfig.kt b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerConfig.kt
new file mode 100644
index 0000000..b5f3665
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerConfig.kt
@@ -0,0 +1,193 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.BitmessageContext
+import ch.dissem.bitmessage.cryptography.bc.BouncyCryptography
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import ch.dissem.bitmessage.entity.payload.Pubkey
+import ch.dissem.bitmessage.networking.nio.NioNetworkHandler
+import ch.dissem.bitmessage.repository.*
+import ch.dissem.bitmessage.server.Constants.ADMIN_LIST
+import ch.dissem.bitmessage.server.Constants.BLACKLIST
+import ch.dissem.bitmessage.server.Constants.CLIENT_LIST
+import ch.dissem.bitmessage.server.Constants.SHORTLIST
+import ch.dissem.bitmessage.server.Constants.WHITELIST
+import ch.dissem.bitmessage.server.repository.ServerProofOfWorkRepository
+import ch.dissem.bitmessage.utils.Singleton
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.DependsOn
+import springfox.documentation.spi.DocumentationType
+import springfox.documentation.spring.web.plugins.Docket
+
+@Configuration
+class JabitServerConfig {
+
+ @Value("\${bitmessage.port}")
+ private val port: Int = 0
+ @Value("\${bitmessage.connection.ttl.hours}")
+ private val connectionTTL: Long = 0
+ @Value("\${bitmessage.connection.limit}")
+ private val connectionLimit: Int = 0
+
+ @Value("\${database.url}")
+ private lateinit var dbUrl: String
+ @Value("\${database.user}")
+ private lateinit var dbUser: String
+ @Value("\${database.password}")
+ private var dbPassword: String? = null
+
+ @Bean
+ fun jdbcConfig() = JdbcConfig(dbUrl, dbUser, dbPassword)
+
+ @Bean
+ fun addressRepo() = JdbcAddressRepository(jdbcConfig())
+
+ @Bean
+ fun inventory() = JdbcInventory(jdbcConfig())
+
+ @Bean
+ fun labelRepo() = JdbcLabelRepository(jdbcConfig())
+
+ @Bean
+ fun messageRepo() = JdbcMessageRepository(jdbcConfig())
+
+ @Bean
+ fun proofOfWorkRepo() = JdbcProofOfWorkRepository(jdbcConfig())
+
+ @Bean
+ fun nodeRegistry() = JdbcNodeRegistry(jdbcConfig())
+
+ @Bean
+ fun networkHandler() = NioNetworkHandler()
+
+ @Bean
+ fun cryptography() = BouncyCryptography().also {
+ Singleton.initialize(it) // needed for admins and clients
+ }
+
+ @Bean
+ fun serverListener(): BitmessageContext.Listener =
+ ServerListener(
+ admins(), clients(),
+ whitelist(), shortlist(), blacklist()
+ )
+
+ @Bean
+ fun serverProofOfWorkRepository() = ServerProofOfWorkRepository(jdbcConfig())
+
+ @Bean
+ fun commandHandler() = ProofOfWorkRequestHandler(serverProofOfWorkRepository(), clients())
+
+ @Bean
+ fun bitmessageContext() = BitmessageContext.build {
+ addressRepo = addressRepo()
+ inventory = inventory()
+ labelRepo = labelRepo()
+ messageRepo = messageRepo()
+ nodeRegistry = nodeRegistry()
+ proofOfWorkRepo = proofOfWorkRepo()
+ networkHandler = networkHandler()
+ listener = serverListener()
+ customCommandHandler = commandHandler()
+ cryptography = cryptography()
+ preferences.port = port
+ preferences.connectionLimit = connectionLimit
+ preferences.connectionTTL = connectionTTL
+ }
+
+ @Bean
+ @DependsOn("cryptography")
+ fun admins() = Utils.readOrCreateList(
+ ADMIN_LIST,
+ """# Admins can send commands to the server.
+ |
+ """.trimMargin()
+ ).map { BitmessageAddress(it) }.toMutableSet()
+
+ @Bean
+ @DependsOn("cryptography")
+ fun clients() = Utils.readOrCreateList(
+ CLIENT_LIST,
+ "# Clients may send incomplete objects for proof of work.\n"
+ ).map { BitmessageAddress(it) }.toMutableSet()
+
+ @Bean
+ fun whitelist() = Utils.readOrCreateList(
+ WHITELIST,
+ """# If there are any Bitmessage addresses in the whitelist, only those will be shown.
+ |# blacklist.conf will be ignored, but shortlist.conf will be applied to whitelisted addresses.
+ |
+ """.trimMargin()
+ )
+
+ @Bean
+ fun shortlist() = Utils.readOrCreateList(
+ SHORTLIST,
+ """"# Broadcasts of these addresses will be restricted to the last $SHORTLIST_SIZE entries.
+ |
+ |# Time Service:
+ |BM-BcbRqcFFSQUUmXFKsPJgVQPSiFA3Xash
+ |
+ |# Q's Aktivlist:
+ |BM-GtT7NLCCAu3HrT7dNTUTY9iDns92Z2ND
+ |
+ """.trimMargin()
+ )
+
+ @Bean
+ fun blacklist() = Utils.readOrCreateList(
+ BLACKLIST,
+ """# Bitmessage addresses in this file are being ignored and their broadcasts won't be returned.
+ |
+ """.trimMargin()
+ )
+
+ @Bean
+ fun api(): Docket = Docket(DocumentationType.SWAGGER_2)
+ .select()
+ .build()
+
+ @Bean
+ fun identity(): BitmessageAddress {
+ val identities = bitmessageContext().addresses.getIdentities()
+ val identity: BitmessageAddress
+ if (identities.isEmpty()) {
+ LOG.info("Creating new identity...")
+ identity = bitmessageContext().createIdentity(false, Pubkey.Feature.DOES_ACK)
+ LOG.info("Identity " + identity.address + " created.")
+ } else {
+ LOG.info("Identities:")
+ identities.forEach { LOG.info(it.address) }
+ identity = identities[0]
+ if (identities.size > 1) {
+ LOG.info("Using " + identity)
+ }
+ }
+ LOG.info("QR Code:\n" + Utils.qrCode(identity))
+ return identity
+ }
+
+ companion object {
+ private val LOG = LoggerFactory.getLogger(JabitServerConfig::class.java)
+
+ val SHORTLIST_SIZE = 5
+ }
+}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerController.kt b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerController.kt
new file mode 100644
index 0000000..7a687d2
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/JabitServerController.kt
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.BitmessageContext
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import ch.dissem.bitmessage.server.Converter.broadcasts
+import ch.dissem.bitmessage.server.Converter.message
+import ch.dissem.bitmessage.server.entities.Broadcasts
+import org.springframework.scheduling.annotation.Scheduled
+import org.springframework.web.bind.annotation.CrossOrigin
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod.GET
+import org.springframework.web.bind.annotation.RestController
+import javax.annotation.PostConstruct
+import javax.annotation.Resource
+import javax.inject.Inject
+
+/**
+ * @author Christian Basler
+ */
+@CrossOrigin
+@RestController
+class JabitServerController {
+
+ @Resource
+ private lateinit var whitelist: Set
+ @Resource
+ private lateinit var shortlist: Set
+ @Resource
+ private lateinit var blacklist: Set
+ @Inject
+ private lateinit var identity: BitmessageAddress
+ @Inject
+ private lateinit var ctx: BitmessageContext
+
+ @RequestMapping(value = ["identity"], method = [GET], produces = ["application/json"])
+ fun identity() = """{
+ "address": "${identity.address}",
+ "uri": "${Utils.getURL(identity, true)}"
+}"""
+
+
+ @RequestMapping(value = ["status"], method = [GET], produces = ["application/json"])
+ fun status() = "{${ctx.status()}}"
+
+ @RequestMapping(value = ["read/{broadcastAddress}"], method = [GET])
+ fun read(@PathVariable broadcastAddress: String): Broadcasts {
+ if ("test".equals(broadcastAddress, ignoreCase = true)) {
+ return broadcasts(
+ BitmessageAddress("BM-2cWhyaPxydemCeM8dWJUBmEo8iu7v2JptK"),
+ message("Test", "This is a test message. The rest service is running."),
+ message("Another Test", "And because it's such fun, a second message.")
+ )
+ }
+
+ var broadcaster = ctx.addresses.getAddress(broadcastAddress)
+ if (broadcaster == null) {
+ broadcaster = BitmessageAddress(broadcastAddress)
+ }
+
+ if (!whitelist.isEmpty() && !whitelist.contains(broadcaster.address)) {
+ return broadcasts(broadcaster, message("Not Whitelisted", "Messages for " + broadcaster +
+ " can't be shown, as the sender isn't on the whitelist."))
+ }
+ if (blacklist.contains(broadcaster.address)) {
+ return broadcasts(broadcaster, message("Blacklisted", "Unfortunately, " + broadcaster +
+ " is on the blacklist, so it's messages can't be shown."))
+ }
+
+ if (!broadcaster.isSubscribed) {
+ ctx.addSubscribtion(broadcaster)
+ }
+ val messages = ctx.messages.findMessages(broadcaster)
+ return if (shortlist.contains(broadcaster.address) && messages.size > SHORTLIST_SIZE) {
+ messages.listIterator(SHORTLIST_SIZE).forEach { ctx.messages.remove(it) }
+ broadcasts(broadcaster, messages.subList(0, SHORTLIST_SIZE))
+ } else {
+ broadcasts(broadcaster, messages)
+ }
+ }
+
+ @Scheduled(cron = "0 0 0 * * *")
+ fun broadcastStatus() = ctx.broadcast(identity, "Status", ctx.status().toString())
+
+ @Scheduled(cron = "0 0 2 * * *")
+ fun cleanup() = ctx.cleanup()
+
+ @PostConstruct
+ fun setUp() = ctx.startup()
+
+ companion object {
+ private val SHORTLIST_SIZE = 5
+ }
+}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.kt b/src/main/kotlin/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.kt
new file mode 100644
index 0000000..4b5835b
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/ProofOfWorkRequestHandler.kt
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.InternalContext
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import ch.dissem.bitmessage.entity.CustomMessage
+import ch.dissem.bitmessage.entity.MessagePayload
+import ch.dissem.bitmessage.entity.valueobject.PrivateKey
+import ch.dissem.bitmessage.exception.DecryptionFailedException
+import ch.dissem.bitmessage.extensions.CryptoCustomMessage
+import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest
+import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest.Request.CALCULATING
+import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest.Request.COMPLETE
+import ch.dissem.bitmessage.ports.CustomCommandHandler
+import ch.dissem.bitmessage.ports.ProofOfWorkEngine
+import ch.dissem.bitmessage.server.repository.ServerProofOfWorkRepository
+import ch.dissem.bitmessage.utils.UnixTime.DAY
+import org.slf4j.LoggerFactory
+import java.util.*
+import kotlin.concurrent.schedule
+
+/**
+ * @author Christian Basler
+ */
+class ProofOfWorkRequestHandler(private val repo: ServerProofOfWorkRepository, clients: Collection) : CustomCommandHandler, InternalContext.ContextHolder {
+
+ private val decryptionKeys = clients.map { it.publicDecryptionKey }
+ private lateinit var engine: ProofOfWorkEngine
+ private lateinit var context: InternalContext
+
+ private val identity: BitmessageAddress by lazy {
+ context.addressRepository.getIdentities().firstOrNull() ?: BitmessageAddress(PrivateKey(
+ false,
+ context.streams[0],
+ InternalContext.NETWORK_NONCE_TRIALS_PER_BYTE,
+ InternalContext.NETWORK_EXTRA_BYTES
+ )).also { context.addressRepository.save(it) }
+ }
+
+ init {
+ Timer().schedule(15000) {
+ doMissingProofOfWork()
+ } // wait 15 seconds
+ Timer().schedule(60000, DAY * 1000) {
+ repo.cleanupTasks(7 * DAY)
+ } // First time after 1 minute, then daily
+ }
+
+ fun doMissingProofOfWork() {
+ val incompleteTasks = repo.getIncompleteTasks()
+ LOG.info("Doing POW for ${incompleteTasks.size} tasks.")
+ for (task in incompleteTasks) {
+ engine.calculateNonce(task.initialHash, task.target) { initalHash, nonce -> repo.updateTask(initalHash, nonce) }
+ }
+ }
+
+ override fun handle(request: CustomMessage): MessagePayload? {
+ val cryptoMessage = CryptoCustomMessage.read(request) { client, input ->
+ ProofOfWorkRequest.read(client, input)
+ }
+ val decryptedRequest = decrypt(cryptoMessage) ?: return CustomMessage.error(
+ "Unknown sender. Please ask the server's administrator to add you as a client. For this he'll need your identity."
+ )
+ when (decryptedRequest.request) {
+ ProofOfWorkRequest.Request.CALCULATE -> {
+ if (!repo.hasTask(decryptedRequest.initialHash)) {
+ repo.storeTask(decryptedRequest)
+ // TODO: This is probably the place to do some book-keeping
+ // if we want to bill our customers.
+ engine.calculateNonce(decryptedRequest.initialHash, decryptedRequest.data) { initalHash, nonce -> repo.updateTask(initalHash, nonce) }
+ return CryptoCustomMessage(
+ ProofOfWorkRequest(identity, decryptedRequest.initialHash, CALCULATING, ByteArray(0))
+ )
+ } else {
+ val nonce = repo.getNonce(decryptedRequest)
+ return CryptoCustomMessage(
+ if (nonce != null) {
+ ProofOfWorkRequest(identity, decryptedRequest.initialHash, COMPLETE, nonce)
+ } else {
+ ProofOfWorkRequest(identity, decryptedRequest.initialHash, CALCULATING, ByteArray(0))
+ }
+ ).apply { signAndEncrypt(identity, decryptedRequest.sender.pubkey!!.encryptionKey) }
+ }
+ }
+ else -> return null
+ }
+ }
+
+ private fun decrypt(cryptoMessage: CryptoCustomMessage): ProofOfWorkRequest? {
+ for (key in decryptionKeys) {
+ try {
+ return cryptoMessage.decrypt(key)
+ } catch (_: DecryptionFailedException) {
+ }
+ }
+ return null
+ }
+
+ override fun setContext(context: InternalContext) {
+ this.context = context
+ this.engine = context.proofOfWorkEngine
+ }
+
+ companion object {
+ private val LOG = LoggerFactory.getLogger(ProofOfWorkRequestHandler::class.java)
+ }
+}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/ServerListener.kt b/src/main/kotlin/ch/dissem/bitmessage/server/ServerListener.kt
new file mode 100644
index 0000000..0a58a5b
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/ServerListener.kt
@@ -0,0 +1,171 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.BitmessageContext
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import ch.dissem.bitmessage.entity.Plaintext
+import ch.dissem.bitmessage.entity.Plaintext.Encoding.EXTENDED
+import ch.dissem.bitmessage.entity.Plaintext.Type.MSG
+import ch.dissem.bitmessage.entity.valueobject.extended.Message
+import ch.dissem.bitmessage.server.Constants.ADMIN_LIST
+import ch.dissem.bitmessage.server.Constants.BLACKLIST
+import ch.dissem.bitmessage.server.Constants.CLIENT_LIST
+import ch.dissem.bitmessage.server.Constants.SHORTLIST
+import ch.dissem.bitmessage.server.Constants.WHITELIST
+import org.slf4j.LoggerFactory
+import java.util.*
+
+/**
+ * @author Christian Basler
+ */
+class ServerListener(private val admins: MutableCollection,
+ private val clients: MutableCollection,
+ private val whitelist: MutableCollection,
+ private val shortlist: MutableCollection,
+ private val blacklist: MutableCollection) : BitmessageContext.Listener.WithContext {
+
+ private lateinit var ctx: BitmessageContext
+ private val identity: BitmessageAddress by lazy {
+ val identities = ctx.addresses.getIdentities()
+ if (identities.isEmpty()) {
+ ctx.createIdentity(false)
+ } else {
+ identities[0]
+ }
+ }
+
+ override fun setContext(ctx: BitmessageContext) {
+ this.ctx = ctx
+ }
+
+ override fun receive(plaintext: Plaintext) {
+ if (admins.contains(plaintext.from)) {
+ val command = plaintext.subject!!.trim { it <= ' ' }.toLowerCase().split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
+ val data = plaintext.text
+ if (command.size == 1) {
+ when (command[0].toLowerCase()) {
+ "status" -> {
+ val response = Plaintext.Builder(MSG)
+ response.from(identity)
+ response.to(plaintext.from)
+ if (plaintext.encoding == EXTENDED) {
+ response.message(
+ Message.Builder()
+ .subject("RE: status")
+ .body(ctx.status().toString())
+ .addParent(plaintext)
+ .build()
+ )
+ } else {
+ response.message("RE: status", ctx.status().toString())
+ }
+ ctx.send(response.build())
+ }
+ else -> LOG.info("ignoring unknown command " + plaintext.subject!!)
+ }
+ } else if (command.size == 2) {
+ when (command[1].toLowerCase()) {
+ "client", "clients" -> updateUserList(CLIENT_LIST, clients, command[0], data)
+ "admin", "admins", "administrator", "administrators" -> updateUserList(ADMIN_LIST, admins, command[0], data)
+ "whitelist" -> updateList(WHITELIST, whitelist, command[0], data)
+ "shortlist" -> updateList(SHORTLIST, shortlist, command[0], data)
+ "blacklist" -> updateList(BLACKLIST, blacklist, command[0], data)
+ else -> LOG.info("ignoring unknown command " + plaintext.subject!!)
+ }
+ }
+ }
+ }
+
+ private fun updateUserList(file: String, list: MutableCollection, command: String, data: String?) {
+ when (command.toLowerCase()) {
+ "set" -> {
+ list.clear()
+ val scanner = Scanner(data!!)
+ while (scanner.hasNextLine()) {
+ val line = scanner.nextLine()
+ try {
+ list.add(BitmessageAddress(line))
+ } catch (e: Exception) {
+ LOG.info("$command $file: ignoring line: $line")
+ }
+
+ }
+ Utils.saveList(file, list.map { it.address })
+ }
+ "add" -> {
+ val scanner = Scanner(data!!)
+ while (scanner.hasNextLine()) {
+ val line = scanner.nextLine()
+ try {
+ list.add(BitmessageAddress(line))
+ } catch (e: Exception) {
+ LOG.info("$command $file: ignoring line: $line")
+ }
+
+ }
+ Utils.saveList(file, list.map { it.address })
+ }
+ "remove" -> {
+ list.removeIf { address -> data!!.contains(address.address) }
+ Utils.saveList(file, list.map { it.address })
+ }
+ else -> LOG.info("unknown command $command on list $file")
+ }
+ }
+
+ private fun updateList(file: String, list: MutableCollection, command: String, data: String?) {
+ when (command.toLowerCase()) {
+ "set" -> {
+ list.clear()
+ val scanner = Scanner(data!!)
+ while (scanner.hasNextLine()) {
+ val line = scanner.nextLine()
+ try {
+ list.add(BitmessageAddress(line).address)
+ } catch (e: Exception) {
+ LOG.info("$command $file: ignoring line: $line")
+ }
+
+ }
+ Utils.saveList(file, list)
+ }
+ "add" -> {
+ val scanner = Scanner(data!!)
+ while (scanner.hasNextLine()) {
+ val line = scanner.nextLine()
+ try {
+ list.add(BitmessageAddress(line).address)
+ } catch (e: Exception) {
+ LOG.info("$command $file: ignoring line: $line")
+ }
+
+ }
+ Utils.saveList(file, list)
+ }
+ "remove" -> {
+ list.removeAll { data!!.contains(it) }
+ Utils.saveList(file, list)
+ }
+ else -> LOG.info("unknown command $command on list $file")
+ }
+ }
+
+ companion object {
+ private val LOG = LoggerFactory.getLogger(ServerListener::class.java)
+ }
+}
diff --git a/src/main/java/ch/dissem/bitmessage/server/ServletInitializer.java b/src/main/kotlin/ch/dissem/bitmessage/server/ServletInitializer.kt
similarity index 65%
rename from src/main/java/ch/dissem/bitmessage/server/ServletInitializer.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/ServletInitializer.kt
index 5f4bdf2..0a348aa 100644
--- a/src/main/java/ch/dissem/bitmessage/server/ServletInitializer.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/ServletInitializer.kt
@@ -14,16 +14,15 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server;
+package ch.dissem.bitmessage.server
-import org.springframework.boot.builder.SpringApplicationBuilder;
-import org.springframework.boot.context.web.SpringBootServletInitializer;
+import org.springframework.boot.builder.SpringApplicationBuilder
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
-public class ServletInitializer extends SpringBootServletInitializer {
+class ServletInitializer : SpringBootServletInitializer() {
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(JabitServerApplication.class);
- }
+ override fun configure(application: SpringApplicationBuilder): SpringApplicationBuilder {
+ return application.sources(JabitServerApplication::class.java)
+ }
}
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/Utils.kt b/src/main/kotlin/ch/dissem/bitmessage/server/Utils.kt
new file mode 100644
index 0000000..6676dc6
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/Utils.kt
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server
+
+import ch.dissem.bitmessage.entity.BitmessageAddress
+import com.google.zxing.WriterException
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
+import com.google.zxing.qrcode.encoder.Encoder
+import com.google.zxing.qrcode.encoder.QRCode
+import org.slf4j.LoggerFactory
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.FileWriter
+import java.nio.file.Files
+import java.util.*
+
+object Utils {
+ private val LOG = LoggerFactory.getLogger(Utils::class.java)
+
+ fun readOrCreateList(filename: String, content: String): MutableSet {
+ val file = File(filename).apply {
+ if (!exists()) {
+ if (createNewFile()) {
+ FileWriter(this).use { fw -> fw.write(content) }
+ }
+ }
+ }
+ return readList(file)
+ }
+
+ fun saveList(filename: String, content: Collection) {
+ FileWriter(filename).use { fw ->
+ content.forEach { l ->
+ fw.write(l)
+ fw.write(System.lineSeparator())
+ }
+ }
+ }
+
+ fun readList(file: File) = Files.readAllLines(file.toPath())
+ .map { it.trim { it <= ' ' } }
+ .filter { it.startsWith("BM-") }
+ .toMutableSet()
+
+ fun getURL(address: BitmessageAddress, includeKey: Boolean): String {
+ val attributes = mutableListOf()
+ if (address.alias != null) {
+ attributes.add("label=${address.alias}")
+ }
+ if (includeKey) {
+ address.pubkey?.let { pubkey ->
+ val out = ByteArrayOutputStream()
+ pubkey.writer().writeUnencrypted(out)
+ attributes.add("pubkey=${Base64.getUrlEncoder().encodeToString(out.toByteArray())}")
+ }
+ }
+
+ return if (attributes.isEmpty()) {
+ "bitmessage:${address.address}"
+ } else {
+ "bitmessage:${address.address}?${attributes.joinToString(separator = "&")}"
+ }
+ }
+
+ fun qrCode(address: BitmessageAddress): String {
+ val code: QRCode
+ try {
+ code = Encoder.encode(getURL(address, false), ErrorCorrectionLevel.L, null)
+ } catch (e: WriterException) {
+ LOG.error(e.message, e)
+ return ""
+ }
+
+ val matrix = code.matrix
+ val result = StringBuilder()
+ for (i in 0..1) {
+ for (j in 0 until matrix.width + 8) {
+ result.append('â–ˆ')
+ }
+ result.append('\n')
+ }
+ run {
+ var i = 0
+ while (i < matrix.height) {
+ result.append("████")
+ for (j in 0 until matrix.width) {
+ if (matrix.get(i, j) > 0) {
+ if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) {
+ result.append(' ')
+ } else {
+ result.append('â–„')
+ }
+ } else {
+ if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) {
+ result.append('â–€')
+ } else {
+ result.append('â–ˆ')
+ }
+ }
+ }
+ result.append("████\n")
+ i += 2
+ }
+ }
+ for (i in 0..1) {
+ for (j in 0 until matrix.width + 8) {
+ result.append('â–ˆ')
+ }
+ result.append('\n')
+ }
+ return result.toString()
+ }
+
+ fun zero(nonce: ByteArray) = nonce.none { it.toInt() != 0 }
+}
diff --git a/src/main/java/ch/dissem/bitmessage/server/entities/Broadcasts.java b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Broadcasts.kt
similarity index 71%
rename from src/main/java/ch/dissem/bitmessage/server/entities/Broadcasts.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/entities/Broadcasts.kt
index 1349a0f..07d3153 100644
--- a/src/main/java/ch/dissem/bitmessage/server/entities/Broadcasts.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Broadcasts.kt
@@ -14,17 +14,12 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server.entities;
-
-import ch.dissem.bitmessage.entity.BitmessageAddress;
-import ch.dissem.bitmessage.entity.Plaintext;
-
-import java.util.Collection;
+package ch.dissem.bitmessage.server.entities
/**
* JSON representation for the broadcasts of a specific sender
*/
-public class Broadcasts {
- public Sender sender;
- public Message[] messages;
-}
+data class Broadcasts(
+ var sender: Sender? = null,
+ var messages: Array = emptyArray()
+)
diff --git a/src/main/java/ch/dissem/bitmessage/server/entities/Message.java b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Message.kt
similarity index 67%
rename from src/main/java/ch/dissem/bitmessage/server/entities/Message.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/entities/Message.kt
index 07038d6..ceaa5b0 100644
--- a/src/main/java/ch/dissem/bitmessage/server/entities/Message.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Message.kt
@@ -14,20 +14,14 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server.entities;
-
-import ch.dissem.bitmessage.entity.Plaintext;
-import ch.dissem.bitmessage.utils.UnixTime;
-
-import java.time.Instant;
-import java.time.ZonedDateTime;
+package ch.dissem.bitmessage.server.entities
/**
* JSON representation for plaintext messages
*/
-public class Message {
- public Object id;
- public Long received;
- public String subject;
- public String body;
-}
+data class Message(
+ var id: Any? = null,
+ var received: Long? = null,
+ var subject: String? = null,
+ var body: String? = null
+)
diff --git a/src/main/java/ch/dissem/bitmessage/server/entities/Sender.java b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Sender.kt
similarity index 78%
rename from src/main/java/ch/dissem/bitmessage/server/entities/Sender.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/entities/Sender.kt
index b61833c..24df62e 100644
--- a/src/main/java/ch/dissem/bitmessage/server/entities/Sender.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Sender.kt
@@ -14,14 +14,12 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server.entities;
-
-import ch.dissem.bitmessage.entity.BitmessageAddress;
+package ch.dissem.bitmessage.server.entities
/**
* JSON representation for a BitmessageAddress
*/
-public class Sender {
- public String address;
- public String alias;
-}
+data class Sender(
+ var address: String? = null,
+ var alias: String? = null
+)
diff --git a/src/main/java/ch/dissem/bitmessage/server/entities/Update.java b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Update.kt
similarity index 71%
rename from src/main/java/ch/dissem/bitmessage/server/entities/Update.java
rename to src/main/kotlin/ch/dissem/bitmessage/server/entities/Update.kt
index 3aebada..9e898d3 100644
--- a/src/main/java/ch/dissem/bitmessage/server/entities/Update.java
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/entities/Update.kt
@@ -14,17 +14,9 @@
* limitations under the License.
*/
-package ch.dissem.bitmessage.server.entities;
+package ch.dissem.bitmessage.server.entities
/**
* @author Christian Basler
*/
-public class Update {
- public final T oldValue;
- public final T newValue;
-
- public Update(T oldValue, T newValue) {
- this.oldValue = oldValue;
- this.newValue = newValue;
- }
-}
+data class Update(val oldValue: T, val newValue: T)
diff --git a/src/main/kotlin/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.kt b/src/main/kotlin/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.kt
new file mode 100644
index 0000000..0fbcfdb
--- /dev/null
+++ b/src/main/kotlin/ch/dissem/bitmessage/server/repository/ServerProofOfWorkRepository.kt
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2015 Christian Basler
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package ch.dissem.bitmessage.server.repository
+
+import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest
+import ch.dissem.bitmessage.repository.JdbcConfig
+import ch.dissem.bitmessage.repository.JdbcHelper
+import ch.dissem.bitmessage.utils.UnixTime
+import java.util.*
+
+/**
+ * @author Christian Basler
+ */
+class ServerProofOfWorkRepository(config: JdbcConfig) : JdbcHelper(config) {
+
+ fun getIncompleteTasks(): List {
+ config.getConnection().use { connection ->
+ val result = LinkedList()
+ val rs = connection.createStatement().executeQuery(
+ "SELECT initial_hash, target FROM ProofOfWorkTask WHERE nonce IS NULL")
+ while (rs.next()) {
+ result.add(Task(
+ rs.getBytes(1),
+ rs.getBytes(2)
+ ))
+ }
+ return result
+ }
+ }
+
+ /**
+ * client (can be removed once the new IV is returned)
+ * IV (without nonce)
+ * IV (with nonce, can be removed once the new IV is returned)
+ * status: calculating, finished, confirmed
+ * data (can be removed once POW calculation is done)
+ */
+ fun storeTask(request: ProofOfWorkRequest) {
+ config.getConnection().use { connection ->
+ val ps = connection.prepareStatement(
+ "INSERT INTO ProofOfWorkTask (initial_hash, client, target, timestamp) VALUES (?, ?, ?, ?)")
+ ps.setBytes(1, request.initialHash)
+ ps.setString(2, request.sender.address)
+ ps.setBytes(3, request.data)
+ ps.setLong(4, UnixTime.now)
+ ps.executeUpdate()
+ }
+ }
+
+ fun updateTask(initalHash: ByteArray, nonce: ByteArray) {
+ config.getConnection().use { connection ->
+ val ps = connection.prepareStatement(
+ "UPDATE ProofOfWorkTask SET nonce = ? WHERE initial_hash = ?")
+ ps.setBytes(1, nonce)
+ ps.setBytes(2, initalHash)
+ ps.executeUpdate()
+ }
+ }
+
+ fun getNonce(request: ProofOfWorkRequest): ByteArray? {
+ config.getConnection().use { connection ->
+ val ps = connection.prepareStatement("SELECT nonce FROM ProofOfWorkTask WHERE initial_hash = ?")
+ ps.setBytes(1, request.initialHash)
+ val rs = ps.executeQuery()
+ return if (rs.next()) {
+ rs.getBytes(1)
+ } else {
+ null
+ }
+ }
+ }
+
+ fun hasTask(initialHash: ByteArray): Boolean {
+ config.getConnection().use { connection ->
+ val ps = connection.prepareStatement("SELECT count(1) FROM ProofOfWorkTask WHERE initial_hash = ?")
+ ps.setBytes(1, initialHash)
+ val rs = ps.executeQuery()
+ rs.next()
+ return rs.getInt(1) > 0
+ }
+ }
+
+ fun cleanupTasks(ageInSeconds: Long) {
+ config.getConnection().use { connection ->
+ val ps = connection.prepareStatement(
+ "DELETE FROM ProofOfWorkTask WHERE timestamp < ?")
+ ps.setLong(1, UnixTime.now - ageInSeconds)
+ ps.executeUpdate()
+ }
+ }
+
+ class Task internal constructor(val initialHash: ByteArray, val target: ByteArray)
+}
diff --git a/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.java b/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.java
deleted file mode 100644
index ab6ed9a..0000000
--- a/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package ch.dissem.bitmessage.server;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.boot.test.SpringApplicationConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.WebAppConfiguration;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@SpringApplicationConfiguration(classes = JabitServerApplication.class)
-@WebAppConfiguration
-public class JabitServerApplicationTests {
-
- @Test
- public void contextLoads() {
- }
-
-}
diff --git a/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.kt b/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.kt
new file mode 100644
index 0000000..a2d3ba7
--- /dev/null
+++ b/src/test/java/ch/dissem/bitmessage/server/JabitServerApplicationTests.kt
@@ -0,0 +1,17 @@
+package ch.dissem.bitmessage.server
+
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.springframework.boot.test.context.SpringBootTest
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
+import org.springframework.test.context.web.WebAppConfiguration
+
+@WebAppConfiguration
+@RunWith(SpringJUnit4ClassRunner::class)
+@SpringBootTest(classes = [JabitServerApplication::class])
+class JabitServerApplicationTests {
+
+ @Test
+ fun contextLoads() = Unit
+
+}
diff --git a/webapp/.editorconfig b/webapp/.editorconfig
deleted file mode 100644
index c2cdfb8..0000000
--- a/webapp/.editorconfig
+++ /dev/null
@@ -1,21 +0,0 @@
-# EditorConfig helps developers define and maintain consistent
-# coding styles between different editors and IDEs
-# editorconfig.org
-
-root = true
-
-
-[*]
-
-# Change these settings to your own preference
-indent_style = space
-indent_size = 2
-
-# We recommend you to keep these unchanged
-end_of_line = lf
-charset = utf-8
-trim_trailing_whitespace = true
-insert_final_newline = true
-
-[*.md]
-trim_trailing_whitespace = false
diff --git a/webapp/.gitattributes b/webapp/.gitattributes
deleted file mode 100644
index 2125666..0000000
--- a/webapp/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* text=auto
\ No newline at end of file
diff --git a/webapp/.gitignore b/webapp/.gitignore
deleted file mode 100644
index fdb1b10..0000000
--- a/webapp/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-node_modules
-dist
-bower_components
-.tmp
diff --git a/webapp/.jscsrc b/webapp/.jscsrc
deleted file mode 100644
index 880a269..0000000
--- a/webapp/.jscsrc
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "preset": "google",
- "disallowSpacesInAnonymousFunctionExpression": null,
- "excludeFiles": ["node_modules/**"]
-}
diff --git a/webapp/.jshintrc b/webapp/.jshintrc
deleted file mode 100644
index f30ce1e..0000000
--- a/webapp/.jshintrc
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "node": true,
- "browser": true,
- "bitwise": true,
- "camelcase": true,
- "curly": true,
- "eqeqeq": true,
- "immed": true,
- "indent": 2,
- "latedef": true,
- "noarg": true,
- "quotmark": "single",
- "undef": true,
- "unused": true,
- "newcap": false,
- "globals": {
- "wrap": true,
- "unwrap": true,
- "Polymer": true,
- "Platform": true,
- "page": true,
- "app": true
- }
-}
diff --git a/webapp/LICENSE.md b/webapp/LICENSE.md
deleted file mode 100644
index bb3f440..0000000
--- a/webapp/LICENSE.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# License
-
-Everything in this repo is BSD style license unless otherwise specified.
-
-Copyright (c) 2015 The Polymer Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-* Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-* Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/webapp/README.md b/webapp/README.md
deleted file mode 100644
index ccd6f12..0000000
--- a/webapp/README.md
+++ /dev/null
@@ -1,364 +0,0 @@
-![](https://cloud.githubusercontent.com/assets/110953/7877439/6a69d03e-0590-11e5-9fac-c614246606de.png)
-## Polymer Starter Kit
-
-> A starting point for building web applications with Polymer 1.0
-
-### Included out of the box:
-
-* [Polymer](http://polymer-project.org), [Paper](https://elements.polymer-project.org/browse?package=paper-elements), [Iron](https://elements.polymer-project.org/browse?package=iron-elements) and [Neon](https://elements.polymer-project.org/browse?package=neon-elements) elements
-* [Material Design](http://www.google.com/design/spec/material-design/introduction.html) layout
-* Routing with [Page.js](https://visionmedia.github.io/page.js/)
-* Unit testing with [Web Component Tester](https://github.com/Polymer/web-component-tester)
-* Optional offline setup through [Platinum](https://elements.polymer-project.org/browse?package=platinum-elements) Service Worker elements
-* End-to-end Build Tooling (including [Vulcanize](https://github.com/Polymer/vulcanize))
-
-## Getting Started
-
-To take advantage of Polymer Starter Kit you need to:
-
-1. Get a copy of the code.
-2. Install the dependencies if you don't already have them.
-3. Modify the application to your liking.
-4. Deploy your production code.
-
-### Get the code
-
-[Download](https://github.com/polymerelements/polymer-starter-kit/releases/latest) and extract Polymer Starter Kit to where you want to work. The project comes in two flavours - Light and Full.
-
-**Beginners**: Try Polymer Starter Kit Light. This doesn't require any extra dependencies nor knowledge of modern front-end tooling. This option is good for prototyping if you haven't build a Polymer app before.
-
-**Intermediate - Advanced**: Use the full version of Polymer Starter Kit. This comes with all the build tools you'll need for testing and productionising your app so it's nice and lean. You'll need to run a few extra commands to install the tools we recommend but it's worth it to make sure your final app is super optimised.
-
-Rob Dodson has a fantastic [PolyCast video](https://www.youtube.com/watch?v=xz-yixRxZN8) available that walks through using Polymer Starter Kit. An [end-to-end with Polymer](https://www.youtube.com/watch?v=1f_Tj_JnStA) and Polymer Starter Kit talk is also available.
-
-### Install dependencies
-
-#### Quick-start (for experienced users)
-
-With Node.js installed, run the following one liner from the root of your Polymer Starter Kit download:
-
-```sh
-npm install -g gulp bower && npm install && bower install
-```
-
-#### Prerequisites (for everyone)
-
-The full starter kit requires the following major dependencies:
-
-- Node.js, used to run JavaScript tools from the command line.
-- npm, the node package manager, installed with Node.js and used to install Node.js packages.
-- gulp, a Node.js-based build tool.
-- bower, a Node.js-based package manager used to install front-end packages (like Polymer).
-
-**To install dependencies:**
-
-1) Check your Node.js version.
-
-```sh
-node --version
-```
-
-The version should be at or above 0.12.x.
-
-2) If you don't have Node.js installed, or you have a lower version, go to [nodejs.org](https://nodejs.org) and click on the big green Install button.
-
-3) Install `gulp` and `bower` globally.
-
-```sh
-npm install -g gulp bower
-```
-
-This lets you run `gulp` and `bower` from the command line.
-
-4) Install the starter kit's local `npm` and `bower` dependencies.
-
-```sh
-cd polymer-starter-kit && npm install && bower install
-```
-
-This installs the element sets (Paper, Iron, Platinum) and tools the starter kit requires to build and serve apps.
-
-### Development workflow
-
-#### Serve / watch
-
-```sh
-gulp serve
-```
-
-This outputs an IP address you can use to locally test and another that can be used on devices connected to your network.
-
-#### Run tests
-
-```sh
-gulp test:local
-```
-
-This runs the unit tests defined in the `app/test` directory through [web-component-tester](https://github.com/Polymer/web-component-tester).
-
-To run tests Java 7 or higher is required. To update Java go to http://www.oracle.com/technetwork/java/javase/downloads/index.html and download ***JDK*** and install it.
-
-#### Build & Vulcanize
-
-```sh
-gulp
-```
-
-Build and optimize the current project, ready for deployment. This includes linting as well as vulcanization, image, script, stylesheet and HTML optimization and minification.
-
-## Application Theming & Styling
-
-Polymer 1.0 introduces a shim for CSS custom properties. We take advantage of this in `app/styles/app-theme.html` to provide theming for your application. You can also find our presets for Material Design breakpoints in this file.
-
-[Read more](https://www.polymer-project.org/1.0/docs/devguide/styling.html) about CSS custom properties.
-
-### Styling
-1. ***main.css*** - to define styles that can be applied outside of Polymer's custom CSS properties implementation. Some of the use-cases include defining styles that you want to be applied for a splash screen, styles for your application 'shell' before it gets upgraded using Polymer or critical style blocks that you want parsed before your elements are.
-2. ***app-theme.html*** - to provide theming for your application. You can also find our presets for Material Design breakpoints in this file.
-3. ***shared-styles.html*** - to shared styles between elements and index.html.
-4. ***element styles only*** - styles specific to element. These styles should be inside the `` inside `template`.
-
- ```HTML
-
-
-
-
-
-
{{item}}
-
-
-
-
- ```
-
-These style files are located in the [styles folder](app/styles/).
-
-## Unit Testing
-
-Web apps built with Polymer Starter Kit come configured with support for [Web Component Tester](https://github.com/Polymer/web-component-tester) - Polymer's preferred tool for authoring and running unit tests. This makes testing your element based applications a pleasant experience.
-
-[Read more](https://github.com/Polymer/web-component-tester#html-suites) about using Web Component tester.
-
-## Dependency Management
-
-Polymer uses [Bower](http://bower.io) for package management. This makes it easy to keep your elements up to date and versioned. For tooling, we use npm to manage Node.js-based dependencies.
-
-## Service Worker
-
-Polymer Starter Kit offers an optional offline experience thanks to Service Worker and the [Platinum Service Worker elements](https://github.com/PolymerElements/platinum-sw). New to Service Worker? Read the following [introduction](http://www.html5rocks.com/en/tutorials/service-worker/introduction/) to understand how it works.
-
-Our optional offline setup should work well for relatively simple applications. For more complex apps, we recommend learning how Service Worker works so that you can make the most of the Platinum Service Worker element abstractions.
-
-### Enable Service Worker support?
-
-To enable Service Worker support for Polymer Starter Kit project use these 3 steps:
-
-1. Uncomment Service Worker code in index.html
- ```HTML
-
-
- ```
-2. Uncomment Service Worker code in elements.html
-
- ```HTML
-
-
- ```
-3. Uncomment 'cache-config' in the `runSequence()` section of the 'default' gulp task, like below:
-[(gulpfile.js)](https://github.com/PolymerElements/polymer-starter-kit/blob/master/gulpfile.js)
-
- ```JavaScript
- // Build Production Files, the Default Task
- gulp.task('default', ['clean'], function (cb) {
- runSequence(
- ['copy', 'styles'],
- 'elements',
- ['jshint', 'images', 'fonts', 'html'],
- 'vulcanize', 'cache-config',
- cb);
- });
- ```
-
-#### Filing bugs in the right place
-
-If you experience an issue with Service Worker support in your application, check the origin of the issue and use the appropriate issue tracker:
-
-* [sw-toolbox](https://github.com/GoogleChrome/sw-toolbox/issues)
-* [platinum-sw](https://github.com/PolymerElements/platinum-sw/issues)
-* [platinum-push-notifications-manager](https://github.com/PolymerElements/push-notification-manager/)
-* For all other issues, feel free to file them [here](https://github.com/polymerelements/polymer-starter-kit/issues).
-
-#### I get an error message about "Only secure origins are allowed"
-
-Service Workers are only available to "secure origins" (HTTPS sites, basically) in line with a policy to prefer secure origins for powerful new features. However http://localhost is also considered a secure origin, so if you can, developing on localhost is an easy way to avoid this error. For production, your site will need to support HTTPS.
-
-#### How do I debug Service Worker?
-
-If you need to debug the event listener wire-up use `chrome://serviceworker-internals`.
-
-#### What are those buttons on chrome://serviceworker-internals?
-
-This page shows your registered workers and provides some basic operations.
-
-* Unregister: Unregisters the worker.
-* Start: Starts the worker. This would happen automatically when you navigate to a page in the worker's scope.
-* Stop: Stops the worker.
-* Sync: Dispatches a 'sync' event to the worker. If you don't handle this event, nothing will happen.
-* Push: Dispatches a 'push' event to the worker. If you don't handle this event, nothing will happen.
-* Inspect: Opens the worker in the Inspector.
-
-#### Development flow
-
-In order to guarantee that the latest version of your Service Worker script is being used, follow these instructions:
-
-* After you made changes to your service worker script, close all but one of the tabs pointing to your web application
-* Hit shift-reload to bypass the service worker as to ensure that the remaining tab isn't under the control of a service worker
-* Hit reload to let the newer version of the Service Worker control the page.
-
-If you find anything to still be stale, you can also try navigating to `chrome:serviceworker-internals` (in Chrome), finding the relevant Service Worker entry for your application and clicking 'Unregister' before refreshing your app. This will (of course) only clear it from the local development machine. If you have already deployed to production then further work will be necessary to remove it from your user's machines.
-
-#### Disable Service Worker support after you enabled it
-
-If for any reason you need to disable Service Worker support after previously enabling it, you can remove it from your Polymer Starter Kit project using these 4 steps:
-
-1. Remove references to the platinum-sw elements from your application [index](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/index.html).
-2. Remove the two Platinum Service Worker elements (platinum-sw/..) in [app/elements/elements.html](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/elements/elements.html)
-3. Remove 'precache' from the list in the 'default' gulp task ([gulpfile.js](https://github.com/PolymerElements/polymer-starter-kit/blob/master/gulpfile.js))
-4. Navigate to `chrome://serviceworker-internals` and unregister any Service Workers registered by Polymer Starter Kit for your app just in case there's a copy of it cached.
-
-## Yeoman support
-
-[generator-polymer](https://github.com/yeoman/generator-polymer/releases) now includes support for Polymer Starter Kit out of the box.
-
-## Frequently Asked Questions
-
-### Where do I customise my application theme?
-
-Theming can be achieved using [CSS Custom properties](https://www.polymer-project.org/1.0/docs/devguide/styling.html#xscope-styling-details) via [app/styles/app-theme.html](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/styles/app-theme.html).
-You can also use `app/styles/main.css` for pure CSS stylesheets (e.g for global styles), however note that Custom properties will not work there under the shim.
-
-A [Polycast](https://www.youtube.com/watch?v=omASiF85JzI) is also available that walks through theming using Polymer 1.0.
-
-### Where do I configure routes in my application?
-
-This can be done via [`app/elements/routing.html`](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/elements/routing.html). We use Page.js for routing and new routes
-can be defined in this import. We then toggle which `` page to display based on the [selected](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/index.html#L105) route.
-
-### Why are we using Page.js rather than a declarative router like ``?
-
-`` (in our opinion) is good, but lacks imperative hooks for getting full control
-over the routing in your application. This is one place where a pure JS router shines. We may
-at some point switch back to a declarative router when our hook requirements are tackled. That
-said, it should be trivial to switch to `` or another declarative router in your
-own local setup.
-
-### Where can I find the application layouts from your Google I/O 2015 talk?
-
-App layouts live in a separate repository called [app-layout-templates](https://github.com/PolymerElements/app-layout-templates).
-You can select a template and copy over the relevant parts you would like to reuse to Polymer Starter Kit.
-
-You will probably need to change paths to where your Iron and Paper dependencies can be found to get everything working.
-This can be done by adding them to the [`elements.html`](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/elements/elements.html) import.
-
-### Something has failed during installation. How do I fix this?
-
-Our most commonly reported issue is around system permissions for installing Node.js dependencies.
-We recommend following the [fixing npm permissions](https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md)
-guide to address any messages around administrator permissions being required. If you use `sudo`
-to work around these issues, this guide may also be useful for avoiding that.
-
-If you run into an exception that mentions five optional dependencies failing (or an `EEXIST` error), you
-may have run into an npm [bug](https://github.com/npm/npm/issues/6309). We recommend updating to npm 2.11.0+
-to work around this. You can do this by opening a Command Prompt/terminal and running `npm install npm@2.11.0 -g`. If you are on Windows,
-Node.js (and npm) may have been installed into `C:\Program Files\`. Updating npm by running `npm install npm@2.11.0 -g` will install npm
-into `%AppData%\npm`, but your system will still use the npm version. You can avoid this by deleting your older npm from `C:\Program Files\nodejs`
-as described [here](https://github.com/npm/npm/issues/6309#issuecomment-67549380).
-
-If the issue is to do with a failure somewhere else, you might find that due to a network issue
-a dependency failed to correctly install. We recommend running `npm cache clean` and deleting the `node_modules` directory followed by
-`npm install` to see if this corrects the problem. If not, please check the [issue tracker](https://github.com/PolymerElements/polymer-starter-kit/issues) in case
-there is a workaround or fix already posted.
-
-### I'm having trouble getting Vulcanize to fully build my project on Windows. Help?
-
-Some Windows users have run into trouble with the `elements.vulcanized.html` file in their `dist` folder
-not being correctly vulcanized. This can happen if your project is in a folder with a name containing a
-space. You can work around this issue by ensuring your path doesn't contain one.
-
-There is also an [in-flight](https://github.com/PolymerElements/polymer-starter-kit/issues/62#issuecomment-108974016) issue
-where some are finding they need to disable the `inlineCss` option in our configuration for Vulcanize
-to correctly build. We are still investigating this, however for the time-being use the workaround if
-you find your builds getting stuck here.
-
-
-### How do I add new JavaScript files to Starter Kit so they're picked up by the build process?
-
-At the bottom of `app/index.html`, you will find a build block that can be used to include additional
-scripts for your app. Build blocks are just normal script tags that are wrapped in a HTML
-comment that indicates where to concatenate and minify their final contents to.
-
-Below, we've added in `script2.js` and `script3.js` to this block. The line
-`` specifies that these scripts will be squashed into `scripts/app.js`
-during a build.
-
-```html
-
-
-
-
-
-```
-
-If you are not using the build-blocks, but still wish for additional files (e.g scripts or stylesheets) to be included in the final `dist` directory, you will need to either copy these files as part of the gulpfile.js build process (see the `copy` task for how to automate this) or manually copy the files.
-
-### I'm finding the installation/tooling here overwhelming. What should I do?
-
-Don't worry! We've got your covered. Polymer Starter Kit tries to offer everything you need to build and optimize your apps for production, which is why we include the tooling we do. We realise however that our tooling setup may not be for everyone.
-
-If you find that you just want the simplest setup possible, we recommend using Polymer Starter Kit light, which is available from the [Releases](https://github.com/PolymerElements/polymer-starter-kit/releases) page. This takes next to no time to setup.
-
-### If you require more granular configuration of Vulcanize than polybuild provides you an option by:
-
-1. Copy code below
-2. Then replace `gulp.task('vulcanize', function () {...` entire gulp vulcanize task code in `gulpfile.js`
-
-```javascript
-// Vulcanize granular configuration
-gulp.task('vulcanize', function () {
- var DEST_DIR = 'dist/elements';
- return gulp.src('dist/elements/elements.vulcanized.html')
- .pipe($.vulcanize({
- stripComments: true,
- inlineCss: true,
- inlineScripts: true
- }))
- .pipe(gulp.dest(DEST_DIR))
- .pipe($.size({title: 'vulcanize'}));
-});
-```
-
-## Contributing
-
-Polymer Starter Kit is a new project and is an ongoing effort by the Web Component community. We welcome your bug reports, PRs for improvements, docs and anything you think would improve the experience for other Polymer developers.
diff --git a/webapp/app/cache-config.json b/webapp/app/cache-config.json
deleted file mode 100644
index c6a8cef..0000000
--- a/webapp/app/cache-config.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "README": "This is the cache config for the dev server. The service worker cache is disabled, and it is recommended that you leave this as-is. In the dist environment, this file will be auto-generated based on the contents of your dist/ directory.",
- "disabled": true
-}
diff --git a/webapp/app/elements/elements.html b/webapp/app/elements/elements.html
deleted file mode 100644
index c0958ac..0000000
--- a/webapp/app/elements/elements.html
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/webapp/app/elements/message-list/message-list.html b/webapp/app/elements/message-list/message-list.html
deleted file mode 100644
index 8b4a80b..0000000
--- a/webapp/app/elements/message-list/message-list.html
+++ /dev/null
@@ -1,80 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-