Skip to content

Commit

Permalink
Switch to new nkn-sdk-js
Browse files Browse the repository at this point in the history
Signed-off-by: Yilun <[email protected]>
  • Loading branch information
yilunzhang committed Apr 13, 2020
1 parent aa34314 commit ef1f138
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 245 deletions.
63 changes: 33 additions & 30 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ var _yargs = _interopRequireDefault(require("yargs"));

var _nodePty = require("node-pty");

var _nknMulticlient = _interopRequireDefault(require("nkn-multiclient"));

var _nknWallet = _interopRequireDefault(require("nkn-wallet"));
var _nknSdk = _interopRequireDefault(require("nkn-sdk"));

var _crypto = require("crypto");

var _child_process = require("child_process");

var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

let argv = _yargs.default.command('$0', 'start nshd').command('addr', 'show addr').option('base-dir', {
Expand Down Expand Up @@ -105,7 +105,9 @@ try {
}

try {
wallet = _nknWallet.default.loadJsonWallet(walletJson, password);
wallet = _nknSdk.default.Wallet.fromJSON(walletJson, {
password
});
} catch (e) {
console.error('Parse wallet error:', e);
process.exit(1);
Expand All @@ -123,9 +125,11 @@ try {
console.log('Create password and save to file', passwordFile);
}

wallet = _nknWallet.default.newWallet(password);
wallet = new _nknSdk.default.Wallet({
password
});

_fs.default.writeFileSync(walletFile, wallet.toJSON());
_fs.default.writeFileSync(walletFile, JSON.stringify(wallet));

console.log('Create wallet and save to file', walletFile);
}
Expand Down Expand Up @@ -213,7 +217,7 @@ function getAuthorizedUser(src) {
return null;
}

const client = (0, _nknMulticlient.default)({
const client = new _nknSdk.default.MultiClient({
seed: wallet.getSeed(),
identifier: identifier
});
Expand All @@ -239,19 +243,16 @@ class Session {
delete sessions[this.remoteAddr];
});

this.flushSession = () => {
this.flushSession = async () => {
if (this.outputBuffer.length > 0) {
let res = {
stdout: this.outputBuffer
};
this.outputBuffer = '';

try {
this.client.send(this.remoteAddr, JSON.stringify(res), {
msgHoldingSeconds: 0
}).catch(e => {
console.error("Send msg error:", e);
let res = {
stdout: this.outputBuffer
};
await this.client.send(this.remoteAddr, JSON.stringify(res), {
noReply: true
});
this.outputBuffer = '';
} catch (e) {
console.error("Send msg error:", e);
}
Expand Down Expand Up @@ -280,14 +281,13 @@ class Session {
}

let sessions = {};
client.on('connect', () => {
client.onConnect(() => {
console.log('Listening at', client.addr);

for (let i = 0, length = client.clients.length; i < length; i++) {
let c = client.clients[i];
for (let c of Object.values(client.clients)) {
setInterval(function () {
try {
c.ws && c.ws.ping && c.ws.ping();
c.ws && c.ws.readyState === _isomorphicWs.default.OPEN && c.ws.ping && c.ws.ping();
} catch (e) {
console.warn('Websocket ping error:', e);
}
Expand All @@ -297,25 +297,28 @@ client.on('connect', () => {
let lastUpdateTime = new Date();
setInterval(async function () {
try {
await client.send(client.addr, '', {
msgHoldingSeconds: 0
});
await client.send(client.addr, '');
lastUpdateTime = new Date();
} catch (e) {
console.warn('Multiclient ping error:', e);

if (new Date().getTime() - lastUpdateTime.getTime() > pingInterval * 3) {
console.log('Multiclient keepalive timeout, trying to reconnect...');

for (let i = 0, length = client.clients.length; i < length; i++) {
client.clients[i].reconnect();
for (let c of Object.values(client.clients)) {
c.reconnect();
}
}
}
}, pingInterval);
});
client.on('message', async (src, payload, payloadType, encrypt) => {
if (!encrypt) {
client.onMessage(async ({
src,
payload,
payloadType,
isEncrypted
}) => {
if (!isEncrypted) {
console.log('Received unencrypted msg from', src);
return false;
}
Expand All @@ -331,7 +334,7 @@ client.on('message', async (src, payload, payloadType, encrypt) => {
return false;
}

if (payloadType === _nknMulticlient.default.PayloadType.BINARY) {
if (payloadType !== _nknSdk.default.pb.payloads.PayloadType.TEXT) {
console.log('Received msg with wrong payload type from', src);
return false;
}
Expand Down Expand Up @@ -408,7 +411,7 @@ client.on('message', async (src, payload, payloadType, encrypt) => {

try {
await client.send(src, JSON.stringify(res), {
msgHoldingSeconds: 0
noReply: true
});
} catch (e) {
console.error("Send msg error:", e);
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nkn-shell-daemon",
"version": "1.0.6",
"version": "1.0.7",
"description": "NKN Shell Daemon",
"main": "nshd.js",
"bin": {
Expand Down Expand Up @@ -28,8 +28,7 @@
},
"homepage": "https://nkn.org",
"dependencies": {
"nkn-multiclient": "^0.0.8",
"nkn-wallet": "^0.4.7",
"nkn-sdk": "^1.1.1",
"node-pty": "^0.9.0",
"yargs": "^14.2.0"
},
Expand Down
47 changes: 22 additions & 25 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import fs from 'fs'
import os from 'os'
import yargs from 'yargs'
import { spawn } from 'node-pty'
import nknClient from 'nkn-multiclient'
import nknWallet from 'nkn-wallet'
import nkn from 'nkn-sdk'
import { randomBytes } from 'crypto'
import { exec, execSync } from 'child_process'
import WebSocket from 'isomorphic-ws'

let argv = yargs
.command('$0', 'start nshd')
Expand Down Expand Up @@ -107,7 +107,7 @@ try {
process.exit(1)
}
try {
wallet = nknWallet.loadJsonWallet(walletJson, password)
wallet = nkn.Wallet.fromJSON(walletJson, { password })
} catch (e) {
console.error('Parse wallet error:', e)
process.exit(1)
Expand All @@ -121,8 +121,8 @@ try {
fs.writeFileSync(passwordFile, password)
console.log('Create password and save to file', passwordFile)
}
wallet = nknWallet.newWallet(password)
fs.writeFileSync(walletFile, wallet.toJSON())
wallet = new nkn.Wallet({ password })
fs.writeFileSync(walletFile, JSON.stringify(wallet))
console.log('Create wallet and save to file', walletFile)
}
if (showAddr) {
Expand Down Expand Up @@ -199,7 +199,7 @@ function getAuthorizedUser(src) {
return null
}

const client = nknClient({
const client = new nkn.MultiClient({
seed: wallet.getSeed(),
identifier: identifier,
})
Expand Down Expand Up @@ -227,16 +227,14 @@ class Session {
delete sessions[this.remoteAddr]
})

this.flushSession = () => {
this.flushSession = async () => {
if (this.outputBuffer.length > 0) {
let res = {
stdout: this.outputBuffer
}
this.outputBuffer = ''
try {
this.client.send(this.remoteAddr, JSON.stringify(res), { msgHoldingSeconds: 0 }).catch(e => {
console.error("Send msg error:", e)
});
let res = {
stdout: this.outputBuffer
};
await this.client.send(this.remoteAddr, JSON.stringify(res), { noReply: true })
this.outputBuffer = ''
} catch (e) {
console.error("Send msg error:", e)
}
Expand Down Expand Up @@ -264,14 +262,13 @@ class Session {

let sessions = {}

client.on('connect', () => {
client.onConnect(() => {
console.log('Listening at', client.addr)

for (let i = 0, length = client.clients.length; i < length; i++) {
let c = client.clients[i]
for (let c of Object.values(client.clients)) {
setInterval(function () {
try {
c.ws && c.ws.ping && c.ws.ping()
c.ws && c.ws.readyState === WebSocket.OPEN && c.ws.ping && c.ws.ping()
} catch (e) {
console.warn('Websocket ping error:', e)
}
Expand All @@ -281,22 +278,22 @@ client.on('connect', () => {
let lastUpdateTime = new Date()
setInterval(async function () {
try {
await client.send(client.addr, '', { msgHoldingSeconds: 0 })
await client.send(client.addr, '')
lastUpdateTime = new Date()
} catch (e) {
console.warn('Multiclient ping error:', e)
if (new Date().getTime() - lastUpdateTime.getTime() > pingInterval * 3) {
console.log('Multiclient keepalive timeout, trying to reconnect...')
for (let i = 0, length = client.clients.length; i < length; i++) {
client.clients[i].reconnect()
for (let c of Object.values(client.clients)) {
c.reconnect()
}
}
}
}, pingInterval)
})

client.on('message', async (src, payload, payloadType, encrypt) => {
if (!encrypt) {
client.onMessage(async ({ src, payload, payloadType, isEncrypted }) => {
if (!isEncrypted) {
console.log('Received unencrypted msg from', src)
return false
}
Expand All @@ -311,7 +308,7 @@ client.on('message', async (src, payload, payloadType, encrypt) => {
return false
}

if (payloadType === nknClient.PayloadType.BINARY) {
if (payloadType !== nkn.pb.payloads.PayloadType.TEXT) {
console.log('Received msg with wrong payload type from', src)
return false
}
Expand Down Expand Up @@ -378,7 +375,7 @@ client.on('message', async (src, payload, payloadType, encrypt) => {
}
}
try {
await client.send(src, JSON.stringify(res), { msgHoldingSeconds: 0 })
await client.send(src, JSON.stringify(res), { noReply: true })
} catch (e) {
console.error("Send msg error:", e)
}
Expand Down
Loading

0 comments on commit ef1f138

Please sign in to comment.