Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

experiment: demo electron integration #999

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions client/cmd/electron-demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package-lock.json
site/
node_modules/
*.h
*.so
*.dll
build/
bin/
31 changes: 31 additions & 0 deletions client/cmd/electron-demo/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
default: build

compile-go:
go build -buildmode=c-shared -o ./libdexc/libdexc.so ./libdexc/...

npm-install:
npm install

cleanup:
rm -r build 2> /dev/null || true
rm -r site 2> /dev/null || true
rm -r /tmp/dexc 2> /dev/null || true
mkdir -p site

move-site:
cp -r ../../webserver/site/src/ ./site/
cp -r ../../webserver/site/dist/ ./site/

build-c:
./node_modules/.bin/node-gyp configure
./node_modules/.bin/node-gyp build
./node_modules/.bin/electron-rebuild

build: compile-go npm-install cleanup move-site build-c


run:
./node_modules/.bin/electron main.js

run-simnet: build
./node_modules/.bin/electron main.js --simnet
9 changes: 9 additions & 0 deletions client/cmd/electron-demo/binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"targets": [
{
"target_name": "dexc",
"sources": [ "cnode/cnode.cc" ],
"libraries": ["<!(pwd)/libdexc/libdexc.so"],
}
]
}
33 changes: 33 additions & 0 deletions client/cmd/electron-demo/cnode/cnode.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// hello.cc
#include <node.h>
#include "../libdexc/libdexc.h"

namespace cnode {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

const char* ToCString(const String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}

void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate, args[0]);
const char* cstr = ToCString(str);
char * charstr = const_cast<char *>(cstr);
char* result = Call(charstr);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, result).ToLocalChecked());
}

void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "call", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

} // namespace cnode
12 changes: 12 additions & 0 deletions client/cmd/electron-demo/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Decred DEX Electron Integration Example</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<div id="main"></div>
<script src="index.js"></script>
</body>
</html>
162 changes: 162 additions & 0 deletions client/cmd/electron-demo/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
const { ipcRenderer } = require('electron')
const path = require('path')

Mainnet = 0
Testnet = 1
Simnet = 2

NetName = {
[Mainnet]: Mainnet,
[Testnet]: Testnet,
[Simnet]: Simnet
}

LogLevelTrace = 0
LogLevelDebug = 1
LogLevelInfo = 2
LogLevelWarn = 3
LogLevelError = 4
LogLevelCritical = 5
LogLevelOff = 6

DCR_ID = 42
BTC_ID = 0

function appGetPath (name) {
return fetchIPC('getPath', name)
}

function fetchIPC (func, ...args) {
let res = ipcRenderer.sendSync(func, ...args)
res = res ? JSON.parse(res) : null
if (res && res.error) throw Error(String(res.error))
return res
}

class DEX {
static startCore () {
const dbPath = path.join(appGetPath('temp'), (new Date().getTime()).toString(), 'dexc', 'db.db')
return fetchIPC('callDEX', 'startCore', {
dbPath: dbPath,
net: Simnet,
logLevel: LogLevelDebug,
})
}

static isInitialized () {
const res = fetchIPC('callDEX', 'IsInitialized', '')
console.log("isInitialized res", res, typeof res)
return res
}

static init (pw) {
return fetchIPC('callDEX', 'Init', { pass: pw })
}

static startServer (addr) {
return fetchIPC('callDEX', 'startServer', addr)
}

static createWallet (assetID, config, pass, appPass) {
return fetchIPC('callDEX', 'CreateWallet', {
assetID: assetID,
config: config,
pass: pass,
appPass: appPass,
})
}

static register (addr, appPass, fee, cert) {
return fetchIPC('callDEX', 'Register', {
url: addr,
appPass: appPass,
fee: fee,
cert: cert,
})
}

static user () {
return fetchIPC('callDEX', 'User', '')
}
}

/* sleep can be used by async functions to pause for a specified period. */
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}

const mainDiv = document.getElementById('main')

async function writeMain (s) {
const div = document.createElement('div')
div.textContent = s
mainDiv.appendChild(div)
}

function stringToUTF8Hex (s) {
return s.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join("")
}

async function prepSimnet () {

const pw = "abc"
if (!DEX.isInitialized()) {
await writeMain('Initializing DEX')
await writeMain(`result: ${DEX.init(pw)}`)
}

const homeDir = appGetPath('home')
const dextestDir = path.join(homeDir, 'dextest')

const user = DEX.user()
if (!user.assets[DCR_ID].wallet) {
const walletCertPath = path.join(dextestDir, 'dcr', 'alpha', 'rpc.cert')
await writeMain('Loading simnet Decred wallet')
DEX.createWallet(DCR_ID, {
account: 'default',
username: 'user',
password: 'pass',
rpccert: walletCertPath,
rpclisten: '127.0.0.1:19567'
}, pw, pw)

await writeMain('Loading simnet Bitcoin wallet')
DEX.createWallet(BTC_ID, {
walletname: '', // alpha wallet
rpcuser: 'user',
rpcpassword: 'pass',
rpcport: '20556',
}, pw, pw)
}

const simnetDexAddr = '127.0.0.1:17273'
if (!user.exchanges[simnetDexAddr]) {
await writeMain('Registering at simnet DEX server')
const defaultRegFee = 1e8
const serverCertPath = path.join(dextestDir, 'dcrdex', 'rpc.cert')
DEX.register(simnetDexAddr, pw, defaultRegFee, serverCertPath)
}
}

async function run () {
let net = Mainnet
const args = fetchIPC('cmdArgs', '')
if (args.indexOf('--simnet') > -1) net = Simnet
else if (args.indexOf('--testnet') > -1) net = Simnet
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testnet


console.log("using network", NetName[net])

await writeMain('Starting DEX Core')
DEX.startCore()

if (net == Simnet) prepSimnet()

// Start server
const addr = `localhost:54321`
await writeMain('Starting Web Server')
await writeMain(`result: ${DEX.startServer(addr)}`)

window.location.href = `http://${addr}`
}

run()
Loading