Giter Club home page Giter Club logo

nkn-sdk-js's Introduction

nkn-sdk-js

GitHub license npm version CircleCI Status PRs Welcome

nkn

JavaScript implementation of NKN client and wallet SDK. The SDK consists of a few components:

  • NKN Client: Send and receive data for free between any NKN clients regardless their network condition without setting up a server or relying on any third party services. Data are end to end encrypted by default. Typically you might want to use multiclient instead of using client directly.

  • NKN MultiClient: Send and receive data using multiple NKN clients concurrently to improve reliability and latency. In addition, it supports session mode, a reliable streaming protocol similar to TCP based on ncp.

  • NKN Wallet: Wallet SDK for NKN blockchain. It can be used to create wallet, transfer token to NKN wallet address, register name, subscribe to topic, etc.

Advantages of using NKN client/multiclient for data transmission:

  • Network agnostic: Neither sender nor receiver needs to have public IP address or port forwarding. NKN clients only establish outbound (websocket) connections, so Internet access is all they need. This is ideal for client side peer to peer communication.

  • Top level security: All data are end to end authenticated and encrypted. No one else in the world except sender and receiver can see or modify the content of the data. The same public key is used for both routing and encryption, eliminating the possibility of man in the middle attack.

  • Decent performance: By aggregating multiple overlay paths concurrently, multiclient can get ~100ms end to end latency and 10+mbps end to end session throughput between international devices.

  • Everything is free, open source and decentralized. (If you are curious, node relay traffic for clients for free to earn mining rewards in NKN blockchain.)

Documentation: https://docs.nkn.org/nkn-sdk-js.

Install

For npm:

npm install nkn-sdk

And then in your code:

const nkn = require('nkn-sdk');

or using ES6 import:

import nkn from 'nkn-sdk';

For browser, use dist/nkn.js or dist/nkn.min.js.

For environment where cryptographically secure random number generator is not natively implemented (e.g. React Native), see Random bytes generation.

Client

NKN client provides the basic functions of sending and receiving data between NKN clients or topics regardless their network condition without setting up a server or relying on any third party services. Typically you might want to use multiclient instead of using client directly.

Create a client with a generated key pair:

let client = new nkn.Client();

Or with an identifier (used to distinguish different clients sharing the same key pair):

let client = new nkn.Client({
  identifier: 'any-string',
});

Get client secret seed and public key:

console.log(client.getSeed(), client.getPublicKey());

Create a client using an existing secret seed:

let client = new nkn.Client({
  seed: '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0',
});

Secret key should be kept SECRET! Never put it in version control system like here.

By default the client will use bootstrap RPC server (for getting node address) provided by nkn.org. Any NKN full node can serve as a bootstrap RPC server. You can create a client using customized bootstrap RPC server:

let client = new nkn.Client({
  rpcServerAddr: 'https://ip:port',
});

Get client NKN address, which is used to receive data from other clients:

console.log(client.addr);

Listen for connection established:

client.onConnect(() => {
  console.log('Client ready.');
});

Send text message to other clients:

client.send(
  'another-client-address',
  'hello world!',
);

You can also send byte array directly:

client.send(
  'another-client-address',
  Uint8Array.from([1,2,3,4,5]),
);

The destination address can also be a name registered using wallet.

Publish text message to all subscribers of a topic (subscribe is done through wallet):

client.publish(
  'topic',
  'hello world!',
);

Receive data from other clients:

client.onMessage(({ src, payload }) => {
  console.log('Receive message', payload, 'from', src);
});

If a valid data (string or Uint8Array) is returned at the end of the handler, the data will be sent back to sender as reply:

client.onMessage(({ src, payload }) => {
  return 'Well received!';
});

Handler can also be an async function, and reply can be byte array as well:

client.onMessage(async ({ src, payload }) => {
  return Uint8Array.from([1,2,3,4,5]);
});

Note that if multiple message handlers are added, the result returned by the first handler (in the order of being added) will be sent as reply.

The send method will return a Promise that will be resolved when sender receives a reply, or rejected if not receiving reply or acknowledgement within timeout period. Similar to message, reply can be either string or byte array:

client.send(
  'another-client-address',
  'hello world!',
).then((reply) => {
  // The reply here can be either string or Uint8Array
  console.log('Receive reply:', reply);
}).catch((e) => {
  // This will most likely to be timeout
  console.log('Catch:', e);
});

Client receiving data will automatically send an acknowledgement back to sender if message handler returns null or undefined so that sender will be able to know if the packet has been delivered. On the sender's side, it's almost the same as receiving a reply, except that the Promise is resolved with null:

client.send(
  'another-client-address',
  'hello world!',
).then(() => {
  console.log('Receive ACK');
}).catch((e) => {
  // This will most likely to be timeout
  console.log('Catch:', e);
});

If handler returns false, no reply or ACK will be sent.

Check examples/client.js for complete examples and https://docs.nkn.org/nkn-sdk-js for full documentation.

MultiClient

MultiClient creates multiple NKN client instances by adding identifier prefix (__0__., __1__., __2__., ...) to a NKN address and send/receive packets concurrently. This will greatly increase reliability and reduce latency at the cost of more bandwidth usage (proportional to the number of clients).

MultiClient basically has the same API as client, with a few additional initial configurations and session mode:

let multiclient = new nkn.MultiClient({
  numSubClients: 4,
  originalClient: false,
});

where originalClient controls whether a client with original identifier (without adding any additional identifier prefix) will be created, and numSubClients controls how many sub-clients to create by adding prefix __0__., __1__., __2__., etc. Using originalClient: true and numSubClients: 0 is equivalent to using a standard NKN Client without any modification to the identifier. Note that if you use originalClient: true and numSubClients is greater than 0, your identifier should not starts with __X__ where X is any number, otherwise you may end up with identifier collision.

Any additional options will be passed to NKN client.

MultiClient instance shares most of the public API as regular NKN client, see client for usage and examples. If you need low-level property or API, you can use multiclient.defaultClient to get the default client and multiclient.clients to get all clients.

Check examples/client.js for complete examples and https://docs.nkn.org/nkn-sdk-js for full documentation.

Session

In addition to the default packet mode, multiclient also supports session mode, a reliable streaming protocol similar to TCP based on ncp.

Listens for incoming sessions (without listen() no sessions will be accepted):

multiclient.listen();

Dial a session:

multiclient.dial('another-client-address').then((session) => {
  console.log(session.localAddr, 'dialed a session to', session.remoteAddr);
});

Accepts for incoming sessions:

multiclient.onSession((session) => {
  console.log(session.localAddr, 'accepted a session from', session.remoteAddr);
});

Write to session:

session.write(Uint8Array.from([1,2,3,4,5])).then(() => {
  console.log('write success');
});

Read from session:

session.read().then((data) => {
  console.log('read', data);
});

session.read also accepts a maxSize parameter, e.g. session.read(maxSize). If maxSize > 0, at most maxSize bytes will be returned. If maxSize == 0 or not set, the first batch of received data will be returned. If maxSize < 0, all received data will be concatenated and returned together.

Session can be converted to WebStream using session.getReadableStream() and session.getWritableStream(closeSessionOnEnd = false). Note that WebStream is not fully supported by all browser, so you might need to polyfill it globally or setting session.ReadableStream and session.WritableStream constructors.

Check examples/session.js for complete example or try demo file transfer web app at https://nftp.nkn.org and its source code at https://github.com/nknorg/nftp-js.

Wallet

NKN Wallet SDK.

Create a new wallet with a generated key pair:

let wallet = new nkn.Wallet({ password: 'password' });

Create wallet from a secret seed:

let wallet = new nkn.Wallet({
  seed: wallet.getSeed(),
  password: 'new-wallet-password',
});

Export wallet to JSON string:

let walletJson = wallet.toJSON();

Load wallet from JSON and password:

let wallet = nkn.Wallet.fromJSON(walletJson, { password: 'password' });

By default the wallet will use RPC server provided by nkn.org. Any NKN full node can serve as a RPC server. You can create a wallet using customized RPC server:

let wallet = new nkn.Wallet({
  password: 'password',
  rpcServerAddr: 'https://ip:port',
});

Verify whether an address is a valid NKN wallet address:

console.log(nkn.Wallet.verifyAddress(wallet.address));

Verify password of the wallet:

console.log(wallet.verifyPassword('password'));

Get balance of this wallet:

wallet.getBalance().then((value) => {
  console.log('Balance for this wallet is:', value.toString());
});

Transfer token to another wallet address:

wallet.transferTo(wallet.address, 1, { fee: 0.1, attrs: 'hello world' }).then((txnHash) => {
  console.log('Transfer transaction hash:', txnHash);
});

Subscribe to a topic for this wallet for next 100 blocks (around 20 seconds per block), client using the same key pair (seed) as this wallet and same identifier as passed to subscribe will be able to receive messages from this topic:

wallet.subscribe('topic', 100, 'identifier', 'metadata', { fee: '0.1' }).then((txnHash) => {
  console.log('Subscribe transaction hash:', txnHash);
});

Check examples/wallet.js for complete examples and https://docs.nkn.org/nkn-sdk-js for full documentation.

Random bytes generation

By default, this library uses the same random bytes generator as tweetnacl-js.

If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not Math.random!), and you know what you are doing, you can plug it like this:

nkn.setPRNG(function(x, n) {
  // ... copy n random bytes into x ...
});

An example using node.js native crypto library:

crypto = require('crypto');
nkn.setPRNG(function(x, n) {
  var i, v = crypto.randomBytes(n);
  for (i = 0; i < n; i++) x[i] = v[i];
  // clean up v
});

Note that setPRNG completely replaces internal random byte generator with the one provided.

Contributing

Can I submit a bug, suggestion or feature request?

Yes. Please open an issue for that.

Can I contribute patches?

Yes, we appreciate your help! To make contributions, please fork the repo, push your changes to the forked repo with signed-off commits, and open a pull request here.

Please sign off your commit. This means adding a line "Signed-off-by: Name " at the end of each commit, indicating that you wrote the code and have the right to pass it on as an open source patch. This can be done automatically by adding -s when committing:

git commit -s

Community

nkn-sdk-js's People

Contributors

billfort avatar dependabot[bot] avatar hrishioa avatar iheron avatar leetdev avatar yilunzhang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

nkn-sdk-js's Issues

请问如何获取消息和ack的数字签名

比如我想做一款去中心化的聊天应用,每个人可以存储和分发其他人的历史消息。
那么就需要存下对方发过来消息和ack的签名,来证明这条信息是其他人发的。
现在的sdk,如何获取消息的数字签名?如何通过地址+消息计算数字签名来校验?

nkn version 1.2.1 ERR_PACKAGE_PATH_NOT_EXPORTED when running example

After installing the version 1.2.1 and trying to run an example I get

      throw e;
      ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /Users/sce9sc/Documents/Work/testNknLatestNode/node_modules/@nkn/ncp/package.json
    at new NodeError (node:internal/errors:371:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:429:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:683:3)
    at resolveExports (node:internal/modules/cjs/loader:482:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/sce9sc/Documents/Work/testNknLatestNode/node_modules/nkn-sdk/lib/multiclient/multiclient.js:8:35) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

能为app开发框架Hbuilder做个专门的插件吗

我们习惯于用开发框架Hbuilder做app,目前,我们开发的两个app需要接入nkn技术。
在Hbuilder里,按照nkn-sdk-js的说明操作,我们没能成功地实现通讯,不管是使用nodejs还是在本地web-view里面,我们都只能和node建立起连接,没能正常地实现两点通讯
Hbuilder在**内有很多开发者使用,如果能够有针对Hbuilder优化过的sdk,或者Hbuilder专门的nkn插件,我们觉得会有一大批开发者跟进,如果能实现就太感谢了

Investigate a smarter way for publish

Hi,

This is just an observation. I haven't had any issues with it! So it might be very fine as is.
Yet, i'm looking at this function with the thought of having 1000+ subscribers. It might be better to optimize before this has happened then to be surprised when it actually happens.

Lets take the following code snippet from the MultiClient sdk:

  async publish(topic: string, data: MessageData, options: PublishOptions = {}): Promise<null> {
    options = common.util.assignDefined({}, defaultPublishOptions, options, { noReply: true });
    let offset = options.offset;
    let res = await this.defaultClient.getSubscribers(topic, { offset, limit: options.limit, txPool: options.txPool });
    let subscribers = res.subscribers;
    let subscribersInTxPool = res.subscribersInTxPool;
    while (res.subscribers && res.subscribers.length >= options.limit) {
      offset += options.limit;
      res = await this.defaultClient.getSubscribers(topic, { offset, limit: options.limit });
      subscribers = subscribers.concat(res.subscribers);
    }
    if (options.txPool) {
      subscribers = subscribers.concat(subscribersInTxPool);
    }
    return await this.send(subscribers, data, options);
  }

This "feels" like a very centralized approach even though no server call to a centralized location is done. It relies on you, the one who called publish, to send it to everyone who is subscribed to a certain topic.

This is no issue for 1, 10 or even 32 subscribers. But it begins to add up as you get more. With a lot of subscribes (say thousands) this will be a burden for the one that does a publish. If that is a phone, for example, this might be a quite annoying (app might not respond or become really slow till done) issue giving a bad user experience. Specifically when you have a slower connection or lower end device!

I'd like to propose the following solution here.
You'd want a publish to as many subscribers as that's just more performant in terms of latency (i assume). I'd limit it to at most 32 publish per client. Each client that receives the publish will then publish it to at most 32 more and so forth till they all have been handled.

Adding extra metadata

As it's written above you'd keep sending the same message as you never know when to stop. You don't know which nodes have had the message. This can be solved by adding extra metadata.
The node that publishes sends a highly compressed string that indicates to which nodes the message was send. That string will always be a multiple of 2. Those 2 characters are the first 2 characters of the public key where the message is send to.
Take the following subscriber array as an example:

  subscribers: [
    'd60d5354fa0e7a105540249e04d7d90eb6217cb4cbd090002a93a09a23e84ae0',
    'ce004ce2551bf33c8ab6c77e5f8a67eb010219f30f883793261f117554b62fc2',
    'ebf2bc4846cce506c26ae6e2f11e66ac242f73f0ac98b91a1dfc24a2f3b202bf',
    '2eaa125508e902729f4ea0bb3abdb4d2991c6d2b526c7d13555fc77bc2684295',
    '81f689fe056057b89a27d63d0f1bebce67355eafc675fc2c18f9af85d39e2509',
    '308108e1a507bdbb64129190a13cbbd5f05a51166f4e2b899dc0e3674efd75d2',
    '550cef688c7ae791cf9bf9fc8a199b3bc49cf3f7337aac514d337fa22c2038a1'
  ]

The metadata would then look like:

metadata: `d6ceeb2e813055`

So d6 = d60d5354fa0e7a105540249e04d7d90eb6217cb4cbd090002a93a09a23e84ae0
ce = ce004ce2551bf33c8ab6c77e5f8a67eb010219f30f883793261f117554b62fc2
etc...

This doesn't have to be secure. It's merely a list of nodes that this node will send the publish too.

The next node receiving the message will look at all subscribers again with the API method for that.
It then looks at the metatada value and starts parsing it for each 2 string. So imagine that node receives:

  subscribers: [
    'd60d5354fa0e7a105540249e04d7d90eb6217cb4cbd090002a93a09a23e84ae0',
    'ce004ce2551bf33c8ab6c77e5f8a67eb010219f30f883793261f117554b62fc2',
    'ebf2bc4846cce506c26ae6e2f11e66ac242f73f0ac98b91a1dfc24a2f3b202bf',
    '2eaa125508e902729f4ea0bb3abdb4d2991c6d2b526c7d13555fc77bc2684295',
    '81f689fe056057b89a27d63d0f1bebce67355eafc675fc2c18f9af85d39e2509',
    '0f6c8099f44646fd3a04959eca9730626dc68b15dff4f03d7e80cae8b44e6ab6',
    '308108e1a507bdbb64129190a13cbbd5f05a51166f4e2b899dc0e3674efd75d2',
    '550cef688c7ae791cf9bf9fc8a199b3bc49cf3f7337aac514d337fa22c2038a1',
    '860292955b91fbae82050e132605694b30e2bc022a5a6c52b44999b7cd5ac52c'
  ]

The metadata would then look like:

metadata: `d6ceeb2e813055`

After it's done parsing it knows these subscribers don't have the message yet:

  subscribers: [
    '0f6c8099f44646fd3a04959eca9730626dc68b15dff4f03d7e80cae8b44e6ab6',
    '860292955b91fbae82050e132605694b30e2bc022a5a6c52b44999b7cd5ac52c'
  ]

So it adjusts the metadata to add these 2 nodes:

metadata: `d6ceeb2e8130550f86`

(note the appended 0f and 86)
and sends the message to those nodes.

Those nodes in turn follow the same logic and see no new public keys to send the message. The publish is now done.

With this suggestion i try to stay true to the concept of NKN to have an efficient pubsub (not a gossip/flood protocol) while distributing the pubsub load for highly popular topics.

I tried to be as thorough and clear as i can. I'm sure i forgot something somewhere that might make this suggestion more complicated to actually build. Or perhaps even impossible? ...

I'm looking forward to your replies :)

Cheers,
Mark

Client only connects 50% of the time using TLS and doesn't reconnect

Client only connects 50% of the time using TLS and doesn't reconnect. I can't seem to catch the error to force a reconnect. Looking through the source code it looks like you might not be catching errors from the isomorphic ws to initiate the reconnection process. This is a major problem because most sites will be using TLS and this makes connecting to the network a very inconsistent and unreliable action.

image

image

Too many workers spawn

Hi,

Since the latest version, 1.1.3, nkn-sdk with multiclient worker: true spawns 8 workers, instead of 4, in my testing.

Something's spawning them twice, I guess..?

If you go into Firefox about:debugging you can see active workers.

可以考虑提供一个兼容 nodejs Stream 的接口,降低学习成本,同时可以方便对接各种中间件(比如压缩)

比如如果兼容 Stream接口,就可以很方便用pipe的加一个Brotli压缩,或者复用一些其他的nodejs中间件,比如流量统计什么的。

参考 :

image

Does ipv4.nknlabs.io still work?

Every connection to wss://xxx-xxx-xxx-xxx.ipv4.nknlabs.io failed, with VPN or without.When I try to ping the address,it returns Name or service not known

Send response error: Error: failed to send with any client: AssertionError: Failure: Cannot coerce to Uint8Array:

Send response error: Error: failed to send with any client: AssertionError: Failure: Cannot coerce to Uint8Array:

Send response error: Error: failed to send with any client: AssertionError: Failure: Cannot coerce to Uint8Array: boolean,AssertionError: Failure: Cannot coerce to Uint8Array: boolean,AssertionError: Failure: Cannot coerce to Uint8Array: boolean,AssertionError: Failure: Cannot coerce to Uint8Array: boolean
    at MultiClient.send (/Users/z/git/ssh/node_modules/nkn-sdk/lib/multiclient/multiclient.js:377:13)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

这是什么错误?代码见截图

image

运行example中的client.js失败,Error: Challenge timeout

nkn-sdk: v1.2.7

Secret seed: 4fafbc6eac41bd476dea6878094ad7bc2ea52a9a2fa9a88dbaaeb5659737cb32
C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700
        reject(new Error('Challenge timeout'));
               ^

Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Node.js v18.15.0

Request: API method to get wallet transactions

Hi,

I went through the API but can't seem to find any method that gives me a list of transactions.

Having such an API call would be awesome!
I asked about it more often and i think the answer thus far was that it's a hidden feature somewhere. I forgot where though.

Cheers,
Mark

我错了,已解决

如题。
常见场景是,我可能需要持续不断给用户回送消息(比如推送他订阅的股票行情)

example中的client.js运行失败 Error: Challenge timeout

"nkn-sdk": "^1.2.7"
Node.js v18.15.0

Secret seed: 11d8a965788be605daee0f354f85b134488fd691651284b250261fe085339e16
Send message from alice.05cafd4dedf7a40cf948f5146c1b87fc8eb06914d21b5f196dcfb9ce592c8128 to bob.b0c144a374e384762df5abae194ecc2584ab7f91b56851a2992215a532ab8b44
Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)
Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)
Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)
Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)
C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700
        reject(new Error('Challenge timeout'));
               ^

Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Does the SDK support the mini program?

It went something wrong when I try to use the nkn-sdk-js in wechat mini program,
something like npm package dependency. If I install the dependencies manually and
try to create the client, some runtime error occured.

So does the sdk support for mini program?

Thanks!

pubsub not purging subscription from the pool

I subscribe to a topic for, say 2 blocks, and it will add me to the pool. But it might never add me to the chain, especially if I unsubscribe from that topic. And then it seems to take a long time to remove my sub from the pool.

This is a bit of an edge case, but I'd also love some details about how the pubsub mechanism works in terms of gossip of the new sub and what factors determine when/if that sub is put into the chain.

Cheers!

multiClient返回的wss节点中包含有nknlabs.io, 被谷歌检测为不安全, 导致使用sdk的网站也被谷歌浏览器提示为不安全

你好!
使用的浏览器 : 谷歌Chrome
我们的https网站使用了这个sdk, 一打开我们的网站就会调用new MultiClient(), 接着就获取例如下面的wss://144-202-102-11.ipv4.nknlabs.io节点, 然后直接提示"您要访问的是诈骗网站
144-202-102-11.ipv4.nknlabs.io 上的攻击者可能会诱骗您做一些危险的事情..."
image
然后我在谷歌安全透明度里查询到这个地址是不安全的:
https://transparencyreport.google.com/safe-browsing/search?url=144-202-102-11.ipv4.nknlabs.io
接着我修改 144-202-102-11.ipv4.nknlabs.io中除了'nknlabs.io'的其他任意内容都是报不安全, 但是只要修改了'nknlabs.io'就没事了, 所以我猜测是'nknlabs.io'被谷歌标记为了不安全.
同时我在谷歌搜索nknlabs.io的时候发现有些网站是这样的:
549e74d89e5b2f46abf162f778562bd
会不会是某些这种网站存在钓鱼行为导致了谷歌直接屏蔽了'nknlabs.io' ?
这个问题其他浏览器没有, 只是谷歌浏览器, 请问下这个有解决方案吗?

wrong seed size

Hello, I tried to import some older private keys and they are all a few characters longer than the one's being used today.. how can I claim my tokens?

Example Format:

NL69YPb8hFJjfXXNKM6EzPhcWp24XxxPXx
0224a2122514717fffef2496534cbaf4fe8c708acd594e0dfc173b256e6aec222a


session.getReadableStream()时候报错,Session handler error: ReferenceError: ReadableStream is not defined

image
session.getReadableStream()时候报错,如上图


Session handler error: ReferenceError: ReadableStream is not defined
    at Session.getReadableStream (/root/ssh/node_modules/@nkn/ncp/lib/session.js:812:52)
    at /root/ssh/serve/sshs.coffee:49:17
    at /root/ssh/node_modules/nkn-sdk/lib/multiclient/multiclient.js:300:26
    at Array.map (<anonymous>:null:null)
    at MultiClient._handleSessionMsg (/root/ssh/node_modules/nkn-sdk/lib/multiclient/multiclient.js:298:64)
    at runNextTicks (internal/process/task_queues.js:58:5)
    at processImmediate (internal/timers.js:431:9)
    at /root/ssh/node_modules/nkn-sdk/lib/multiclient/multiclient.js:172:13
    at /root/ssh/node_modules/nkn-sdk/lib/client/client.js:522:22
    at Function.all (<anonymous>:null:null)
    at Client._handleInboundMsg (/root/ssh/node_modules/nkn-sdk/lib/client/client.js:520:23)
    at Client._handleMsg (/root/ssh/node_modules/nkn-sdk/lib/client/client.js:465:16)
    at WebSocket.ws.onmessage (/root/ssh/node_modules/nkn-sdk/lib/client/client.js:649:25)

Failing to connect with multi-client and getting RPC errors

I'm getting a whole bunch of errors intermittently -- it will work for awhile just fine and then sometimes it'll throw all these RPC errors.

I'm not sure I should be seeing the RPC call failed error, should I?
I'm assuming this is related to the mainnet server?

I am using TLS, and I'll usually get a few failed websockets but it still connects and works - but then this problem arises and usually can't connect to any nodes at all.

image

v1.3.0 RpcTimeoutError: rpc timeout

v1.3.0,运行example RpcTimeoutError: rpc timeout

Secret seed: 9d130de2d046b78bdabfaabac1e78f6b34d7465c50eb2523f4eaf6668ee88549
Send message from alice.7e845b8daf621666b8beae783e41d20680499550dfd0bee1cb84d4349c8282f3 to bob.7a6629ff53df3265cdf93fe007c94f4e8b2dc4bb19d365a1cdc725f02a3d5ddd
Receive encrypted message "Hello world!" from alice.7e845b8daf621666b8beae783e41d20680499550dfd0bee1cb84d4349c8282f3 after 352 ms
Receive reply "Well received!" from bob.7a6629ff53df3265cdf93fe007c94f4e8b2dc4bb19d365a1cdc725f02a3d5ddd after 689 ms
WebSocket was closed before the connection was established
C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\common\rpc.js:121
      throw new errors.RpcTimeoutError(e.message);
            ^

RpcTimeoutError: rpc timeout
    at rpcCall (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\common\rpc.js:121:13)
    at runNextTicks (node:internal/process/task_queues:60:5)
    at listOnTimeout (node:internal/timers:538:9)
    at process.processTimers (node:internal/timers:512:7)

Node.js v18.15.0

Create a node.js duplex stream

I need some help please.
I am trying really hard to create a tunnel in node.js but I am stuck with creating a duplex stream from
session.getReadableStream() and session.getWritableStream() in order to pipe it to a tcp server and client

I know it is too much to ask . If someone can help i'll really appreciate it.

nkn.min.js 的问题

本地调试
开发模式 地址是 ws://3.81.161.173:30002/

生产模式 地址变成了 wss://3-81-161-173.ipv4.nknlabs.io:30004/

不清楚是为什么

TypeScript declarations

This SDK is lacking TypeScript declarations, which makes developing a TypeScript project using strict mode that uses this library a pain. There's no autocomplete, no intellisense, not to mention all kinds of errors and warnings all over the place.

I am building an app for the GR11 hackathon (Codeshare App using NKN), and was facing this exact issue. I decided to create my own declarations for the SDK library to get past the problem. I would like to share it so other people using this SDK can take advantage as well.

There are 2 ways to publish the declarations - either by adding them to the library itself, or by publishing them via the DefinitelyTyped project (which would create a new NPM package in the @types scope). Which one would you prefer?

I've shared the declarations file I've created in a gist for now. This is the formulation I'm using for it in my project right now (declared as a module); for publishing it would need to be slightly modified.

Let me know how you'd like me to proceed. I can turn it into a library and publish on Definitely Typed myself, or I could create a PR in this repository to have it attached to the library itself. Or you could take it from here and publish it yourself.

技术问题探讨:基于webrtc的隧道与打洞

最近看了一个有趣的实现gRPC over WebRTC
jsmouret/grpc-over-webrtc: gRPC over WebRTC : https://t.cn/A6Ljno57

让我想到了可以基于WebRTC做隧道和打洞

webtorrent/webtorrent: ⚡️ Streaming torrent client for the web : https://t.cn/RNvDtGa
RTCTunnel - 实现通过WebRTC构建网络隧道 - Go开发社区 | CTOLib码库 : https://javascript.ctolib.com/rtctunnel-rtctunnel.html
实现WebRTC P2P连接 - 掘金 : https://juejin.im/post/6844903684539678734

感觉每次都要服务器来中转包,会不会开销太大

有没有可能让服务器只负责帮忙建立隧道,然后用户和用户可以直传数据

Opening a session and keeping it open seems to increase memory usage (JS)

Hi , First of all I must say that this is an incredible work.
The examples are a very helpful. I came across a problem when trying to send a file using session and saw that memory was increasing.
Using nkn-sdk-js javascript lib and the examples for session. I found that by opening a session and leaving it open memory is increasing .

Do you have any ideas why?
Should the session be closed and reopen whenever someone sends something through it?

I am using node version 14.16.0
"nkn-sdk": "^1.2.0",

运行example中的Client.js失败,Error: Challenge timeout

nkn-sdk: v1.2.7

Secret seed: 4fafbc6eac41bd476dea6878094ad7bc2ea52a9a2fa9a88dbaaeb5659737cb32
C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700
        reject(new Error('Challenge timeout'));
               ^

Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Node.js v18.15.0

examples are broken

using "nkn-sdk": "^1.2.4"

client.js example does not work. Fails with error:

alice.onConnectFailed is not a function

运行example中的Client.js失败,Error: Challenge timeout

nkn-sdk: v1.2.7

Secret seed: 4fafbc6eac41bd476dea6878094ad7bc2ea52a9a2fa9a88dbaaeb5659737cb32
C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700
        reject(new Error('Challenge timeout'));
               ^

Error: Challenge timeout
    at Timeout._onTimeout (C:\Users\xxx\Projects\xxx\node_modules\nkn-sdk\lib\client\client.js:700:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Node.js v18.15.0

报一个axios潜在的小坑,同时 分享一篇开发博客,2020-08-22 初识 NKN ,不用SDK遍历种子节点网络

axios 的 timeout 是 response timeout 不是 connection timeout

参考 : 超时不起作用·问题#647·axios

在浏览器中问题不大,浏览器会负责超时。

但是在nodejs环境下,偶尔会卡死进程(写爬虫就经常会经常遇到),所以我重新封装了一下,参考 lib/axios.coffee

我看后端代码直接设置的timeout,其实是存在卡死的概率的。

另外,分享一篇我写的开发博客,2020-08-22 初识 NKN ,不用SDK遍历种子节点网络

Will nodes be allocated by geo location?

Hello, I am trying to use nkn client to transfer files.
I noticed that most of the IP address of websocket are from US, such as "wss://3-137-144-60.ipv4.nknlabs.io:30004". (3.137.144.60 is the IP, I guess)
But my local network is in China, so how can it be allocated to a closer node?

I noticed that I can specify the rpcServerAddr. So, if I set this parameter to a closer rpc server address, will it improve the address allocation?
Or, can I build a nkn node by myself? So that it can be allocated to this node.

vite2 依赖引入后使用报错

import没问题
let wallet = new nkn.Wallet({ password: 'password' });
new的时候就报错
image
node:14.15.3
vite:2.0.0-beta.12
vue:3.0.5

Use workers for sigchain calculations

Hey,

It might be a good idea to separate signature chain calculations into workers. Workers are widely supported, after all, and those calculations can lock up processing for a long time.

If we were to create one or more workers, for just the calculations, then that would improve the ease-of-use of this library.

Currently d-chat handles nkn related operations in one worker, which results in lock-ups and bad UX if one sends multiple messages quick succession, because sending and receiving are done in the same worker thread. But if this library calculated the signature chains in separate worker(s), then you could receive and send messages at the same time, without lock-ups.

I mean, you probably don't need a worker for receiving messages, but you do want one for sending them.

cryptic call to onConnect in example/client.js

I'm trying to understand example/client.js, and this part confuses me :

await Promise.all([
new Promise((resolve, reject) => alice.onConnect(resolve)),
new Promise((resolve, reject) => bob.onConnect(resolve)),
]);

What does this do? It waits for both clients to add a resolve function to their event listener stack, but what will that function end up being if the promise is never consumed by a then?

Also I can't help to notice that the code works just fine if we remove these four lines. I suspect the author meant to do something else.

timeout when send msg to another local client

I create and run a receiver client with onMessage event.
// receiver.js

let receiver = new nkn.Client({
  identifier: 'Char',
  seed: 'generated seed'
})
receiver.onConnect(() => {
  console.log('-----------receiver ready----------')
})
receiver.onMessage(({src, payload}) => {
  console.log('receive message:', payload, 'from:', src)
  return 'Well received'
})

And run another client, setting the responseTimeout = 0. But I cannot get the response and client reconnect after a long time.

let receiver = 'reveiver addr'     
client.onConnect(() => {      
  console.log('-------------client ready-------------')     
  client.send(receiver, 'Hello receiver', {     
    responseTimeout: 0      
  }).then(re => {      
    console.log('send result:', re)      
  }).catch(err => {      
    console.error('send error:', err)      
  })    
})  

Any problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.