fix admin not exporting own RPCs

This commit is contained in:
peter
2019-08-27 21:30:30 +02:00
parent 9a5ba13409
commit 06e9ac91a0
118 changed files with 27418 additions and 25 deletions
+4 -1
View File
@@ -13,4 +13,7 @@ conf
*.ts
!src/**/*
node_modules
node_modules
src/frontend/node_modules
src/frontend/out-tsc
src/frontend/dist
+3 -3
View File
@@ -2123,9 +2123,9 @@
}
},
"frontblock-generic": {
"version": "0.30.1",
"resolved": "https://registry.npmjs.org/frontblock-generic/-/frontblock-generic-0.30.1.tgz",
"integrity": "sha512-r+4/Zq9WGkD6Ma9F2AQp2ZP546jgXLde7aB050HHwF9t0O4ewy+ohfgyvEEH3dpIoQBbUWuD9uaAtahpNUYcqA==",
"version": "0.30.2",
"resolved": "https://registry.npmjs.org/frontblock-generic/-/frontblock-generic-0.30.2.tgz",
"integrity": "sha512-9dSasjv5pth2j6sCJ1cACfVWjTcDuabu/Nki8OBDXE3z4dljw1HnM5fRR7ncbnk7FAnUJXiMuWNBRqi3At3PLA==",
"requires": {
"@types/lowdb": "^1.0.9",
"@types/node": "^12.7.1",
+5 -5
View File
@@ -5,12 +5,12 @@
"scripts": {
"tsc": "tsc",
"start": "npm run build; node dist/FrontblockAdmin.js",
"build": "npm run clean; npm run build-backend",
"build": "npm run clean; npm run build-backend; npm run build-frontend",
"build-backend": "tsc; npm run webpack",
"build-frontend": "npm run build-dashboard",
"build-dashboard": "git submodule init && git submodule update --merge; cd src/frontend/dashboard; npm i && npm run build; cp -r dist/* ../../../static",
"build-frontend": "npm run build-dashboard; cp ./dist/FrontblockLib.js ./static",
"build-dashboard": "git submodule init && git submodule update --merge; cd src/frontend; npm i && npm run build; mkdir ../../static; cp -r dist/* ../../static",
"build-widget": "rollup -c src/frontend/widget/rollup.config.js; mkdir -p plugins/PluginManager; cp FrontendPlugin.js plugins/PluginManager",
"clean": "rm -rf lib static plugins conf dist widget .rpt2_cache *.js *.ts src/frontend/dashboard/dist",
"clean": "rm -rf lib static plugins conf dist widget .rpt2_cache *.js *.ts src/frontend/dist",
"update-frontblock": "rm -rf node_modules/frontblock*; npm install",
"webpack": "webpack --config src/backend/webpack.prod.js --progress --colors"
},
@@ -27,7 +27,7 @@
"debug": "^4.1.1",
"express": "^4.16.4",
"frontblock": "^0.14.0",
"frontblock-generic": "^0.30.1",
"frontblock-generic": "^0.30.2",
"git-cherrypicker": "0.0.3",
"git-describe": "^4.0.4",
"http": "0.0.0",
+8
View File
@@ -12,6 +12,7 @@ import * as path from "path"
import { UpdateManager } from './UpdateManger';
import { FrontblockApi } from 'frontblock-generic/Api';
import { Plugin } from 'frontblock-generic/Plugin';
import { socketioRPC } from 'frontblock-generic/RPC';
var exec = require('child-process-promise').exec;
Logger.configure({
@@ -91,6 +92,13 @@ export class FrontblockAdmin extends AdminBase<AdminConf>{
this.startWebserver()
}
exportRPCs():socketioRPC[]{
return [
...[/* more RPC here */],
...super.exportRPCs()
]
}
private startWebserver(){
if(this.httpServer != null || this.express != null){
logger.warn("Webserver is already running")
+1 -16
View File
@@ -79,22 +79,7 @@ export class UpdateManager extends Plugin{
async updatePlatformDependencies(){
logger.info("installing npm stuff")
/*
const res = await exec('npm install --prefix ./plugins knex sqlite3')
logger.warn(res.stderr)
logger.info(res.stdout)
*/
/*
const extensions = [
new NPMExtension("sqlite3", "./plugins", "4.1.0"),
new NPMExtension("frontblock", "./plugins", "latest")
]
*/
const extensions:NPMExtension[] = []
const extensions:NPMExtension[] = []
await Promise.all(extensions.map(e => e.install()))
const status = await Promise.all(extensions.map(e => e.status()))
+60
View File
@@ -0,0 +1,60 @@
kind: pipeline
name: default
steps:
- name: restore cache
image: drillster/drone-volume-cache
settings:
restore: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: npm install
image: node:12
commands:
- npm install
- name: npm run build
image: node:12
commands:
- npm run build
- name: rebuild cache
image: drillster/drone-volume-cache
settings:
rebuild: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: deploy static files
image: node:12
commands:
- git config --global user.email "${DRONE_COMMIT_AUTHOR_EMAIL}"
- git config --global user.name "${DRONE_COMMIT_AUTHOR}"
- git clone https://gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git
- cp -r ./dist/* ./${DRONE_REPO_NAME}
- cd ./${DRONE_REPO_NAME}
- git add -A
- git commit --allow-empty -m "drone taged as version ${DRONE_TAG}"
- git tag ${DRONE_TAG}
- git push https://$GIT_USER:$GIT_PASSWORD@gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git master ${DRONE_TAG}
environment:
GIT_USER:
from_secret: git_user
GIT_PASSWORD:
from_secret: git_password
when:
event:
- tag
volumes:
- name: cache
host:
path: /tmp
+13
View File
@@ -0,0 +1,13 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
+48
View File
@@ -0,0 +1,48 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
src/assets/*.js
+6
View File
@@ -0,0 +1,6 @@
[submodule "src/app/apiclient"]
path = src/app/apiclient
url = ssh://git@gitea.frontblock.me:2222/fb-plugin/apiclient.git
[submodule "src/app/wallet"]
path = src/app/wallet
url = ssh://git@gitea.frontblock.me:2222/fb-plugin/wallet.git
+27
View File
@@ -0,0 +1,27 @@
# Dashboard
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.1.0.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
+147
View File
@@ -0,0 +1,147 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"dashboard": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss",
"node_modules/@clr/icons/clr-icons.min.css",
"node_modules/@clr/ui/clr-ui-dark.min.css"
],
"scripts": [
"node_modules/systemjs/dist/system.js",
"node_modules/@webcomponents/custom-elements/custom-elements.min.js",
"node_modules/@clr/icons/clr-icons.min.js"
]
},
"configurations": {
"production": {
"tsConfig": "tsconfig.prod.json",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
},
"prodlike": {
"tsConfig": "tsconfig.prod.json",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prodlike.ts"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"tsConfig": "tsconfig.app.json",
"options": {
"browserTarget": "dashboard:build"
},
"configurations": {
"production": {
"browserTarget": "dashboard:build:production"
},
"prodlike": {
"browserTarget": "dashboard:build:prodlike"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "dashboard:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**",
"**/backend/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "dashboard:serve"
},
"configurations": {
"production": {
"devServerTarget": "dashboard:serve:production"
}
}
}
}
}},
"defaultProject": "dashboard"
}
+12
View File
@@ -0,0 +1,12 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
+32
View File
@@ -0,0 +1,32 @@
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
+23
View File
@@ -0,0 +1,23 @@
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Welcome to dashboard!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
+11
View File
@@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root h1')).getText() as Promise<string>;
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
+32
View File
@@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/dashboard'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
+12512
View File
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
{
"name": "dashboard",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --aot=false --optimization=false --proxy-config proxy.conf.json ",
"start-prodlike": "npm run build-assets && ng serve --aot=false --optimization=false --proxy-config proxy.conf.json --configuration=prodlike",
"build": "rm -f src/assets/*.js; ng build --prod --aot=false --optimization=false --build-optimizer=false",
"build-assets": "npm run copy-frontends; npm run deep-clean-plugins",
"update-frontblock": "rm -rf node_modules/frontblock*; npm install",
"get-submodules": "git submodule update --init && git submodule foreach git checkout master",
"copy-frontends": "for module in $(git config --file .gitmodules --get-regexp path | awk '{ print $2 }'); do npm i --prefix $module && npm run --prefix $module build && cp $module/dist/FrontendPlugin.js ./src/assets/$(basename $module).js; done",
"deep-clean-plugins": "for module in $(git config --file .gitmodules --get-regexp path | awk '{ print $2 }'); do rm -rf $module/node_modules; done",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.1",
"@angular/common": "~8.2.1",
"@angular/compiler": "~8.2.1",
"@angular/core": "~8.2.1",
"@angular/forms": "~8.2.1",
"@angular/platform-browser": "~8.2.1",
"@angular/platform-browser-dynamic": "~8.2.1",
"@angular/router": "~8.2.1",
"@clr/angular": "^2.1.1",
"@clr/icons": "^2.1.1",
"@clr/ui": "^2.1.1",
"@types/knex": "^0.16.1",
"@webcomponents/custom-elements": "^1.0.0",
"btc-hdkey": "0.0.17",
"coinselect": "^3.1.11",
"frontblock": "latest",
"frontblock-generic": "^0.23.0",
"key-file-storage": "^2.2.4",
"node-fetch": "^2.6.0",
"rxjs": "~6.5.2",
"stream": "0.0.2",
"systemjs": "^0.21.3",
"tslib": "^1.9.0",
"uuid": "^3.3.2",
"zone.js": "~0.10.1"
},
"devDependencies": {
"@angular-builders/custom-webpack": "^8.2.0",
"@angular-builders/dev-server": "^7.3.1",
"@angular-devkit/build-angular": "^0.802.2",
"@angular/cli": "^8.2.2",
"@angular/compiler-cli": "~8.2.1",
"@angular/language-service": "~8.2.1",
"@types/jasmine": "~3.4.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.7.1",
"@types/systemjs": "^0.20.6",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.2.0",
"karma-chrome-launcher": "~3.0.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.5.3"
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"/widgets-repo/*": {
"target": "http://localhost:4201",
"secure": false,
"pathRewrite": {
"^/widgets-repo": ""
}
}
}
+69
View File
@@ -0,0 +1,69 @@
kind: pipeline
name: default
steps:
- name: restore cache
image: drillster/drone-volume-cache
settings:
restore: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: npm install
image: node:12
commands:
- npm install
- name: npm run build
image: node:12
commands:
- npm run build
- name: rebuild cache
image: drillster/drone-volume-cache
settings:
rebuild: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: npm publish
image: plugins/npm
settings:
username: frontblock
password:
from_secret: npm_password
email: frontblock.me@gmail.com
event:
- tag
- name: deploy plugin
image: node:12
commands:
- git config --global user.email "${DRONE_COMMIT_AUTHOR_EMAIL}"
- git config --global user.name "${DRONE_COMMIT_AUTHOR}"
- git clone https://gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git
- cp -r ./dist/* ./${DRONE_REPO_NAME}
- cd ./${DRONE_REPO_NAME}
- git add -A
- git commit --allow-empty -m "drone tagged as version ${DRONE_TAG}"
- git tag ${DRONE_TAG}
- git push https://$GIT_USER:$GIT_PASSWORD@gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git master ${DRONE_TAG}
environment:
GIT_USER:
from_secret: git_user
GIT_PASSWORD:
from_secret: git_password
when:
event:
- tag
volumes:
- name: cache
host:
path: /tmp
+10
View File
@@ -0,0 +1,10 @@
dist
.rpt2_cache
node_modules
lib
*.d.ts
*.js
*.ts
!src/**/*
@@ -0,0 +1,2 @@
**/*
!FrontblockApiClient.*
@@ -0,0 +1,17 @@
{
"apiConf": {
"apiHost": "api.testnet.frontblock.me",
"apiKey": "",
"apiPort": 10001,
"tls": false
},
"dbConf": {
"type": "sqlite",
"database": "./data/ApiClient.sqlite",
"synchronize": true,
"entities": [
null,
null
]
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
{
"name": "frontblock",
"version": "0.14.0",
"description": "frontblock shop-side library ",
"main": "FrontblockApiClient.js",
"scripts": {
"tsc": "tsc",
"build-backend": "webpack --config src/backend/webpack.prod.js --progress --colors",
"build-frontend": "webpack --config src/frontend/webpack.prod.js --progress --colors",
"build": "npm run clean; npm run tsc; npm run build-backend; npm run build-frontend",
"clean": "rm -rf *.js *.ts backend frontend .rpt2_cache dist lib",
"update-frontblock": "rm -rf node_modules/frontblock*; npm install"
},
"keywords": [
"api",
"client",
"frontblock"
],
"author": "",
"license": "ISC",
"dependencies": {
"@angular/common": "^8.2.1",
"@angular/core": "^8.2.1",
"@angular/forms": "^8.2.1",
"@angular/platform-browser": "^8.2.1",
"@angular/router": "^8.2.1",
"@clr/angular": "^2.1.1",
"@types/node": "^11.13.10",
"frontblock-generic": "^0.28.4",
"fs": "0.0.1-security",
"knex": "^0.19.2",
"log4js": "^4.3.1",
"node-fetch": "^2.5.0",
"path": "^0.12.7",
"rxjs": "^6.5.2",
"rxjs-compat": "^6.5.2"
},
"devDependencies": {
"ts-loader": "^6.0.4",
"typescript": "^3.4.5",
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"webpack-node-externals": "^1.7.2"
}
}
@@ -0,0 +1,104 @@
import { Coin, AccountMap, TransactionMap, SubscriptionResponse, ErrorResponse, SuccessResponse, parseResponse, parseSubResponse } from "frontblock-generic/Types";
import { FrontblockApi as FrontblockApi } from "frontblock-generic/Api";
import * as Logger from 'log4js'
Logger.configure({
appenders: {
"frontblock-api-client": { type: 'stdout' },
//app: { type: 'file', filename: 'application.log' }
},
categories: {
default: { appenders: ['frontblock-api-client'], level: 'debug' }
}
})
const logger = Logger.getLogger("frontblock-api-client")
const bsock = require('bsock')
export type FrontblockApiConf = {
apiHost: string
apiPort: number
tls?: boolean
apiKey?: string
}
/**
* Frontblock api connection lib
*/
export class FrontblockApiClient implements FrontblockApi {
protected started: boolean = false
protected apikey: string = ""
protected socket
constructor(private conf: FrontblockApiConf){
}
async consume<C extends Coin>(apikey: string, uid: string, callback: (tx: TransactionMap[C]) => void): Promise<SubscriptionResponse | ErrorResponse> {
const r = await this.socket.call("consume", apikey, uid)
const res = parseSubResponse(r)
if (res instanceof SubscriptionResponse) {
this.socket.hook(res.uid, (tx) => {
const deserialized = <TransactionMap[C]>JSON.parse(tx)
callback(deserialized)
})
}
return res
}
async quit(apikey: string, consumerUid: string): Promise<ErrorResponse | SuccessResponse> {
const r = await this.socket.call("quit", apikey, consumerUid)
const res = parseResponse(r)
return res
}
async subscribe<C extends Coin>(apikey: string, coin: C, account: AccountMap[C]): Promise<SubscriptionResponse | ErrorResponse> {
const r = await this.socket.call("subscribe", apikey, coin, account)
const res = parseSubResponse(r)
return res
}
async subsume<C extends Coin>(apikey: string, coin: C, account: AccountMap[C], callback: (tx: TransactionMap[C]) => void): Promise<SubscriptionResponse | ErrorResponse> {
const r = await this.socket.call("subsume", apikey, coin, account)
const res = parseSubResponse(r)
if (res instanceof SubscriptionResponse) {
this.socket.hook(res.uid, (tx) => {
const deserialized = <TransactionMap[C]>JSON.parse(tx)
callback(deserialized)
})
}
return res
}
async unsubscribe(apikey: string, uid: string): Promise<ErrorResponse | SuccessResponse> {
const r = await this.socket.call('unsubscribe', apikey, uid)
const res = parseResponse(r)
if (res instanceof SuccessResponse)
this.socket.unhook(uid)
return res
}
async getPluginList(): Promise<string[]> {
return await this.socket.call('getPluginList')
}
connect(): void {
if (this.started) {
logger.warn("FrontblockApiClient has already been started. Ignoring")
return
}
logger.info("Starting apiClient with ", this.conf)
this.socket = bsock.connect(this.conf.apiPort, this.conf.apiHost, this.conf.tls != null ? this.conf.tls : false)
this.started = true
}
disconnect(): void {
if (!this.started) {
logger.warn("FrontblockApiClient has not been started. Ignoring")
return
}
this.socket.close()
}
}
@@ -0,0 +1,201 @@
import { FrontblockApiClient, FrontblockApiConf } from "./FrontblockApiClient";
import { socketioRPC } from "frontblock-generic/RPC"
import { DatabasePlugin, TableDefiniton } from "frontblock-generic/DatabasePlugin"
import { Coin, AccountMap, TransactionMap, SubscriptionResponse } from "frontblock-generic/Types";
import * as knex from 'knex';
import * as Logger from 'log4js'
Logger.configure({
appenders: {
"frontblock-api-client": { type: 'stdout' },
//app: { type: 'file', filename: 'application.log' }
},
categories: {
default: { appenders: [ 'frontblock-api-client' ], level: 'debug' }
}
})
const logger = Logger.getLogger("frontblock-api-client")
/**
* Frontblock admin Plugin for FrontblockApiClient
*/
type ApiClientPluginConf = {
apiConf: FrontblockApiConf,
}
export default class FrontblockApiClientPlugin extends DatabasePlugin<ApiClientPluginConf>{
private apiClient : FrontblockApiClient
constructor(){
super("ApiClient")
}
getDefaultConfig(): ApiClientPluginConf & { dbConf: knex.Config; } {
return {
apiConf: {
apiHost: "api.testnet.frontblock.me",
apiKey: "",
apiPort: 10001,
tls: false
},
dbConf: {
client: 'sqlite3',
connection: {
filename: "./data/ApiClient.sqlite"
},
useNullAsDefault: true
}
}
}
async getConsumers(): Promise<SubscriptionResponse[]> {
const records = await this.knex.select('*').from('consumers')
return records.map(r => JSON.parse(r.JSON))
}
async getSubscriptions(): Promise<SubscriptionResponse[]> {
const records = await this.knex.select('*').from('subscriptions')
return records.map(r => JSON.parse(r.JSON))
}
exportExtraRPCs(): socketioRPC[] {
const quit = async(uid:string) => {return await this.quit(this.getConfigKey('apiConf').apiKey, uid) }
return [
{
name: "subscribe",
func: async <C extends Coin>(coin: C, account: AccountMap[C]) => { return await this.subscribe(this.getConfigKey('apiConf').apiKey, coin, account)},
type: 'call',
visibility: 'private'
},{
name: "subsume",
func: async <C extends Coin>(coin: C, account: AccountMap[C], callback: (tx: TransactionMap[C]) => void) => { return await this.subsume(this.getConfigKey('apiConf').apiKey, coin, account, callback)},
type: 'hook',
unhook: quit,
visibility: 'private'
},{
name: 'unsubscribe',
func: async(uid:string) => { return await this.unsubscribe(this.getConfigKey('apiConf').apiKey, uid) },
type: 'call',
visibility: 'private'
},{
name: 'consume',
func: async<C extends Coin>(uid: string, callback: (tx: TransactionMap[C]) => void) => {return await this.consume(this.getConfigKey('apiConf').apiKey, uid, callback)},
type: 'hook',
unhook: quit,
visibility: 'private'
},{
name: 'quit',
func: quit,
type: 'call',
visibility: 'private'
},{
name: "getSubscriptions",
func: async() => { return await this.getSubscriptions() },
type: "call",
visibility: "private"
},{
name: "getConsumers",
func: async() => { return await this.getConsumers() },
type: "call",
visibility: "private"
}
]
}
private subscribe:FrontblockApiClient['subscribe'] = async (apiKey, coin, account) => {
const res = await this.apiClient.subscribe(apiKey, coin, account)
if(res instanceof SubscriptionResponse){
await this.knex('subscriptions').insert([{uuid: res.uid, JSON: JSON.stringify(res)}])
}
return res
}
private consume:FrontblockApiClient['consume'] = async (apikey, uuid, callback) => {
const res = await this.apiClient.consume(apikey, uuid, callback)
if(res instanceof SubscriptionResponse){
await this.knex('consumers').insert([{uuid: res.uid, JSON: JSON.stringify(res)}])
}
return res
}
private unsubscribe:FrontblockApiClient['unsubscribe'] = async (apikey, uuid) => {
const res = await this.apiClient.unsubscribe(apikey, uuid)
await this.knex('subscriptions')
.where('uuid', uuid)
.del()
return res
}
private quit:FrontblockApiClient['quit'] = async (apikey, uuid) => {
const res = await this.apiClient.quit(apikey, uuid)
await this.knex('consumers')
.where('uuid', uuid)
.del()
return res
}
private subsume:FrontblockApiClient['subsume'] = async (apikey, coin, account, callback) => {
const res = await this.apiClient.subsume(apikey, coin, account, callback)
if(res instanceof SubscriptionResponse){
await Promise.all([
this.knex('consumers')
.insert([{uuid: res.uid, JSON: JSON.stringify(res)}]),
this.knex('subscriptions')
.insert([{uuid: res.uid, JSON: JSON.stringify(new SubscriptionResponse(res.message))}])
])
}
return res
}
private makeApiClient(conf: FrontblockApiConf):FrontblockApiClient{
if(this.apiClient)
this.apiClient.disconnect()
this.apiClient = new FrontblockApiClient(conf)
this.apiClient.connect()
return this.apiClient
}
setConfig(conf:ApiClientPluginConf & { dbConf: knex.Config }):ApiClientPluginConf & { dbConf: knex.Config }{
const currConf = this.getConfig()
if(JSON.stringify(currConf.apiConf) !== JSON.stringify(conf.apiConf)){
this.makeApiClient(conf.apiConf)
}
return super.setConfig(conf)
}
setConfigKey(key:keyof ApiClientPluginConf, value: any):ApiClientPluginConf & { dbConf: knex.Config; }{
if(key === 'apiConf'){
this.makeApiClient(value)
}
return super.setConfigKey(key, value)
}
async start(): Promise<void> {
this.makeApiClient(this.getConfig().apiConf)
super.start()
}
stop(): void {
this.apiClient.disconnect()
super.stop()
}
protected getTableDefinitions(): TableDefiniton[] {
return [{
name: 'subscriptions',
tableBuilder: function (table) {
table.string('uuid').primary();
table.string('JSON');
}
},{
name: 'consumers',
tableBuilder: function (table) {
table.string('uuid').primary();
table.string('JSON');
}
}]
}
}
@@ -0,0 +1,38 @@
const nodeExternals = require('webpack-node-externals');
const TerserPlugin = require('terser-webpack-plugin');
var webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'production',
target: "node",
entry: path.resolve(__dirname, 'Plugin.ts'),
output: {
path: path.resolve(__dirname, '../../dist'),
filename: 'Plugin.js',
libraryTarget: 'commonjs',
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.ts?$/, loader: "ts-loader" }
]
},
optimization: {
minimize: false
},
node: {
global: true,
process: true,
__filename: false,
__dirname: false,
Buffer: true,
},
externals:{
knex: "../node_modules/knex"
}
}
@@ -0,0 +1,92 @@
import { Component, OnInit, isDevMode } from '@angular/core';
import { SubscriptionResponse, parseResponse, SuccessResponse } from 'frontblock-generic/Types';
declare const fb
@Component({
selector: 'consumers',
template: `
<div class="clr-row">
<div class="card clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-auto clr-col-xl-auto">
<div class="card-header">
Consumers
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="entry.severity">
<clr-alert-item>
<span class="alert-text">
{{entry.message}}
</span>
</clr-alert-item>
</clr-alert>
<div *ngIf="loading" class="card-block">
<span class="spinner spinner-inline"></span>
</div>
<div *ngIf="entries.length !== 0 && !loading" class="card-block limit-height">
<div class="card-text limit-height">
<clr-datagrid>
<clr-dg-column>UUID</clr-dg-column>
<clr-dg-column>Subscription UUID</clr-dg-column>
<clr-dg-column>Expiry</clr-dg-column>
<clr-dg-column>Creation</clr-dg-column>
<clr-dg-row *clrDgItems="let line of entries">
<clr-dg-cell>{{line.uid}}</clr-dg-cell>
<clr-dg-cell>{{line.message}}</clr-dg-cell>
<clr-dg-cell>{{line.expiry | date}}</clr-dg-cell>
<clr-dg-cell>{{line.created | date}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded>
<button class="btn btn-icon btn-danger-outline" (click)="quit(line.uid)"><clr-icon shape="times"></clr-icon> Quit</button>
</clr-dg-row-detail>
</clr-dg-row>
<clr-dg-footer>
<clr-dg-pagination #pagination [clrDgPageSize]="10">
<clr-dg-page-size [clrPageSizeOptions]="[10,20,50,100]">Users per page</clr-dg-page-size>
{{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
of {{pagination.totalItems}} users
</clr-dg-pagination>
</clr-dg-footer>
</clr-datagrid>
</div>
</div>
<div class="card-footer">
<button *ngIf="!loading" class="btn btn-sm btn-link" (click)="load()">{{actionName}}</button>
</div>
</div>
`
})
export class ApiclientConsumptionComponent implements OnInit {
loading: boolean = false
actionName: string = "load"
entries: SubscriptionResponse[] = []
alerts: {
severity: "danger" | "warning" | "success"
message: string
}[] = []
constructor() { }
ngOnInit() { }
async load() {
this.loading = true
this.entries = await fb.ApiClient.getConsumers()
if (this.entries.length === 0) {
this.alerts.push({ severity: "warning", message: "0 results were returned" })
}
this.loading = false
this.actionName = "refresh"
}
async quit(uid: string) {
const r = await fb.ApiClient.quit(uid)
const res = parseResponse(r)
if (res instanceof SuccessResponse) {
this.alerts.push({ severity: "success", message: "Quit consuming " + uid })
this.load()
} else {
this.alerts.push({ severity: "danger", message: "Error " + res.message })
}
}
}
@@ -0,0 +1,134 @@
import { Component, OnInit } from '@angular/core';
import { FrontblockApiConf } from '../backend/FrontblockApiClient';
import { isDevMode } from '@angular/core';
declare const fb
@Component({
selector: 'settings',
template: `
<div class="clr-row">
<div class="card clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-auto clr-col-xl-auto">
<div class="card-header">
Settings
</div>
<div class="card-block">
<div class="card-text">
<form clrForm clrLayout="horizontal">
<div class="clr-row clr-form-control ng-star-inserted">
<label class="clr-col-12 clr-col-md-4 clr-control-label">testnet</label>
<div class="clr-col-12 clr-col-md-8">
<input type="checkbox" [(ngModel)]="testnet" (change)="updateTestnet($event)" name="testnetToggle" clrToggle />
</div>
</div>
<clr-input-container *ngIf="!testnet">
<label class="clr-col-12 clr-col-md-4">API key</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="apiKey" required />
</clr-input-container>
<clr-input-container *ngIf="advanced" class="clr-row">
<label class="clr-col-12 clr-col-md-4">API address</label>
<input class="clr-col-12 clr-col-md-8" type="text" [(ngModel)]="data.apiHost" (change)="updatePort($event)" clrInput name="apiHost" required />
<clr-control-error>This field is required!</clr-control-error>
</clr-input-container>
<div class="clr-row clr-form-control ng-star-inserted" *ngIf="advanced">
<label class="clr-col-12 clr-col-md-4 clr-control-label">Use TLS</label>
<div class="clr-col-12 clr-col-md-8">
<input [(ngModel)]="data.tls" type="checkbox" clrCheckbox value="tls" name="options" />
</div>
</div>
<clr-input-container class="clr-row" *ngIf="advanced">
<label class="clr-col-12 clr-col-md-4">Port</label>
<input class="clr-col-12 clr-col-md-8" [(ngModel)]="data.apiPort" clrInput type="number" name="lastName" required />
<clr-control-error>Valid range 1024 - 65536
</clr-control-error>
</clr-input-container>
</form>
</div>
</div>
<div class="card-footer">
<button *ngIf="!saving" class="btn btn-success-outline" (click)="save()">
<span>Save</span>
</button>
<button *ngIf="saving" class="btn btn-disabled" (click)="save()" disabled>
<span class="spinner spinner-inline"></span>
</button>
<button *ngIf="!advanced" class="btn btn-sm btn-link" (click)="setAdvanced()">Advanced</button>
</div>
</div>
</div>
<knex-config fbPlugin="ApiClient"></knex-config>
`
})
export class ApiclientFormComponent implements OnInit {
testnet: boolean = true
saving: boolean = false
advanced: boolean = false
data: FrontblockApiConf = {
apiHost: "api.testnet.frontblock.me",
apiPort: 10001,
tls: false,
apiKey: ""
}
constructor() { }
ngOnInit() { }
setAdvanced() { this.advanced = true }
checkData(): boolean {
return (
typeof this.data.apiPort === "number" &&
typeof this.data.apiHost === "string" &&
typeof this.data.tls === "boolean" &&
typeof this.data.apiKey === "string"
)
}
updateTestnet() {
if (this.testnet) {
this.data.apiHost = "api.testnet.frontblock.me"
this.data.apiPort = 10001
} else {
this.data.apiHost = "api.frontblock.me"
this.data.apiPort = 10000
}
}
updatePort(obj) {
switch (this.data.apiHost) {
case "api.testnet.frontblock.me":
this.data.apiPort = 10001
break;
case "api.frontblock.me":
this.data.apiPort = 10000
break;
default:
console.warn("A non-standard api host was chosen: " + this.data.apiPort)
break;
}
console.log(this.data)
}
async save() {
this.saving = true;
if (typeof this.data.apiPort === "string")
this.data.apiPort = parseInt(this.data.apiPort)
if (this.checkData()) {
const conf = await fb.ApiClient.setConfig(this.data)
console.log(conf)
} else {
//show error in gui
console.error("bad data :(")
}
this.saving = false
}
}
@@ -0,0 +1,101 @@
import { Component, OnInit, isDevMode } from '@angular/core';
import { SubscriptionResponse, SuccessResponse, parseResponse } from 'frontblock-generic/Types';
declare const fb
@Component({
selector: 'subscriptions',
template: `
<div class="clr-row">
<div class="card clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-12 clr-col-xl-12">
<div class="card-header">
Subscriptions
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="entry.severity">
<clr-alert-item>
<span class="alert-text">
{{entry.message}}
</span>
</clr-alert-item>
</clr-alert>
<div *ngIf="loading" class="card-block">
<span class="spinner spinner-inline"></span>
</div>
<div *ngIf="entries.length !== 0 && !loading" class="card-block">
<div class="card-text">
<clr-datagrid>
<clr-dg-column>UUID</clr-dg-column>
<!--
<clr-dg-column>Currency</clr-dg-column>
<clr-dg-column>Address</clr-dg-column>
<clr-dg-column>Memo</clr-dg-column>
<clr-dg-column>Expiry</clr-dg-column>
<clr-dg-column>Creation</clr-dg-column>
-->
<clr-dg-row *clrDgItems="let line of entries">
<clr-dg-cell>{{line.uid}}</clr-dg-cell>
<!--
<clr-dg-cell>{{line.currency}}</clr-dg-cell>
<clr-dg-cell>{{line.address}}</clr-dg-cell>
<clr-dg-cell>{{line.memo}}</clr-dg-cell>
<clr-dg-cell>{{line.expiry | date}}</clr-dg-cell>
<clr-dg-cell>{{line.created | date}}</clr-dg-cell>
-->
<clr-dg-row-detail *clrIfExpanded>
<button class="btn btn-icon btn-danger-outline" (click)="quit(line.uid)"><clr-icon shape="times"></clr-icon> Unsubscribe</button>
</clr-dg-row-detail>
</clr-dg-row>
<clr-dg-footer>
<clr-dg-pagination #pagination [clrDgPageSize]="10">
<clr-dg-page-size [clrPageSizeOptions]="[10,20,50,100]">Users per page</clr-dg-page-size>
{{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
of {{pagination.totalItems}} users
</clr-dg-pagination>
</clr-dg-footer>
</clr-datagrid>
</div>
</div>
<div class="card-footer">
<button *ngIf="!loading" class="btn btn-sm btn-link" (click)="load()">{{actionName}}</button>
</div>
</div>
</div>
`
})
export class ApiclientSubscriptionComponent implements OnInit {
loading: boolean = false
actionName: string = "load"
entries: (SubscriptionResponse )[] = []
alerts: {
severity: "danger" | "warning" | "success"
message: string
}[] = []
constructor() { }
ngOnInit() { }
async load() {
this.loading = true
this.entries = await fb.ApiClient.getSubscriptions()
if (this.entries.length === 0) {
this.alerts.push({ severity: "warning", message: "0 results were returned" })
}
this.loading = false
this.actionName = "refresh"
}
async quit(uid: string) {
const r = await fb.ApiClient.unsubscribe(uid)
const res = parseResponse(r)
if (res instanceof SuccessResponse) {
this.alerts.push({ severity: "success", message: "Stopped subscription " + uid })
this.load()
} else {
this.alerts.push({ severity: "danger", message: "Error " + res.message })
}
}
}
@@ -0,0 +1,52 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ApiclientFormComponent } from './apiclient-settings-form.component';
import { ApiclientConsumptionComponent } from './apiclient-consumptions.component';
import { ApiclientSubscriptionComponent } from './apiclient-subscriptions.component';
import { FrontendPlugin, SidebarEntries } from 'frontblock-generic/Plugin';
import { ClarityModule } from '@clr/angular';
import { FormsModule } from '@angular/forms';
// @ts-ignore
import { KnexConfigModule } from "../../../knex-config/knex-config.module";
@NgModule({
imports: [
FormsModule,
ClarityModule,
KnexConfigModule,
CommonModule,
RouterModule.forChild([
{path: "settings", component: ApiclientFormComponent},
{path: "subscriptions", component: ApiclientSubscriptionComponent},
{path: "consumers", component: ApiclientConsumptionComponent},
]),
],
exports: [RouterModule],
declarations: [
ApiclientFormComponent,
ApiclientConsumptionComponent,
ApiclientSubscriptionComponent
]
})
export class PluginModule implements FrontendPlugin{
getSidebarEntry(): SidebarEntries {
return {
icon: "terminal",
parentRoute: "apiclient",
text: "Api client",
links: [{
route: "settings",
text: "Settings"
},{
route: "consumers",
text: "Consumers"
},{
route: "subscriptions",
text: "Subscriptions"
},]
}
}
}
@@ -0,0 +1,41 @@
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
target: "web",
entry: path.resolve(__dirname, 'module.ts'),
output: {
path: path.resolve(__dirname, '../../dist'),
filename: 'FrontendPlugin.js',
libraryTarget: 'commonjs',
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.ts?$/, loader: "ts-loader" }
]
},
optimization: {
minimizer: [
new TerserPlugin({
exclude: [
/\.\/(.*)\/.ts/,
/\.\/(.*).ts/,
],
}),
],
},
externals: {
'@angular/core': '@angular/core',
'@angular/common': '@angular/common',
'@angular/router': '@angular/router',
'@angular/animations': '@angular/animations',
'@angular/forms': '@angular/forms',
'@clr/angular': '@clr/angular',
'../../../knex-config/knex-config.module': 'knexconfig'
}
}
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"include": ["src/frontend"],
"exclude": [
"src/backend"
],
"compilerOptions": {
"sourceMap": true
}
}
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"alwaysStrict": false,
"noImplicitAny": false,
"target": "ES2015",
"module": "commonjs",
"declaration": true,
"strict": true,
"outDir": ".",
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"importHelpers": true,
"strictNullChecks": false,
},
"include": ["src/backend"],
"exclude": []
}
@@ -0,0 +1,26 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ErrorDisplayComponent } from './error-display/error-display.component';
const routes: Routes = [{
path: "pluginmanager",
loadChildren: () => import('./pluginmanager/module').then(mod => mod.PluginModule)
},{
path: "",
component: HomeComponent
},{
path: "**",
component: ErrorDisplayComponent
}];
export function getRoutes(){
return routes
}
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
+5
View File
@@ -0,0 +1,5 @@
<clr-main-container >
<header-bar></header-bar>
<subnav></subnav>
<dynamic-loader style="height: 100%;"></dynamic-loader>
</clr-main-container>
@@ -0,0 +1,35 @@
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'dashboard'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('dashboard');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to dashboard!');
});
});
+32
View File
@@ -0,0 +1,32 @@
import { Component, ChangeDetectorRef, NgZone, ViewChild, OnInit, AfterContentInit, isDevMode } from '@angular/core';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SidebarEntryService } from './sidebar-entry-service.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentInit {
title = 'dashboard';
@ViewChild(SidebarComponent, {static: false})
sidebar: SidebarComponent
constructor(private zone:NgZone, private sidebarService: SidebarEntryService){
window["refresh"] = setInterval(() => zone.run(()=>{ /*this triggers an angular reload*/}), 200)
if(isDevMode()){
require("../assets/dev/FrontblockLib")
}
}
ngAfterContentInit(){
const _this = this;
(function awaitSidebar(){
if(_this.sidebar != null){
_this.sidebarService.setSidebar(_this.sidebar)
return
}
setTimeout(awaitSidebar,25)
})()
}
}
+69
View File
@@ -0,0 +1,69 @@
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { ClarityModule } from '@clr/angular';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { COMPILER_OPTIONS, CompilerFactory, Compiler } from '@angular/core';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { MainComponent } from './content-area/main.component';
import { DynamicLoaderComponent } from './dynamic-loader/dynamic-loader.component';
import { HomeComponent } from './home/home.component';
import { ErrorDisplayComponent } from './error-display/error-display.component';
import { HeaderBarComponent } from './header-bar/header-bar.component';
import { SubnavComponent } from './subnav/subnav.component';
import { environment } from 'src/environments/environment';
export function createCompiler(fn: CompilerFactory): Compiler {
return fn.createCompiler();
}
const declarations = [
AppComponent,
SidebarComponent,
MainComponent,
DynamicLoaderComponent,
HomeComponent,
HeaderBarComponent,
ErrorDisplayComponent,
SubnavComponent,
]
@NgModule({
declarations: declarations,
imports: [
FormsModule,
BrowserModule,
BrowserAnimationsModule,
ClarityModule,
AppRoutingModule,
],
entryComponents: [],
providers: [
{
provide: COMPILER_OPTIONS,
useValue: {},
multi: true
},
{
provide: CompilerFactory,
useClass: JitCompilerFactory,
deps: [COMPILER_OPTIONS]
},
{
provide: Compiler,
useFactory: createCompiler,
deps: [CompilerFactory]
}
],
bootstrap: [AppComponent]
})
export class AppModule{
}
@@ -0,0 +1,3 @@
<div class="content-area" style="max-height: 100%">
<router-outlet class="clr-all-12" ></router-outlet>
</div>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MainComponent } from './main.component';
describe('MainComponent', () => {
let component: MainComponent;
let fixture: ComponentFixture<MainComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MainComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MainComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,17 @@
import { Component, OnInit, ViewContainerRef, ViewChild } from '@angular/core';
@Component({
selector: 'content-area',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
@ViewChild('content', { read: ViewContainerRef, static: false })
content: ViewContainerRef;
constructor() { }
ngOnInit() {
}
}
@@ -0,0 +1,4 @@
<div class="content-container" style="height: 100%;">
<sidebar></sidebar>
<content-area style="height: 100%; width: 100%"></content-area>
</div>
@@ -0,0 +1,3 @@
.heightmax{
height: 100%!important;
}
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DynamicLoaderComponent } from './dynamic-loader.component';
describe('DynamicLoaderComponent', () => {
let component: DynamicLoaderComponent;
let fixture: ComponentFixture<DynamicLoaderComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DynamicLoaderComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DynamicLoaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,133 @@
/**
* Set existing vendor modules into SystemJS registry.
* This way SystemJS won't make HTTP requests to fetch imported modules
* needed by the dynamicaly loaded Widgets.
*/
import { System } from 'systemjs';
declare const SystemJS: System;
import * as angularRouter from '@angular/router';
import * as angularCore from '@angular/core';
import * as angularCommon from '@angular/common';
import * as angularCommonHttp from '@angular/common/http';
import * as angularForms from '@angular/forms';
import * as angularAnimations from '@angular/animations';
import * as angularAnimationsBrowser from '@angular/animations/browser'
import * as angularPlatformBrowser from '@angular/platform-browser';
import * as angularPlatformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as clarityModule from '@clr/angular';
import * as frontblockGenericTypes from 'frontblock-generic/Types.js'
import * as browserAnimationsModule from "@angular/platform-browser/animations";
import * as btcHdkey from "btc-hdkey"
import * as bitcoinjslib from "bitcoinjs-lib"
import * as fetch from "node-fetch"
import * as coinselect from "coinselect/accumulative"
import * as KnexModule from '../knex-config/knex-config.module'
SystemJS.set('@clr/angular', SystemJS.newModule(clarityModule));
SystemJS.set('@angular/router', SystemJS.newModule(angularRouter));
SystemJS.set('@angular/core', SystemJS.newModule(angularCore));
SystemJS.set('@angular/common', SystemJS.newModule(angularCommon));
SystemJS.set('@angular/common/http', SystemJS.newModule(angularCommonHttp));
SystemJS.set('@angular/forms', SystemJS.newModule(angularForms));
SystemJS.set('@angular/animations', SystemJS.newModule(angularAnimations));
SystemJS.set('@angular/animations/browser', SystemJS.newModule(angularAnimationsBrowser));
SystemJS.set('@angular/platform-browser', SystemJS.newModule(angularPlatformBrowser));
SystemJS.set('@angular/platform-browser/animations', SystemJS.newModule(browserAnimationsModule));
SystemJS.set('@angular/platform-browser-dynamic', SystemJS.newModule(angularPlatformBrowserDynamic));
SystemJS.set('frontblock-generic/Types', SystemJS.newModule(frontblockGenericTypes));
SystemJS.set('btc-hdkey', SystemJS.newModule(btcHdkey))
SystemJS.set('bitcoinjs-lib', SystemJS.newModule(bitcoinjslib))
SystemJS.set('node-fetch', SystemJS.newModule(fetch))
SystemJS.set('coinselect/accumulative', SystemJS.newModule(coinselect))
SystemJS.set('knexconfig', SystemJS.newModule(KnexModule))
SystemJS.config({ meta: { '*': { authorization: true } } });
/** --------- */
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { Router } from '@angular/router';
import { FrontendPlugin, SidebarEntries, SidebarEntry } from "frontblock-generic/Plugin"
import { environment } from "../../environments/environment"
const fb = environment.production ? window["fb"] : {
UpdateManager: {
getLoadedPluginNames: () => ["ApiClient", "Wallet"]
}
}
@Component({
selector: 'dynamic-loader',
templateUrl: './dynamic-loader.component.html',
styleUrls: ['./dynamic-loader.component.scss']
})
export class DynamicLoaderComponent implements AfterViewInit {
@ViewChild(SidebarComponent, { static: false })
private sidebar: SidebarComponent
constructor(
private router: Router,
) {
}
ngAfterViewInit() {
console.log("env", environment)
this.loadWidgets()
}
private async loadWidgets() {
while (!fb.UpdateManager) {
await new Promise((resolve) => setTimeout(resolve, 50))
}
const pluginNames = await fb.UpdateManager.getLoadedPluginNames()
pluginNames.forEach(element => this.installWidget(element));
}
private async installWidget(pluginName: string) {
let module;
if (!angularCore.isDevMode()){
module = await SystemJS.import("plugins/" + pluginName + ".js");
}else{
if(environment.loadLocal){
console.log("Loading "+pluginName+" from angular tsc-out")
module = await import("../"+pluginName.toLocaleLowerCase()+"/src/frontend/module")
}else{
console.log("Loading "+pluginName+" from fake backend")
module = await SystemJS.import("assets/" + pluginName.toLowerCase() + ".js")
}
}
const plugin:FrontendPlugin = new module['PluginModule']()
const entry: SidebarEntries | SidebarEntry = plugin.getSidebarEntry()
const rc = this.router.config
switch (typeof (<any>entry).links) {
case "undefined":
const e: SidebarEntry = <SidebarEntry>entry
e.route = "plugin/" + e.route
this.sidebar.entries.push(e)
rc.unshift({
path: "plugin",
loadChildren: async () => module['PluginModule']
})
break;
case "object":
const m: SidebarEntries = <SidebarEntries>entry
m.links = m.links.map(link => {
return { text: link.text, route: m.parentRoute + "/" + link.route }
})
this.sidebar.multientires.push(m)
rc.unshift({
path: m.parentRoute,
loadChildren: async () => module['PluginModule']
})
}
this.router.resetConfig(rc)
}
}
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'exclamations',
template: `
<span style="color: blue">!!!</span>
`
})
export class ANestedComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
@@ -0,0 +1 @@
<p>Oops that didn't work!</p>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ErrorDisplayComponent } from './error-display.component';
describe('ErrorDisplayComponent', () => {
let component: ErrorDisplayComponent;
let fixture: ComponentFixture<ErrorDisplayComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ErrorDisplayComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ErrorDisplayComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-error-display',
templateUrl: './error-display.component.html',
styleUrls: ['./error-display.component.scss'],
})
export class ErrorDisplayComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@@ -0,0 +1,22 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ErrorDisplayComponent } from './error-display.component';
import { ANestedComponent } from './a-nested.component';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [CommonModule, RouterModule.forChild([{path: "helloWorld", component: ErrorDisplayComponent}])],
exports: [RouterModule],
declarations: [
ErrorDisplayComponent,
ANestedComponent
],
entryComponents: [ErrorDisplayComponent],
providers: [{
provide: 'provider',
useValue: ErrorDisplayComponent
}],
})
export class PluginModule { }
@@ -0,0 +1,12 @@
<clr-header class="header header-1">
<div class="branding">
<span class="title">Frontblock</span>
</div>
<div class="header-actions">
<a class="nav-link nav-icon-text">
<clr-icon shape="bug"></clr-icon>
<span class="nav-text">ALPHA {{devmode}}</span>
</a>
</div>
</clr-header>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HeaderBarComponent } from './header-bar.component';
describe('HeaderBarComponent', () => {
let component: HeaderBarComponent;
let fixture: ComponentFixture<HeaderBarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HeaderBarComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HeaderBarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,15 @@
import { Component, OnInit, isDevMode } from '@angular/core';
import { environment } from '../../environments/environment'
@Component({
selector: 'header-bar',
templateUrl: './header-bar.component.html',
styleUrls: ['./header-bar.component.scss']
})
export class HeaderBarComponent implements OnInit {
devmode = isDevMode()?(environment.loadLocal?"{ ng-DEV }":"{ ng-PRODLIKE }"):""
constructor() { }
ngOnInit() {
}
}
@@ -0,0 +1 @@
<p>home works!</p>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HomeComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'exclamations',
template: `
<span style="color: blue">!!!</span>
`
})
export class ANestedComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
@@ -0,0 +1,24 @@
import { Component, OnInit } from '@angular/core';
declare const fb
@Component({
selector: 'HTMLSUPPLIER', //!!!!
template: `
<div class="card">
<div class="card-block">
<div class="card-title">
HTMLSUPPLIER <br> ${Object.keys(fb.HtmlSupplier).join("<br>")}
</div>
<div class="card-text">
Hello World <exclamations></exclamations>
</div>
</div>
</div>
`
})
export class PluginComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
@@ -0,0 +1,21 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PluginComponent } from './component';
import { ANestedComponent } from './a-nested.component';
import { RouterModule } from '@angular/router';
import { FrontendPlugin, SidebarEntry } from 'frontblock-generic/Plugin';
@NgModule({
imports: [CommonModule, RouterModule.forChild([{path: "htmlsupplier", component: PluginComponent}])],
exports: [RouterModule],
declarations: [
PluginComponent,
ANestedComponent
],
entryComponents: [PluginComponent],
providers: [{
provide: 'provider',
useValue: PluginComponent
}]
})
export class PluginModule{}
@@ -0,0 +1 @@
<p>knex-config works!</p>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { KnexConfigComponent } from './knex-config.component';
describe('KnexConfigComponent', () => {
let component: KnexConfigComponent;
let fixture: ComponentFixture<KnexConfigComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ KnexConfigComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(KnexConfigComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,196 @@
import { Component, OnInit, Input } from '@angular/core';
declare const fb
@Component({
selector: 'knex-config',
template: `
<div class="clr-row">
<div class="card clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-auto clr-col-xl-auto">
<div class="card-header">
Database configuration
</div>
<div class="card-block">
<div class="card-text">
<clr-tabs>
<clr-tab>
<button clrTabLink id="link1">mySQL</button>
<ng-template [(clrIfActive)]="mode['mysql']">
<clr-tab-content id="content1">
<form clrForm clrLayout="horizontal">
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">host</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="mysql-host" [(ngModel)]="mysql['connection']['host']" placeholder="127.0.0.1" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">user</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="mysql-user" [(ngModel)]="mysql['connection']['user']" placeholder="root" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">password</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="password" name="mysql-password" [(ngModel)]="mysql['connection']['password']" placeholder="*****" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">database</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="mysql-database" [(ngModel)]="mysql['connection']['database']" placeholder="db_name" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">version</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="mysql-version" [(ngModel)]="mysql['version']" placeholder="5.7" required />
</clr-input-container>
</form>
</clr-tab-content>
</ng-template>
</clr-tab>
<clr-tab>
<button clrTabLink>pgSQL</button>
<ng-template [(clrIfActive)]="mode['pg']">
<clr-tab-content>
<form clrForm clrLayout="horizontal">
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">host</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="pg-host" [(ngModel)]="pg['connection']['host']" placeholder="127.0.0.1" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">user</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="pg-host" [(ngModel)]="pg['connection']['user']" placeholder="root" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">password</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="password" name="pg-host" [(ngModel)]="pg['connection']['password']" placeholder="*****" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">database</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="pg-host" [(ngModel)]="pg['connection']['database']" placeholder="db_name" required />
</clr-input-container>
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">version</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="pg-host" [(ngModel)]="pg['version']" placeholder="7.2" required />
</clr-input-container>
</form>
</clr-tab-content>
</ng-template>
</clr-tab>
<clr-tab>
<button clrTabLink>SQLite3</button>
<ng-template [(clrIfActive)]="mode['sqlite3']">
<clr-tab-content>
<form clrForm clrLayout="horizontal">
<clr-input-container >
<label class="clr-col-12 clr-col-md-4">file</label>
<input class="clr-col-12 clr-col-md-8" clrInput type="text" name="sqlite-file" [(ngModel)]="sqlite3['connection']['filename']" placeholder="./data/benis.sqlite" required />
</clr-input-container>
</form>
</clr-tab-content>
</ng-template>
</clr-tab>
</clr-tabs>
</div>
</div>
<div class="card-footer">
<button *ngIf="!saving" class="btn btn-success-outline" (click)="save()">
<span>Save</span>
</button>
</div>
</div>
</div>
`
})
export class KnexConfigComponent implements OnInit{
@Input("fbPlugin")
fbPlugin:string
conf: KnexConfig
pg:PgConfig = {
client: "pg",
version: "",
connection: {
database: "",
host: "",
password: "",
user: ""
}
}
mysql:MysqlConfig = {
client: 'mysql',
version: "",
connection: {
database: "",
host: "",
password: "",
user: ""
}
}
sqlite3:SqliteConfig = {
client: "sqlite3",
connection: {
filename: ""
}
}
mode:{[key in KnexDrivers]: boolean} = {
pg: false,
mysql: false,
sqlite3: true
}
async ngOnInit(){
if(!fb[this.fbPlugin]){
throw new Error("Knex config component doesn't have fb."+this.fbPlugin)
}
const c = await fb[this.fbPlugin].getConfig()
this.conf = c.dbConf
Object.keys(this.mode).forEach(knexType => {
this.mode[knexType] = knexType === this.conf.client
if(this.mode[knexType]){
console.log(knexType, this.conf)
this[knexType] = this.conf
}
})
window['knex'] = this
}
save(){
const modeName = Object.entries(this.mode).find(([key, active]) => active)[0]
fb[this.fbPlugin].setConfigKey('dbConf', this[modeName]).then(console.log)
}
}
type KnexDrivers = "pg" | "mysql" | "sqlite3"
type BaseConfig<Driver extends KnexDrivers> = {
client: Driver
}
type PgConfig = BaseConfig<'pg'> & {
version: string
connection: {
host: string,
user: string,
password: string,
database: string
}
}
type MysqlConfig = BaseConfig<'mysql'> & {
version: string
connection: {
host: string,
user: string,
password: string,
database: string
}
}
type SqliteConfig = BaseConfig<'sqlite3'> & {
connection: {
filename: string
}
}
type KnexConfig = SqliteConfig | PgConfig | MysqlConfig
@@ -0,0 +1,23 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { KnexConfigComponent } from './knex-config.component';
import { ClarityModule } from '@clr/angular';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FormsModule,
ClarityModule,
],
exports: [
KnexConfigComponent
],
declarations: [
KnexConfigComponent
],
entryComponents: [],
providers: []
})
export class KnexConfigModule{}
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'exclamations',
template: `
<span style="color: blue">!!!</span>
`
})
export class ANestedComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
@@ -0,0 +1,24 @@
import { Component, OnInit } from '@angular/core';
declare const fb
@Component({
selector: 'PAYMENTMANAGER', //!!!!
template: `
<div class="card">
<div class="card-block">
<div class="card-title">
PAYMENTMANAGER <br> ${Object.keys(fb.PaymentManager).join("<br>")}
</div>
<div class="card-text">
Hello World <exclamations></exclamations>
</div>
</div>
</div>
`
})
export class PluginComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
@@ -0,0 +1,22 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PluginComponent } from './component';
import { ANestedComponent } from './a-nested.component';
import { RouterModule } from '@angular/router';
import { FrontendPlugin, SidebarEntry } from 'frontblock-generic/Plugin';
@NgModule({
imports: [CommonModule, RouterModule.forChild([{path: "paymentmanager", component: PluginComponent}])],
exports: [RouterModule],
declarations: [
PluginComponent,
ANestedComponent
],
entryComponents: [PluginComponent],
providers: [{
provide: 'provider',
useValue: PluginComponent
}]
})
export class PluginModule{
}
@@ -0,0 +1,47 @@
import { Component, OnInit } from '@angular/core';
import { SidebarEntry } from 'frontblock-generic/Plugin';
declare const fb
@Component({
selector: 'debug', //!!!!
template: `
<div class="clr-row">
<div class="clr-col">
<div class="card">
<div class="card-header">
DEBUG
</div>
<div class="card-block">
<div class="card-title">
SETUP
</div>
<div class="card-text">
<p>
Press this button to install all plugins.
<br>
Once the installation is done the page will refresh automatically
</p>
</div>
</div>
<div class="card-footer">
<button class="btn btn-warning-outline" onclick="setup()">SETUP</button>
</div>
</div>
</div>
</div>
`
})
export class PluginmanagerDEBUG implements OnInit {
constructor() { }
ngOnInit() { }
}
export const sidebarEntry: SidebarEntry = {
icon: "wrench",
route: "dev/pluginmanager",
text: "DEV Plugin manager",
}
@@ -0,0 +1,31 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { PluginmanagerDEBUG } from './debug.component';
import { PluginsComponent } from './plugins.component';
import { FrontendPlugin, SidebarEntries } from 'frontblock-generic/Plugin';
import { ClarityModule } from '@clr/angular';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ClarityModule,
CommonModule,
RouterModule.forChild([
{path: "debug", component: PluginmanagerDEBUG},
{path: "plugins", component: PluginsComponent}
]),
],
exports: [RouterModule],
declarations: [
PluginmanagerDEBUG,
PluginsComponent
]
})
export class PluginModule{
}
@@ -0,0 +1,156 @@
import { Component, OnInit, isDevMode } from '@angular/core';
declare const fb
@Component({
selector: 'plugins', //!!!!
template: `
<clr-modal [(clrModalOpen)]="updatepending">
<h3 class="modal-title">Confirm installation</h3>
<div class="modal-body">
<p>{{updateCandidate}} But not much to say...</p>
</div>
<div class="modal-footer">
<button class="btn btn-icon btn-success" (click)="download(updateCandidate)"><clr-icon shape="check"></clr-icon></button>
<button class="btn btn-icon btn-danger" (click)="cancelModal()"><clr-icon shape="times"></clr-icon></button>
</div>
</clr-modal>
<div class="clr-row">
<div class="card clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-12 clr-col-xl-12">
<div class="card-header">
Plugins
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="line.severity">
<clr-alert-item>
<span class="alert-text">
{{line.message}}
</span>
</clr-alert-item>
</clr-alert>
<div *ngIf="loading" class="card-block">
<span class="spinner spinner-inline"></span>
</div>
<div *ngIf="plugins.length !== 0 && !loading" class="card-block">
<div class="card-text">
<clr-datagrid>
<clr-dg-column>Name</clr-dg-column>
<clr-dg-column>Available</clr-dg-column>
<clr-dg-column>Installed</clr-dg-column>
<clr-dg-column>Status</clr-dg-column>
<clr-dg-row *clrDgItems="let line of plugins">
<clr-dg-cell>{{line.name}}</clr-dg-cell>
<clr-dg-cell>
<span *ngIf="line.installed != line.available" class="label info">{{line.available}}</span>
<span *ngIf="line.installed == line.available">{{line.available}}</span>
</clr-dg-cell>
<clr-dg-cell>{{line.installed}}</clr-dg-cell>
<clr-dg-cell>{{line.status}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded>
<button *ngIf="line.status === 'Stopped'" class="btn btn-icon btn-success-outline" (click)="start(line.name)"><clr-icon shape="play"></clr-icon></button>
<button *ngIf="line.status === 'Running'" class="btn btn-icon btn-warning-outline" (click)="stop(line.name)"><clr-icon shape="stop"></clr-icon></button>
<button *ngIf="line.status === 'Stopped'" class="btn btn-icon btn-danger-outline" (click)="delete(line.name)"><clr-icon shape="trash"></clr-icon></button>
<button *ngIf="line.status === 'Available'" class="btn btn-icon btn-info-outline" (click)="showConfirmation(line.name)"><clr-icon shape="download"></clr-icon></button>
<button *ngIf="line.available !== line.installed && line.status === 'Stopped'" class="btn btn-icon btn-outline " (click)="showConfirmation(line.name)">
<clr-icon shape="sync"></clr-icon>
</button>
</clr-dg-row-detail>
</clr-dg-row>
<clr-dg-footer>
<clr-dg-pagination #pagination [clrDgPageSize]="10">
<clr-dg-page-size [clrPageSizeOptions]="[10,20,50,100]">per page</clr-dg-page-size>
{{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
of {{pagination.totalItems}}
</clr-dg-pagination>
</clr-dg-footer>
</clr-datagrid>
</div>
</div>
<div class="card-footer">
<button *ngIf="!reloading" class="btn btn-sm btn-link" (click)="reload()">Check</button>
</div>
</div>
</div>
`
})
export class PluginsComponent implements OnInit {
plugins = [{
name: "test",
available: "0.0.1",
installed: "0.0.1",
status: "Running"
}, {
name: "test II: Return of test",
available: "0.0.1",
installed: "0.0.1",
status: "Stopped"
}, {
name: "test 3",
available: "0.0.2",
installed: "",
status: "Available"
}, {
name: "test IV: minor bump",
available: "0.9.27",
installed: "0.0.11",
status: "Stopped"
},]
reloading = false
updatepending = false
updateCandidate = ""
constructor() { }
start(name:string) {
this.plugins.find((el) => el.name === name)!.status = "Running"
}
stop(name) {
this.plugins.find((el) => el.name === name)!.status = "Stopped"
}
delete(name) {
let plugin = this.plugins.find((el) => el.name === name)
plugin!.status = "Available"
plugin!.installed = ""
}
showConfirmation(name) {
this.updateCandidate = name
this.updatepending = !this.updatepending
}
download(name) {
let plugin = this.plugins.find((el) => el.name === name)
plugin!.status = "Stopped"
plugin!.installed = plugin!.available
this.updatepending = !this.updatepending
}
cancelModal() {
this.updateCandidate = ""
this.updatepending = !this.updatepending
}
async reload(){
this.reloading = true
if(isDevMode()){
await new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
this.plugins = this.plugins.map(plugin => {
const parts = plugin.available.split('.')
plugin.available = parts[0]+"."+parts[1]+"."+(parseInt(parts[2])+1)
return plugin
})
this.reloading = false
}
}
ngOnInit() { }
}
@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { SidebarComponent } from './sidebar/sidebar.component';
@Injectable({
providedIn: 'root'
})
export class SidebarEntryService {
private sidebar:SidebarComponent
constructor() { }
setSidebar(sidebar){
this.sidebar = sidebar
}
getSidebar():SidebarComponent{
return this.sidebar
}
}
@@ -0,0 +1,19 @@
<clr-vertical-nav [clr-nav-level]="1" class="nav-trigger--bottom" style="height: 100%;" [clrVerticalNavCollapsible]="true" [(clrVerticalNavCollapsed)]="collapsed" >
<clr-vertical-nav-group *ngFor="let e of multientires" routerLinkActive="active">
<clr-icon [attr.shape]="e.icon" class="is-solid" clrVerticalNavIcon></clr-icon>
{{e.text}}
<clr-vertical-nav-group-children>
<a clrVerticalNavLink
*ngFor="let l of e.links"
[routerLink]="l.route"
routerLinkActive="active">
{{l.text}}
</a>
</clr-vertical-nav-group-children>
</clr-vertical-nav-group>
<a *ngFor="let entry of entries" clrVerticalNavLink routerLinkActive="active" [routerLink]="entry.route">
<clr-icon [attr.shape]="entry.icon" class="is-solid" clrVerticalNavIcon></clr-icon>
{{entry.text}}
</a>
</clr-vertical-nav>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SidebarComponent } from './sidebar.component';
describe('SidebarComponent', () => {
let component: SidebarComponent;
let fixture: ComponentFixture<SidebarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SidebarComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SidebarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,36 @@
import { Component, OnInit } from '@angular/core';
import { SidebarEntries, SidebarEntry } from 'frontblock-generic/Plugin';
@Component({
selector: 'sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
collapsed = true
entries:SidebarEntry[] = [
]
multientires:SidebarEntries[] = [{
icon: "bundle",
text: "Update Manager",
parentRoute: "pluginmanager",
links: [{
route: "pluginmanager/debug",
text: "DEBUG"
},{
route: "pluginmanager/admin",
text: "Dashboard"
},{
route: "pluginmanager/plugins",
text: "Plugins"
}]
}]
constructor() { }
ngOnInit() {
}
}
@@ -0,0 +1,7 @@
<nav class="subnav">
<ul class="nav">
<li class="nav-item">
<a class="nav-link active" href="#">Dashboard</a>
</li>
</ul>
</nav>
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SubnavComponent } from './subnav.component';
describe('SubnavComponent', () => {
let component: SubnavComponent;
let fixture: ComponentFixture<SubnavComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SubnavComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SubnavComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'subnav',
templateUrl: './subnav.component.html',
styleUrls: ['./subnav.component.scss']
})
export class SubnavComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
+59
View File
@@ -0,0 +1,59 @@
kind: pipeline
name: default
steps:
- name: restore cache
image: drillster/drone-volume-cache
settings:
restore: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: npm install
image: node:12
commands:
- npm install
- name: npm run build
image: node:12
commands:
- npm run build
- name: rebuild cache
image: drillster/drone-volume-cache
settings:
rebuild: true
mount:
- ./node_modules
volumes:
- name: cache
path: /cache
- name: deploy plugin
image: node:12
commands:
- git config --global user.email "${DRONE_COMMIT_AUTHOR_EMAIL}"
- git config --global user.name "${DRONE_COMMIT_AUTHOR}"
- git clone https://gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git
- cp -r ./dist/* ./${DRONE_REPO_NAME}
- cd ./${DRONE_REPO_NAME}
- git add -A
- git commit --allow-empty -m "drone tagged as version ${DRONE_TAG}"
- git tag ${DRONE_TAG}
- git push https://$GIT_USER:$GIT_PASSWORD@gitea.frontblock.me/fb-dist/${DRONE_REPO_NAME}.git master ${DRONE_TAG}
environment:
GIT_USER:
from_secret: git_user
GIT_PASSWORD:
from_secret: git_password
when:
event:
- tag
volumes:
- name: cache
host:
path: /tmp
+11
View File
@@ -0,0 +1,11 @@
dist
kfs
.rpt2_cache
node_modules
lib
*.d.ts
*.js
*.ts
!src/**/*
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
{
"name": "frontblock",
"version": "0.9.10",
"description": "frontblock shop-side library ",
"main": "FrontblockApiClient.js",
"scripts": {
"build-backend": "webpack --config src/backend/webpack.prod.js --progress --colors",
"build-frontend": "webpack --config src/frontend/webpack.prod.js --progress --colors",
"build": "npm run clean; npm run build-backend; npm run build-frontend",
"clean": "rm -rf *.js *.ts backend frontend .rpt2_cache lib dist",
"update-frontblock": "rm -rf node_modules/frontblock*; npm install"
},
"keywords": [
"api",
"client",
"frontblock"
],
"author": "",
"license": "ISC",
"dependencies": {
"@angular/common": "^8.2.1",
"@angular/core": "^8.2.1",
"@angular/forms": "^8.2.1",
"@angular/platform-browser": "^8.2.1",
"@angular/router": "^8.2.1",
"@clr/angular": "^2.1.1",
"@types/node": "^11.13.10",
"adm-zip": "^0.4.13",
"angular": "^1.7.8",
"bip39": "^3.0.2",
"bitcoinjs-lib": "^5.0.4",
"bsock": "^0.1.9",
"btc-hdkey": "0.0.17",
"coinselect": "^3.1.11",
"easy-unzip": "^1.1.0",
"express": "^4.16.4",
"frontblock-generic": "^0.28.4",
"hdkey": "^1.1.1",
"key-file-storage": "^2.2.1",
"knex": "^0.19.2",
"log4js": "^4.3.1",
"minimist": "^1.2.0",
"node-fetch": "^2.5.0",
"original-fs": "^1.1.0",
"rxjs": "^6.5.2",
"rxjs-compat": "^6.5.2",
"unzip": "^0.1.11",
"uuid": "^3.3.2"
},
"devDependencies": {
"ts-loader": "^6.0.4",
"typescript": "^3.4.5",
"webpack": "^4.39.2",
"webpack-cli": "^3.3.6",
"webpack-node-externals": "^1.7.2"
}
}
@@ -0,0 +1,118 @@
import { socketioRPC } from "frontblock-generic/RPC";
import { DatabasePlugin, TableDefiniton } from "frontblock-generic/DatabasePlugin"
import { Coin } from "frontblock-generic/Types";
import * as knex from 'knex';
import * as Logger from 'log4js'
Logger.configure({
appenders: {
"frontblock-wallet": { type: 'stdout' },
//app: { type: 'file', filename: 'application.log' }
},
categories: {
default: { appenders: [ 'frontblock-wallet' ], level: 'debug' }
}
})
const logger = Logger.getLogger("frontblock-wallet")
export type PublicNode = {
coin: Coin
net: 'testnet' | 'mainnet'
url: URL
}
export type WalletPluginConf = {
btcConf: {
publicNodes: PublicNode[]
}
}
export type Key = {
name: string
type: 'plain' | 'encrypted'
value: string
coin: Coin
}
export default class WalletPlugin extends DatabasePlugin<WalletPluginConf>{
constructor(){
super("Wallet")
}
getDefaultConfig(): WalletPluginConf & { dbConf: knex.Config; } {
return {
btcConf: {
publicNodes: [
{coin: 'BTC', net: 'testnet', url: new URL('https://testnet-api.smartbit.com.au/v1/blockchain')},
{coin: 'BTC', net: 'mainnet', url: new URL('https://api.smartbit.com.au/v1/blockchain')}
]
},
dbConf: {
client: 'sqlite3',
connection: {
filename: "./data/Wallet.sqlite"
},
useNullAsDefault: true
}
}
}
protected exportExtraRPCs(): socketioRPC[] {
return [
{
name: "putKey",
func: async(
name: string,
type: 'plain' | 'encrypted',
value: string,
coin: Coin
) => {
return await this.putKey({
name: name,
type:type,
value:value,
coin:coin
})
},
type: 'call',
visibility: 'private'
},{
name: "delKey",
func: async(name: string) => { return await this.delKey(name) },
type: 'call',
visibility: 'private'
},{
name: "getKeys",
func: async() => { return await this.getKeys() },
type: 'call',
visibility: 'private'
}
]
}
public async putKey(key: Key){
return await this.knex('keys').insert([key])
}
public async delKey(name: string){
return await this.knex('keys')
.where('name', name)
.del()
}
public async getKeys(): Promise<Key[]>{
return await this.knex.select('*').from('keys')
}
protected getTableDefinitions(): TableDefiniton[] {
return [{
name: 'keys',
tableBuilder: function (table) {
table.string('name').primary();
table.string('type');
table.string('value');
table.string('coin');
}
}]
}
}
@@ -0,0 +1,37 @@
const nodeExternals = require('webpack-node-externals');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'production',
target: "node",
entry: path.resolve(__dirname, 'Plugin.ts'),
output: {
path: path.resolve(__dirname, '../../dist'),
filename: 'Plugin.js',
libraryTarget: 'commonjs',
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.ts?$/, loader: "ts-loader" }
]
},
optimization: {
minimize: false
},
node: {
global: true,
process: true,
__filename: false,
__dirname: false,
Buffer: true,
},
externals:{
knex: "../node_modules/knex"
}
}
@@ -0,0 +1,174 @@
import { Component, OnInit, isDevMode } from '@angular/core';
import { PluginsComponent } from './btc.component';
import { ClrDatagridStringFilterInterface, ClrDatagridNumericFilterInterface, ClrDropdownModule } from '@clr/angular';
declare const fb
@Component({
selector: 'address-viewer', //!!!!
template: `
<div class="clr-row">
<div *ngIf="regularAddresses.length != 0" class="clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-12 clr-col-xl-6">
<div class="card">
<div class="card-header">
Addresses
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="line.severity">
<clr-alert-item>
<span class="alert-text">
{{line.message}}
</span>
</clr-alert-item>
</clr-alert>
<clr-datagrid class="datagrid-compact ">
<clr-dg-column>Address</clr-dg-column>
<clr-dg-column>
Balance
</clr-dg-column>
<clr-dg-column>
Pending
</clr-dg-column>
<clr-dg-column>
Estimate total
<clr-dg-numeric-filter [clrDgNumericFilter]="otherBalanceFilter" [clrFilterValue]="[0, null]"></clr-dg-numeric-filter>
</clr-dg-column>
<clr-dg-row *clrDgItems="let line of regularAddresses">
<clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace">
<span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}}
</span>
</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded >
<div class="clr-row">
<div class="clr-col-3">
<button class="btn btn-info-outline" (click)="parent.addrExplorer(line.address)">Explorer</button>
</div>
<div *ngIf="parent.keys[line.address] != null" class="clr-col-9" style="word-break:break-all">
<h6 style="margin-top: 0">Derivation </h6>
{{parent.keys[line.address].derivation}}
<h6> Public key </h6>
{{parent.keys[line.address].publicExtendedKey}}
<h6> Private key </h6>
{{parent.keys[line.address].privateExtendedKey}}
</div>
</div>
</clr-dg-row-detail>
</clr-dg-row>
<clr-dg-footer>
<clr-dg-pagination #pagination2 [clrDgPageSize]="10">
<clr-dg-page-size [clrPageSizeOptions]="[5,10,20,50,100]">per page</clr-dg-page-size>
{{pagination2.firstItem + 1}} - {{pagination2.lastItem + 1}}
of {{pagination2.totalItems}}
</clr-dg-pagination>
</clr-dg-footer>
</clr-datagrid>
</div>
</div>
<div *ngIf="changeAddresses.length != 0" class="clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-12 clr-col-xl-6">
<div class="card">
<div class="card-header">
Change Addresses
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="line.severity">
<clr-alert-item>
<span class="alert-text">
{{line.message}}
</span>
</clr-alert-item>
</clr-alert>
<clr-datagrid class="datagrid-compact">
<clr-dg-column>Address</clr-dg-column>
<clr-dg-column>
Balance
</clr-dg-column>
<clr-dg-column>
Pending
</clr-dg-column>
<clr-dg-column>
Estimate total
<clr-dg-numeric-filter [clrDgNumericFilter]="balanceFilter" [clrFilterValue]="[0.00000001, null]"></clr-dg-numeric-filter>
</clr-dg-column>
<clr-dg-row *clrDgItems="let line of changeAddresses">
<clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace">
<span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}}
</span>
</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded >
<div class="clr-row">
<div class="clr-col-3">
<button class="btn btn-info-outline" (click)="parent.addrExplorer(line.address)">Explorer</button>
<p>
</div>
<div *ngIf="parent.keys[line.address] != null" class="clr-col-9" style="word-break:break-all">
<h6 style="margin-top: 0">Derivation </h6>
{{parent.keys[line.address].derivation}}
<h6> Public key </h6>
{{parent.keys[line.address].publicExtendedKey}}
<h6> Private key </h6>
{{parent.keys[line.address].privateExtendedKey}}
</div>
</div>
</clr-dg-row-detail>
</clr-dg-row>
<clr-dg-footer>
<clr-dg-pagination #pagination [clrDgPageSize]="10">
<clr-dg-page-size [clrPageSizeOptions]="[5,10,20,50,100]">per page</clr-dg-page-size>
{{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
of {{pagination.totalItems}}
</clr-dg-pagination>
</clr-dg-footer>
</clr-datagrid>
</div>
</div>
</div>
`
})
export class AddressViewerComponent implements OnInit{
balanceFilter = new BalanceFilter()
otherBalanceFilter = new BalanceFilter()
regularAddresses = []
changeAddresses = []
keys = {}
parent:PluginsComponent
ngOnInit() { }
setParent(parent:PluginsComponent){
this.parent = parent
}
setRegularAddresses(addresses){
this.regularAddresses = addresses
}
setChangeAddresses(addresses){
this.changeAddresses = addresses
}
}
class BalanceFilter implements ClrDatagridNumericFilterInterface<any>{
accepts(item: any, low: number, high: number): boolean {
high = parseFloat(""+high)
low = parseFloat(""+low)
const balance = (parseFloat(item.unconfirmed.balance) + parseFloat(item.confirmed.balance))
return (Number.isNaN(low) || balance >= low)
&& (Number.isNaN(high) || balance <= high)
}
}
@@ -0,0 +1,702 @@
import { Component, OnInit, isDevMode, ViewChild, AfterViewInit, OnDestroy, HostListener } from '@angular/core';
import { WalletGeneratorComponent } from './wallet-generator.component';
import { WalletPickerComponent } from './wallet-picker.component';
import { HDKey } from "btc-hdkey"
import { AddressViewerComponent } from './address-viewer.component';
const coinselect = require('coinselect/accumulative')
const fetch = require("node-fetch")
import { TransactionBuilder, Signer } from 'bitcoinjs-lib'
import { networks } from 'bitcoinjs-lib'
import { SubscriptionResponse, ErrorResponse } from 'frontblock-generic/Types';
let feeRate = 5 // satoshis per byte
const hdkey = new HDKey()
declare const fb
@Component({
selector: 'plugins', //!!!!
template: `
<wallet-generator></wallet-generator>
<!-- loading -->
<clr-modal [clrModalSize]="'md'" [(clrModalOpen)]="loading">
<div class="modal-body ">
<span class="spinner spinner-inverse spinner-md">
Loading...
</span>
<h3>Checking addresses</h3> <br>
Checking the first {{loadingN*115}} addresses. <br>
Found addresses containing balance: {{regaddresses.length + changeaddresses.length}}
</div>
</clr-modal>
<!-- / loading -->
<!-- faucets -->
<div *ngIf="mode.net == 'testnet'" class="clr-all-12">
<div class="card">
<div class="card-header">
Faucet
</div>
<div class="card-block" >
<button class="btn btn-icon btn-info-outline" onclick="window.open('https://testnet-faucet.mempool.co/', '_blank')"><clr-icon shape="fuel"></clr-icon></button>
<button class="btn btn-icon btn-info-outline" onclick="window.open('https://bitcoinfaucet.uo1.net/', '_blank')"><clr-icon shape="fuel"></clr-icon></button>
<button class="btn btn-icon btn-info-outline" onclick="window.open('https://coinfaucet.eu/en/btc-testnet/', '_blank')"><clr-icon shape="fuel"></clr-icon></button>
<button class="btn btn-icon btn-success-outline" onclick="window.open('https://www.google.com/search?q=btc+testnet+faucet&oq=btc+testnet+faucet', '_blank')"><clr-icon shape="plus"></clr-icon> more</button>
</div>
<div class="card-footer" >
Get free test-BTC
</div>
</div>
</div>
<!-- /faucets -->
<!-- row 1 -->
<div class="clr-all-12">
<!-- wallet picker + send box + balance box -->
<div class="clr-row">
<!-- left column -->
<div class="clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-5 clr-col-xl-5">
<!-- Wallet picker -->
<div class="clr-row">
<walletpicker class="clr-all-12"></walletpicker>
</div>
<!-- /Wallet picker -->
<!-- Send box -->
<div *ngIf="mode.type=='private'" class="clr-row">
<div class="clr-all-12">
<div class="card">
<div class="card-header">
Send
</div>
<clr-alert *ngFor="let error of errors" [clrAlertType]="'danger'">
<clr-alert-item>
<span class="alert-text">
{{error}}
</span>
</clr-alert-item>
</clr-alert>
<clr-alert *ngFor="let success of successes" [clrAlertType]="'success'">
<clr-alert-item>
<span class="alert-text">
{{success}}
</span>
</clr-alert-item>
</clr-alert>
<div class="card-block" >
<div class="clr-row" style="padding-left:12px; padding-right:12px">
<input [(ngModel)]="sendTo" type="text" placeholder="To address" class="clr-input clr-col-12" />
<input [(ngModel)]="sendAmount" type="text" min="0" placeholder="Amount" class="clr-input clr-col-12" style="margin-top:12px; margin-borrom:12px" />
</div>
</div>
<div class="card-footer" *ngIf="!sending" >
<button class="btn btn-success-outline" (click)="createAndSendTx(sendTo, sendAmount)">send</button>
</div>
</div>
</div>
</div>
<!-- /Send Box -->
</div>
<!-- /left column -->
<!-- right column -->
<div class="clr-col-12 clr-col-sm-12 clr-col-md-12 clr-col-lg-7 clr-col-xl-7" >
<!-- Balance box -->
<div *ngIf="rootkey.publicExtendedKey != ''" class="card">
<div class="card-header" style="word-break: break-all">
<span *ngIf="mode.net=='testnet'" class="label label-danger">Testnet</span>{{rootkey.publicExtendedKey}}
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="line.severity">
<clr-alert-item>
<span class="alert-text">
{{line.message}}
</span>
</clr-alert-item>
</clr-alert>
<div class="card-block">
<h3 style="margin-top:12px">{{balanceDisplay.total | number: '1.8-18'}} BTC </h3>
<p class="monospace">
<span *ngIf="balanceDisplay.unconfirmed < 0">&nbsp;</span>{{balanceDisplay.confirmed | number: '1.18'}} BTC confirmed<br />
{{balanceDisplay.unconfirmed | number: '1.18'}} BTC pending
</p>
<p *ngIf="mode.type=='private'">
<clr-icon shape="key"></clr-icon> Private key available
</p>
</div>
<div class="card-footer clr-row" style="margin-left: 2px" >
<button *ngIf="!autorefresh" class="btn btn-icon clr-col-4" (click)="reload()"> <clr-icon shape="refresh"></clr-icon> Reload </button>
<clr-toggle-wrapper class="clr-col-auto clr-align-self-center">
<input type="checkbox" clrToggle [(ngModel)]="autorefresh" />
<label>Autorefresh</label>
</clr-toggle-wrapper>
</div>
</div>
<!-- Balance box-->
</div>
<!-- right column -->
</div>
<!-- /row wallet picker + send box + balance box -->
<!-- live-tx -->
<div class="clr-row" *ngIf="apiClientPlugin && transactions.length != 0" >
<div class="clr-col-12">
<div class="clr-all-12" style="padding-left:0px; padding-right: 0px">
<div class="card">
<div class="card-header">
Live Transactions
</div>
<div class="card-block" >
<table class="table table-compact">
<thead>
<tr>
<th>Hash</th>
<th>Amount</th>
<th>Status</th>
<th>To</th>
<th>From</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let line of transactions">
<td style="word-break:break-all">{{line.hash}}</td>
<td>{{line.amount}}</td>
<td>{{line.status}}</td>
<td style="word-break:break-all">{{line.to}}</td>
<td style="word-break:break-all">{{line.from.join(', ')}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /live-tx -->
<!-- address-viewer -->
<div class="clr-all-12" style="padding-left:0px; padding-right: 0px">
<address-viewer></address-viewer>
</div>
<!-- address-viewer -->
</div>
<!-- /row 1 -->
`
})
export class PluginsComponent implements AfterViewInit, OnDestroy {
timerRefresh: NodeJS.Timeout
errors: string[] = []
successes: string[] = []
wallets: WalletStore = {}
rootkey: bip32Keypair = { publicExtendedKey: "", privateExtendedKey: "" }
keys: KeyStore = {}
regaddresses: AddressLine[] = []
changeaddresses: AddressLine[] = []
balanceDisplay = {
confirmed: 0,
total: 0,
unconfirmed: 0
}
mode: {
type: keyType,
net: networkType
} = {
net: "testnet",
type: "public"
}
sendTo: string
sendAmount: number
sending = false
loading = false
loadingN = 1
autorefresh = false
refreshing = false
apiClientPlugin = false
subscriptions = []
transactions = []
@ViewChild(AddressViewerComponent, { static: false })
AddressViewerComponent: AddressViewerComponent
@ViewChild(WalletGeneratorComponent, { static: false })
WalletGeneratorComponent: WalletGeneratorComponent
@ViewChild(WalletPickerComponent, { static: false })
WalletPickerComponent: WalletPickerComponent
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
this.unsubscribe()
return true
}
async ngAfterViewInit(): Promise<void> {
this.WalletGeneratorComponent.setParent(this)
this.WalletPickerComponent.setParent(this)
this.AddressViewerComponent.setParent(this)
this.apiClientPlugin = fb.ApiClient != null
window['btc'] = this
const keys: any[] = await fb.Wallet.getKeys()
keys.filter(key => key.coin === "BTC").forEach(key => {
this.wallets[key.name] = {key: key.value, name: key.name}
})
this.WalletPickerComponent.setWallets(this.wallets)
this.timerRefresh = setInterval(async () => { if (this.autorefresh && !this.refreshing && !this.loading) this.refresh() }, 30000)
}
ngOnDestroy(): void {
this.unsubscribe()
clearInterval(this.timerRefresh)
}
unsubscribe(){
this.subscriptions.map(s => {
fb.ApiClient.unsubscribe(s)
})
}
addWallet(wallet: {key:string, name:string}) {
fb.Wallet.putKey(wallet.name, "plain", wallet.key, "BTC")
this.wallets[wallet.name] = wallet
this.WalletPickerComponent.setWallets(this.wallets)
}
showWizard() {
this.WalletGeneratorComponent.open()
}
loadKey(key: string) {
this.wallets = {}
this.regaddresses = []
const t = hdkey.checkHDKey(key)
if (t) {
this.mode = t
}
this.rootkey = hdkey.HDKeyFromExtendedKey(key)
this.reload()
}
async reload(): Promise<void> {
if (this.loading)
return
this.loading = true
this.loadingN = 1
await this.refresh()
if (fb.ApiClient) {
const res: (SubscriptionResponse | ErrorResponse)[] = await Promise.all([
...this.regaddresses,
...this.changeaddresses
].map(async a => await fb.ApiClient.subsume("BTC", { address: a.address }, tx => { this.transactions.unshift(tx) })))
this.subscriptions = this.subscriptions.concat(res.map(r => {
if (r.result = "Success") {
return r.message
} else {
return
}
})).filter(s => !(!s))
}
this.loading = false
}
async refresh(): Promise<void> {
if (this.refreshing)
return
this.refreshing = true
this.keys = {}
let p1 = this.updateChange()
let p2 = this.updateBalance()
let balances: GrandTotal[] = await Promise.all([p1, p2])
this.balanceDisplay = balances.reduce((a, o) => {
a.confirmed += o.confirmed
a.total += o.total
a.unconfirmed += o.unconfirmed
return a
}, {
confirmed: 0,
unconfirmed: 0,
total: 0
})
this.AddressViewerComponent.setChangeAddresses(this.changeaddresses)
this.AddressViewerComponent.setRegularAddresses(this.regaddresses)
this.refreshing = false
}
getAddresses(rootAddr: string, n = 10, skip = 0, changeAddresses = false): string[] | null {
let addresses: string[] = []
for (let i = skip; i < skip + n; i++) {
let addr
if (changeAddresses) {
addr = hdkey.deriveAddress(rootAddr, i, 'm/1/')
} else {
addr = hdkey.deriveAddress(rootAddr, i)
}
if (!addr) {
return
}
addresses.push(addr)
}
return addresses
}
async fetchAddresses(addresses: string[], network: networkType): Promise<{ success: boolean, address?: any, addresses?: any }> {
let lookupstr = addresses.join(',')
try {
let r = await fetch(api[network] + '/address/' + lookupstr, {
'method': 'GET',
'mode': 'cors',
'data': { limit: 200 }
})
if (r.status !== 200) {
return { success: false }
}
let json = (await r).json()
return json
} catch (e) {
return { success: false }
}
}
async getAddressInfos(rootAddr: string, n = 10, skip = 0, changeAddresses = false): Promise<any> {
const t = hdkey.checkHDKey(rootAddr)
if (!t) {
return false
}
const addresses = this.getAddresses(rootAddr, n, skip, changeAddresses)
return await this.fetchAddresses(addresses, t.net)
}
/*
async getTxs(address: string, type:networkType){
try{
let r = await fetch(api[type]+'/address/'+address, {
'method':'GET',
'mode':'cors'
})
if(r.status !== 200){
return {success: false}
}
return (await r).json()
}catch(e){
console.warn ("getTxs", e)
}
}
*/
async getUnspentTxs(addresses: string[], type: networkType): Promise<getUnspentTxsApiResponse> {
let lookupstr = addresses.join(',')
let url = api[type] + '/address/' + lookupstr + '/unspent'
let txs:getUnspentTxsApiResponse['unspent'] = []
while (true) {
try {
let resp = await fetch(url, {
'method': 'GET',
'mode': 'cors'
})
if (resp.status !== 200) {
return { success: false }
}
const json: getUnspentTxsApiResponse = await resp.json()
if (!json.success)
break;
txs = [...txs, ...(json.unspent?json.unspent.filter(u => u.confirmations > 0):[])]
if(!json.paging.next_link)
break;
url = json.paging.next_link
} catch (e) {
console.warn("getUnspentTxs", e)
return { success: false }
}
}
return {
success: true,
unspent: txs
}
}
getKeyForAddress(keyName) {
return this.keys[keyName]
}
calculateTotal(addresses: AddressLine[]): GrandTotal {
const resMap: any = addresses.reduce((o1:any, o2:any) => { o1[o2.address] = o2; return o1 }, {})
const total: GrandTotal = Object.values<AddressLine>(resMap).reduce((accum: GrandTotal, obj: AddressLine) => {
accum.confirmed += parseFloat(<any>obj.confirmed.balance)
accum.unconfirmed += parseFloat(<any>obj.unconfirmed.balance)
accum.total += parseFloat(<any>obj.confirmed.balance) + parseFloat(<any>obj.unconfirmed.balance)
return accum
}, {
confirmed: 0,
unconfirmed: 0,
total: 0
})
return total
}
async updateBalance(): Promise<GrandTotal> {
let n = 1
let res: { success: boolean; addresses: any; address: any; }
this.regaddresses = []
while (true) {
this.loadingN = n
try {
res = await this.getAddressInfos(this.rootkey.publicExtendedKey, 115 * n, 115 * (n - 1))
} catch (e) {
break
}
if (res.success === true) {
if ('addresses' in res) { // multiple
this.regaddresses = [...this.regaddresses, ...res.addresses]
}
if ('address' in res) {
this.regaddresses.push(res.address)
}
n++
} else {
console.warn(`This error is a result of a failed fetch request.
These are always shown by the browser and cannot be hidden (a design decision)
They are completely safe and mean no more addresses were found`)
console.log('No more balance found after attempting ', 115 * n, 'addresses')
if (this.mode.type == "private") {
for (let i = 0; i < 115 * n + 1; i++) {
const keyN = hdkey.deriveKey(this.rootkey.privateExtendedKey, i)
const addrN = hdkey.addressFromHDKey(keyN._publicKey, this.mode.net)
keyN.derivation = i
this.keys[addrN] = keyN
}
}
break
}
}
//add an extra empty address at the end
const extraAddr = hdkey.deriveAddress(this.rootkey.publicExtendedKey, this.regaddresses.length)
this.regaddresses.push({
address: <string>extraAddr,
confirmed: { balance: 0 },
unconfirmed: { balance: 0 },
total: { balance: 0 },
})
return this.calculateTotal(this.regaddresses)
}
async updateChange(): Promise<GrandTotal> {
let n = 1
this.changeaddresses = []
while (true) {
let res
try {
res = await this.getAddressInfos(this.rootkey.publicExtendedKey, 115 * n, 115 * (n - 1), true)
} catch (e) {
break
}
if (res.success === true) {
if ('addresses' in res) { // multiple
this.changeaddresses = [...this.changeaddresses, ...res.addresses]
}
if ('address' in res) {
this.changeaddresses.push(res.address)
}
n++
} else {
console.warn(`This error is a result of a failed fetch request.
These are always shown by the browser and cannot be hidden (a design decision)
They are completely safe and mean no more addresses were found`)
console.log('No more change balance found after attempting ', 115 * n, 'addresses')
if (this.mode.type == "private") {
//make keypairs for addresses
for (let i = 0; i < 115 * n; i++) {
const keyN = hdkey.deriveKey(this.rootkey.privateExtendedKey, i, 'm/1/')
const addrN = hdkey.addressFromHDKey(keyN._publicKey, this.mode.net)
keyN.derivation = i
this.keys[addrN] = keyN
}
}
break
}
}
return this.calculateTotal(this.changeaddresses)
}
async createAndSendTx(target: string, value: number) {
this.sending = true
if (target == null || typeof target !== 'string' || target === '' || value == null || value <= 0) {
this.errors.push('Bad inputs. Expected bitcoin address and number')
this.sending = false
return
}
if (value > this.balanceDisplay.confirmed) {
this.errors.push('Insufficient funds')
this.sending = false
return
}
let addresses: string[] = [...this.regaddresses.map(a => a.address), ...this.changeaddresses.map(a => a.address)]
const txs = await this.getUnspentTxs(addresses, this.mode.net)
if (txs == null || txs.success !== true || txs.unspent.length === 0) {
this.errors.push('No UTXOs found')
this.sending = false
return
}
const utxos = txs.unspent.map(t => {
return {
address: t.addresses[0],
txId: t.txid,
vout: t.n,
value: Math.floor(parseFloat(t.value) * 100000000)
}
}).filter(utx => utx.value > 0 && utx.address != target)
let { inputs, outputs, fee } = coinselect(utxos, [{ address: target, value: Math.floor(parseFloat(<any>value) * 100000000) }], feeRate)
// .inputs and .outputs will be undefined if no solution was found
if (!inputs || !outputs) {
console.log(fee)
this.errors.push('Could not build a valid transaction')
this.sending = false
return
}
const txb = new TransactionBuilder(networks[this.mode.net])
txb.setVersion(1)
inputs.forEach((input) => {
txb.addInput(input.txId, input.vout)
})
outputs.forEach((output) => {
if (!output.address) {
output.address = hdkey.deriveAddress(this.rootkey.publicExtendedKey, this.changeaddresses.length, 'm/1/')
}
txb.addOutput(output.address, output.value)
})
inputs.forEach((input, i) => {
txb.sign(i, <Signer>this.keys[input.address])
})
await this.sendTx(txb.build())
}
private async sendTx(tx) {
if (tx == null) {
this.errors.push('No transaction to send!')
return
}
let url = api[this.mode.net] + "/pushtx"
let r
try {
r = await fetch(url, {
'method': 'POST',
'body': JSON.stringify({ 'hex': tx.toHex() })
})
} catch (e) {
console.warn("sendTx", e)
return
}
if (r.status === 200) {
this.successes.push("Sent " + this.sendAmount + " to " + this.sendTo)
this.sending = false
this.errors = []
this.sendTo = ""
this.sendAmount = null
} else {
this.errors.push('The API ' + url + ' returned a non-200 error code ' + r.status + ' ' + r.statusText)
}
}
addrExplorer(address) {
const url = this.mode.net === 'testnet' ? 'https://live.blockcypher.com/btc-testnet/address/' : 'https://live.blockcypher.com/btc/address/'
window.open(url + address, '_blank')
}
}
export type KeyStore = { [keyname in string]: bip32Keypair & Signer }
export type AddressLine = {
address: string,
confirmed: { balance: number },
unconfirmed: { balance: number },
total: { balance: number },
}
type networkType = 'testnet' | 'mainnet'
type keyType = 'public' | 'private'
type WalletStore = {
[address in string]: {
key: string
name: string
}
}
type GrandTotal = {
confirmed: number,
unconfirmed: number,
total: number
}
type bip32Keypair = { publicExtendedKey: string, privateExtendedKey: string }
type getUnspentTxsApiResponse = {
success: boolean,
paging?: {
next_link: string | null
}
unspent?: {
addresses: string[],
confirmations: number,
id: number, n: number,
req_sigs: number,
script_pub_key: any,
txid: string,
type: string,
value: string,
value_int: number
}[]
}
const api = {
testnet: 'https://testnet-api.smartbit.com.au/v1/blockchain',
mainnet: 'https://api.smartbit.com.au/v1/blockchain'
}
@@ -0,0 +1,266 @@
import { Component, OnInit, isDevMode, ViewChild } from '@angular/core';
import { ClrWizard } from '@clr/angular';
import { HDKey } from "btc-hdkey"
import { PluginsComponent } from './btc.component';
declare const fb
@Component({
selector: 'wallet-generator', //!!!!
template: `
<clr-wizard #wizard [(clrWizardOpen)]="mdOpen" [clrWizardForceForwardNavigation]="true" clrWizardSize="lg">
<clr-wizard-title>Bitcoin wallet generator and importer</clr-wizard-title>
<clr-wizard-button [type]="'cancel'">Cancel</clr-wizard-button>
<clr-wizard-button [type]="'previous'">Back</clr-wizard-button>
<clr-wizard-button [type]="'next'">Next</clr-wizard-button>
<clr-wizard-button [type]="'finish'">Finish</clr-wizard-button>
<clr-wizard-page (clrWizardPageCustomButton)="doCustomClick($event)">
<ng-template clrPageTitle>Menemonic/BIP39 (optional)</ng-template>
<ng-template clrPageNavTitle>
Menemonic/BIP39
</ng-template>
<p>
A menemonic is a collection of words that is supposed to be easier to remember than a complex seed. It may be used to reconstruct the private key.
</p>
<p>
Enter your menemonic below or generate a new one.
</p>
<textarea [(ngModel)]="menemonic" class="clr-textarea" style="margin-top: 24px; width: 100%; height: 200px">{{menemonic}}</textarea>
<div class="clr-row">
<clr-checkbox-wrapper class="clr-col">
<input type="checkbox" clrCheckbox value="testnet" name="testnet1" [(ngModel)]="testnet" />
<label>testnet</label>
</clr-checkbox-wrapper>
<button class="btn btn-outline-success clr-col" (click)="generateMenemonic()">{{"Generate"}}</button>
</div>
<ng-template clrPageButtons>
<clr-wizard-button [type]="'cancel'">Cancel</clr-wizard-button>
<clr-wizard-button [type]="'menemonic-next'">{{menemonic.length==0?"Skip":"Next"}}</clr-wizard-button>
</ng-template>
</clr-wizard-page>
<clr-wizard-page (clrWizardPageCustomButton)="doCustomClick($event)">
<ng-template clrPageTitle>Seed phrase (optional)</ng-template>
<ng-template clrPageNavTitle>
Seed phrase
</ng-template>
<p>
If you entered a menemonic in the previous step, a seed was generated from it.
</p>
<p>
If you would like to use your own seed enter it below. Use something sufficiently hard to guess.
</p>
<textarea class="clr-textarea" (ngModelChange)="updateSeed()" [(ngModel)]="seed" style="margin-top: 24px; width: 100%; height: 200px">{{seed}}</textarea>
<clr-checkbox-wrapper>
<input type="checkbox" clrCheckbox value="testnet" name="testnet2" [(ngModel)]="testnet" />
<label>testnet</label>
</clr-checkbox-wrapper>
<ng-template clrPageButtons>
<clr-wizard-button [type]="'cancel'">Cancel</clr-wizard-button>
<clr-wizard-button [type]="'back'">Back</clr-wizard-button>
<clr-wizard-button [type]="'seed-next'">{{seed.length==0?"Skip":"Next"}}</clr-wizard-button>
</ng-template>
</clr-wizard-page>
<clr-wizard-page [clrWizardPageNextDisabled]="keyInvalid" (clrWizardPageCustomButton)="doCustomClick($event)">
<ng-template clrPageTitle>Extended Key/BIP32</ng-template>
<p>
Accepts keys in the xpub and xprv (BIP32) format
</p>
<textarea [(ngModel)]="key" (ngModelChange)="updateKey()"class="clr-textarea" style="margin-top: 24px; width: 100%; height: 200px"></textarea>
</clr-wizard-page>
<clr-wizard-page class="break-word" (clrWizardPageCustomButton)="doCustomClick($event)">
<ng-template clrPageTitle>Confirm</ng-template>
<div class="alert alert-danger" role="alert">
<div class="alert-items">
<div class="alert-item static">
<div class="alert-icon-wrapper">
<clr-icon class="alert-icon" shape="exclamation-circle"></clr-icon>
</div>
<span class="alert-text">
Do not give any of this information to other people! Even your public key holds the power to correlate all your addresses back to you!
</span>
</div>
</div>
</div>
<div *ngIf="keypair.privateExtendedKey != null && keypair.privateExtendedKey.length != 0" class="alert alert-warning" role="alert">
<div class="alert-items">
<div class="alert-item static">
<div class="alert-icon-wrapper">
<clr-icon class="alert-icon" shape="exclamation-circle"></clr-icon>
</div>
<span class="alert-text">
WARNING: A private key is not required for operating frontblock
</span>
</div>
</div>
</div>
<div *ngIf="keypair.privateExtendedKey != null && keypair.privateExtendedKey.length != 0" class="alert alert-info" role="alert">
<div class="alert-items">
<div class="alert-item static">
<div class="alert-icon-wrapper">
<clr-icon class="alert-icon" shape="exclamation-circle"></clr-icon>
</div>
<span class="alert-text">
HINT: You can exclusively store the public key by going back one step and importing the xpub you just created
</span>
</div>
</div>
</div>
<table class="table">
<thead>
<tr>
<th class="left">Type</th>
<th class="left">Value</th>
</tr>
</thead>
<tbody>
<tr *ngIf="menemonic.length != 0">
<td class="left"> menemonic</td>
<td class="left">{{menemonic}}</td>
</tr>
<tr *ngIf="seed.length != 0">
<td class="left"> seed</td>
<textarea rows="3" class="clr-textarea left" [ngModel]="seed" style="width: 100%"></textarea>
</tr>
<tr>
<td class="left"> xpub</td>
<textarea rows="3" class="clr-textarea left" [ngModel]="keypair.publicExtendedKey" style="width: 100%"></textarea>
</tr>
<tr *ngIf="keypair.privateExtendedKey != null && keypair.privateExtendedKey.length != 0">
<td class="left"> xprv</td>
<textarea rows="3" class="clr-textarea left" [ngModel]="keypair.privateExtendedKey" style="width: 100%"></textarea>
</tr>
</tbody>
</table>
<clr-checkbox-wrapper>
<input type="checkbox" clrCheckbox value="option1" name="options" />
<label>I understand this is important</label>
</clr-checkbox-wrapper>
<ng-template clrPageButtons>
<clr-wizard-button [type]="'cancel'">Cancel</clr-wizard-button>
<clr-wizard-button [type]="'back'">Back</clr-wizard-button>
<clr-wizard-button class="btn btn-success" [type]="'myfinish'">Finish</clr-wizard-button>
</ng-template>
</clr-wizard-page>
</clr-wizard>
`
})
export class WalletGeneratorComponent implements OnInit {
@ViewChild("wizard", {static: false}) wizard: ClrWizard;
key:string = ""
keyInvalid = true
accept = false
seed:string = ""
mdOpen: boolean = false
checkKey: boolean = true
menemonic:string = ""
keypair: any = {}
testnet: boolean = false
profileName
private hdKey = new HDKey()
private parent:PluginsComponent
ngOnInit() { }
open(){
this.key = ""
this.keyInvalid = true
this.seed = ""
this.checkKey = true
this.menemonic = ""
this.keypair = {}
this.testnet = false
this.wizard.reset()
this.mdOpen = true
}
setParent(parent:PluginsComponent){
this.parent = parent
}
async generateMenemonic(){
this.menemonic = this.hdKey.randomMenemonic()
}
async seedFromMenemonic(){
try{
this.seed = this.hdKey.seedFromMenemonic(this.menemonic)
}catch(e){
/* invalid menemonic */
console.log(e)
}
}
async accountFromSeed(){
this.keypair = this.hdKey.deriveAccount(this.seed, this.testnet?"testnet":"mainnet", 0)
console.log(this.keypair)
this.key = this.keypair.privateExtendedKey != null?this.keypair.privateExtendedKey:this.keypair.publicExtendedKey
this.keyInvalid = false
}
async importKey(){
this.hdKey.HDKeyFromExtendedKey(this.key)
}
checkBip32(){
return this.hdKey.checkHDKey(this.keypair.privateExtendedKey != null?this.keypair.privateExtendedKey:this.keypair.publicExtendedKey)
}
finish(){
this.parent.addWallet({
name: this.key.substr(4,15),
key: this.key
})
}
public doCustomClick(buttonType: string): void {
if ("menemonic-next" === buttonType) {
if(this.menemonic.length != 0){
this.seedFromMenemonic()
}
this.wizard.next();
}
if ("myfinish" === buttonType) {
this.finish()
this.wizard.close()
}
if ("seed-next" === buttonType) {
if(this.seed.length != 0){
this.accountFromSeed()
}
this.wizard.next();
}
if ("back" === buttonType) {
this.wizard.previous();
}
}
updateSeed(){
this.menemonic = ""
}
updateKey(){
this.keyInvalid = true
this.menemonic = ""
this.seed = ""
let key
try{
key = this.hdKey.HDKeyFromExtendedKey(this.key)
}catch(e){
/* invalid key */
console.log("bad key")
}
if(key){
this.keypair = key
this.keyInvalid = false
}
}
}
@@ -0,0 +1,50 @@
import { Component, OnInit, isDevMode } from '@angular/core';
import { PluginsComponent } from './btc.component';
declare const fb
@Component({
selector: 'walletpicker', //!!!!
template: `
<div class="card" style="overflow:hidden; padding-bottom:12px">
<div class="card-header">
Wallets
</div>
<clr-alert *ngFor="let entry of alerts" [clrAlertType]="line.severity">
<clr-alert-item>
<span class="alert-text">
{{line.message}}
</span>
</clr-alert-item>
</clr-alert>
<clr-tree-node style="margin-top:12px; margin-bottom:12px">
<a style="cursor:pointer" (click)="parent.showWizard()"><clr-icon shape="download" class="is-solid"></clr-icon> New / Import</a>
</clr-tree-node>
<clr-tree-node *ngFor="let line of wallets">
<a style="cursor:pointer" (click)="parent.loadKey(line.key)">
<clr-icon *ngIf="line.key.startsWith('xpub') || line.key.startsWith('tpub')" shape="lock" class="is-solid"></clr-icon>
<clr-icon *ngIf="line.key.startsWith('xprv') || line.key.startsWith('tprv')" shape="key" class="is-solid"></clr-icon>
{{line.name}}
</a>
</clr-tree-node>
</div>
`
})
export class WalletPickerComponent implements OnInit {
private parent:PluginsComponent
wallets = []
setWallets(wallets){
this.wallets = Object.values(wallets)
}
setParent(parent:PluginsComponent){
this.parent = parent
}
ngOnInit() { }
}
@@ -0,0 +1,67 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { PluginsComponent } from './btc/btc.component';
import { WalletPickerComponent } from './btc/wallet-picker.component';
import { AddressViewerComponent } from './btc/address-viewer.component';
import { FrontendPlugin, SidebarEntries } from 'frontblock-generic/Plugin';
import { ClarityModule } from '@clr/angular';
import { FormsModule } from '@angular/forms';
import { WalletGeneratorComponent } from './btc/wallet-generator.component';
import { WalletSettingsComponent } from './settings.component';
// @ts-ignore
import { KnexConfigModule } from "../../../knex-config/knex-config.module";
@NgModule({
imports: [
FormsModule,
ClarityModule,
KnexConfigModule,
CommonModule,
RouterModule.forChild([
{path: "btc", component: PluginsComponent},
{path: "settings", component: WalletSettingsComponent},
]),
],
exports: [RouterModule],
declarations: [
WalletSettingsComponent,
PluginsComponent,
WalletPickerComponent,
AddressViewerComponent,
WalletGeneratorComponent
]
})
export class PluginModule implements FrontendPlugin{
getSidebarEntry(): SidebarEntries {
return {
icon: "wallet",
text: "Wallets",
parentRoute: "wallet",
links: [{
route: "btc",
text: "BTC Wallet"
},{
route: "ltc",
text: "LTC Wallet"
},{
route: "eth",
text: "ETH Wallet"
},{
route: "xrp",
text: "XRP Wallet"
},{
route: "xlm",
text: "XLM Wallet"
},{
route: "settings",
text: "Settings"
}]
}
}
}
@@ -0,0 +1,17 @@
import { Component, OnInit, isDevMode } from '@angular/core';
declare const fb
@Component({
selector: 'wallet-settings', //!!!!
template:
`
<knex-config fbPlugin="Wallet"></knex-config>
`
})
export class WalletSettingsComponent implements OnInit {
ngOnInit() { }
}
@@ -0,0 +1,41 @@
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
target: "web",
entry: path.resolve(__dirname, 'module.ts'),
output: {
path: path.resolve(__dirname, '../../dist'),
filename: 'FrontendPlugin.js',
libraryTarget: 'commonjs',
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.ts?$/, loader: "ts-loader" }
]
},
optimization: {
minimizer: [
new TerserPlugin({
exclude: [
/\.\/(.*)\/.ts/,
/\.\/(.*).ts/,
],
}),
],
},
externals: {
'@angular/core': '@angular/core',
'@angular/common': '@angular/common',
'@angular/router': '@angular/router',
'@angular/animations': '@angular/animations',
'@angular/forms': '@angular/forms',
'@clr/angular': '@clr/angular',
'../../../knex-config/knex-config.module': 'knexconfig'
}
}

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