@activeledger/sdk 中文文档教程

发布于 5年前 浏览 18 项目主页 更新于 3年前

Activeledger

Activeledger - Node SDK

Activeledger 节点 SDK 已构建为提供一种将基于节点的应用程序与 Activeledger 网络连接起来的简单方法。 此 SDK 可用于 JavaScript 和 TypeScript 项目。

GitHub

存储库在这里

Further Documentation

文档在这里

Installation

$ npm i -s @activeledger/sdk

Usage

SDK 目前支持以下功能

  • Connection handling
  • Key generation
  • Key onboarding
  • Transaction building
  • Encrypted & unencrypted transaction posting
  • SSE Subscriptions

安装 SDK 后,根据需要导入类和接口。

// Example
import { Connection } from "@activeledger/sdk";

Enums

Activeledger Node SDK 提供了一个枚举来帮助处理密钥类型。

KeyRef
Elliptic CurveKeyType.EllipticCurve
RSAKeyType.RSA

Interfaces

Activeledger Node SDK提供多种接口供您使用。

InterfaceDescription
IKeyFor Activeledger keys
IOnboardTxSpecifically for key onboarding, mainly used internally
IOnboardTxBodyUsed by IOnboardTx for \$tx variable
INodeKeyDataUsed to hold the node key data for encrypting a transaction
IHttpOptionsInternal interface for setting HTTP options
ILedgerResponseA helper for the ledger response
ISummaryObjectUsed by ILedgerResponse
IStreamsObjectUsed by ILedgerResponse
INewObjectUsed by IStreamsObject
IUpdatedObjectUsed by IStreamsObject
IBaseTransactionHelper for creating transactions
ITxBodyUsed by IBaseTransaction for the \$tx variable

Connection

发送交易时,您必须传递一个连接,该连接提供与网络和指定节点建立链接所需的信息。

为此,必须创建一个连接对象。 必须向该对象传递协议、地址、端口和可选的加密标志。

Example

import { Connection } from "@activeledger/sdk";
// Setup the connection object to use localhost over http unencrypted
const connection = new Connection("http", "localhost", 5260);

// Use localhost but encrypt transactions
const connection = new Connection("http", "localhost", 5260, true);

KeyHandler

注意:生成 RSA 密钥会占用大量资源,可能需要几秒钟。

密钥处理程序可用于生成和载入密钥。

密钥生成功能和密钥载入功能设置为单独使用,因为您可能不想立即载入密钥。 此外,您将需要存储密钥,因为它用于签署涉及您在登录时创建的身份的所有交易。

目前可以生成两种密钥类型,更多的密钥类型正在计划中,将首先在 Activeledger 中实现。 这些类型是 RSA 和椭圆曲线。

Generating a key

生成密钥时,您必须将名称和密钥类型传递给它。

Example

注意:此示例使用提供密钥结构的 IKey 接口

import { KeyHandler, IKey, KeyType } from "@activeledger/sdk";

const keyHandler = new KeyHandler();

let key: IKey;

// Generate RSA Key
keyHandler
  .generateKey("keyname", KeyType.RSA)
  .then((generatedKey: IKey) => {
    key = generatedKey;
  })
  .catch();
// or to generate an Elliptic Curve key
// keyHandler.generateKey("keyname", KeyType.EllipticCurve)

Onboarding a key

生成密钥后,要使用它签署交易,必须将其加入分类帐网络

Example
import { Connection, KeyHandler, IKey, KeyType, ILedgerResponse } from "@activeledger/sdk";

const connection = new Connection("http", "localhost", 5260);
const keyHandler = new KeyHandler();

let key: IKey;
keyHandler
  .generateKey("keyname", KeyType.EllipticCurve)
  .then((generatedKey: IKey) => {
    key = generatedKey;
    return keyHandler.onboardKey(key, connection);
  })
  .then((ledgerResp: ILedgerResponse) => {
    resolve(ledgerResp);
  })
  .catch();

Exporting a key

您可以使用 SDK 将 JSON 格式的密钥导出到文件系统。 这将与 IKey 接口具有相同的结构。

导出密钥时,所需的参数是密钥对象和存储它的位置。 请注意,该位置不应包含文件名,这是一个可选参数。

ParameterDescriptionTypeRequired
keyThe Key objectIKeyYes
locationThe storage locationstringYes
createDirCreate directory if it doesn't existbooleanNo
overwriteOverwrite a file with the same namebooleanNo
nameThe name of the filestringNo
Example
import { KeyHandler } from "@activeledger/sdk";

const keyHandler = new KeyHandler();

const key: IKey = await keyHandler.generateKey("Key Name", KeyType.EllipticCurve);
keyHandler.exportKey(key, "./").then(() => {
  // Now export is finished do something
});

Importing a key

您还可以使用 SDK 从文件系统导入密钥。 请注意,此密钥文件必须遵循与 IKey 接口相同的结构。

导入函数要求 location 参数包含扩展名为 .json 的文件名。

ParameterDescriptionTypeRequired
locationThe storage locationstringYes
Example
import { KeyHandler } from "@activeledger/sdk";

const keyHandler = new KeyHandler();
keyHandler.importKey(`./${key.name}.json`).then((importedKey: IKey) => {
  // Do something with the key
});

TransactionHandler

交易处理程序用于签署和发送交易。

在构建要发送到分类帐的交易时,您可以使用 IBaseTransaction 作为助手。

Signing a transaction

签署交易时,您必须发送交易的完成版本。 签名后不能进行任何更改,因为这将导致分类帐拒绝它。

您必须将交易和正确的密钥传递给此函数。 密钥必须是已成功加入交易发送到的分类帐的密钥。

也可以将要签名的交易作为字符串发送,然后签名函数将只返回签名作为字符串。

Example
import { TransactionHandler, IBaseTransaction } from "@activeledger/sdk";

// Connection and key code goes here if needed

// Create a transaction. In this example a namespace onboarding transaction
const txHandler = new TransactionHandler();
const tx: IBaseTransaction = {
  $sigs: {},
  $tx: {
    $contract: "namespace",
    $i: {},
    $namespace: "default",
  },
};

// The identity of the key that the namespace will be linked to
tx.$tx.$i[key.identity] = {
  namespace: "example-namespace",
};

// Sign the transaction
txHandler
  .signTransaction(tx, key)
  .then((signedTx: IBaseTransaction) => {
    tx = signedTx;
  })
  .catch();

// Sign a string transaction
txHandler
  .signTransaction("Hello world", key)
  .then((signature: string) => {
    // Do something with the signature
  })
  .catch();

Sending a transaction

Example
import { TransactionHandler, IBaseTransaction } from "@activeledger/sdk";

// Connection setup, Transaction building and signing here

// Send the transaction
txHandler
  .sendTransaction(tx, connection)
  .then((response: ILedgerResponse) => {
    // Do something with the response
  })
  .catch();

Events

SDK 的事件类使调用者可以轻松访问 ActiveCore 提供的服务器端事件。

Example usage

Initialise
import { LedgerEvents } from "@activeledger/sdk";

const events = new LedgerEvents("{ActiveCore URL}");
Subscribe to all Activities
const reference = events.subscribeToActivity(eventData => {
  // Do something with event data
});
Subscribe to a specific Activity
const reference = events.subscribeToActivity("{activityStream}", eventData => {
  // Do something with event data
});
Subscribe to all events
const reference = events.subscribeToEvent(eventData => {
  // Do something with event data
});
Subscribe to all events of a specific contract
const config: IEventConfig {
  contract: "{contractId}"
};

const reference = events.subscribeToEvent(eventData => {
    // Do something with event data
  },
  config
);
Subscribe to a specific event of a specific contract
const config: IEventConfig {
  contract: "{contractId}",
  event: "{contractId}"
};

const reference = events.subscribeToEvent(eventData => {
    // Do something with event data
  },
  config
);
Unsubscribe from an event

这对于 Activity 事件和 Events 都是一样的。

// Create a subscription and store the returned reference number
const reference = events.subscribeToActivity(eventData => {
  // Do something with event data
});

// Unsubscribe
events.unsubscribe(reference);

Further Documentation

您可以在此处阅读更多文档。

Activeledger

访问 Activeledger.io

阅读 Activeledgers 文档

License


该项目已根据 MIT 许可证

Activeledger

Activeledger - Node SDK

The Activeledger Node SDK has been built to provide an easy way to connect your Node based application with an Activeledger network. This SDK can be used in JavaScript and TypeScript projects.

GitHub

Repository here

Further Documentation

Documentation here

Installation

$ npm i -s @activeledger/sdk

Usage

The SDK currently supports the following functionality

  • Connection handling
  • Key generation
  • Key onboarding
  • Transaction building
  • Encrypted & unencrypted transaction posting
  • SSE Subscriptions

Once the SDK has been installed import the classes and interfaces as you need them.

// Example
import { Connection } from "@activeledger/sdk";

Enums

The Activeledger Node SDK provides an enum to help handle key types.

KeyRef
Elliptic CurveKeyType.EllipticCurve
RSAKeyType.RSA

Interfaces

The Activeledger Node SDK provides multiple interfaces to provide you with.

InterfaceDescription
IKeyFor Activeledger keys
IOnboardTxSpecifically for key onboarding, mainly used internally
IOnboardTxBodyUsed by IOnboardTx for \$tx variable
INodeKeyDataUsed to hold the node key data for encrypting a transaction
IHttpOptionsInternal interface for setting HTTP options
ILedgerResponseA helper for the ledger response
ISummaryObjectUsed by ILedgerResponse
IStreamsObjectUsed by ILedgerResponse
INewObjectUsed by IStreamsObject
IUpdatedObjectUsed by IStreamsObject
IBaseTransactionHelper for creating transactions
ITxBodyUsed by IBaseTransaction for the \$tx variable

Connection

When sending a transaction, you must pass a connection that provides the information needed to establish a link to the network and specified node.

To do this a connection object must be created. This object must be passed the protocol, address, port, and optionally the encryption flag.

Example

import { Connection } from "@activeledger/sdk";
// Setup the connection object to use localhost over http unencrypted
const connection = new Connection("http", "localhost", 5260);

// Use localhost but encrypt transactions
const connection = new Connection("http", "localhost", 5260, true);

KeyHandler

Note: Generating an RSA key is resource intensive and can take a few seconds.

The Key Handler can be used to generate and onboard a key.

The Key generation function and key onboard function are setup to be used separately as you may not want to immediately onboard a key. Additionally, you will need to store the key as it is used to sign all transactions involving the identity created when you onboard it.

There are two key types that can be generated currently, more are planned and will be implemented into Activeledger first. These types are RSA and Elliptic Curve.

Generating a key

When generating a key you must pass it a name and the key type.

Example

Note: This example uses the IKey interface which provides the structure of the key

import { KeyHandler, IKey, KeyType } from "@activeledger/sdk";

const keyHandler = new KeyHandler();

let key: IKey;

// Generate RSA Key
keyHandler
  .generateKey("keyname", KeyType.RSA)
  .then((generatedKey: IKey) => {
    key = generatedKey;
  })
  .catch();
// or to generate an Elliptic Curve key
// keyHandler.generateKey("keyname", KeyType.EllipticCurve)

Onboarding a key

Once you have a key generated, to use it to sign transactions it must be onboarded to the ledger network

Example
import { Connection, KeyHandler, IKey, KeyType, ILedgerResponse } from "@activeledger/sdk";

const connection = new Connection("http", "localhost", 5260);
const keyHandler = new KeyHandler();

let key: IKey;
keyHandler
  .generateKey("keyname", KeyType.EllipticCurve)
  .then((generatedKey: IKey) => {
    key = generatedKey;
    return keyHandler.onboardKey(key, connection);
  })
  .then((ledgerResp: ILedgerResponse) => {
    resolve(ledgerResp);
  })
  .catch();

Exporting a key

You can use the SDK to export a key in JSON format to the filesystem. This will be in the same structure as the IKey interface.

When exporting a key the required parameters are the Key object and the location to store it. Note that the location should not include the name of the file, this is an optional parameter.

ParameterDescriptionTypeRequired
keyThe Key objectIKeyYes
locationThe storage locationstringYes
createDirCreate directory if it doesn't existbooleanNo
overwriteOverwrite a file with the same namebooleanNo
nameThe name of the filestringNo
Example
import { KeyHandler } from "@activeledger/sdk";

const keyHandler = new KeyHandler();

const key: IKey = await keyHandler.generateKey("Key Name", KeyType.EllipticCurve);
keyHandler.exportKey(key, "./").then(() => {
  // Now export is finished do something
});

Importing a key

You can also use the SDK to import a key from the file system. Note that this key file must follow the same structure as the IKey interface.

The import function requires that the location parameter includes the file name with .json extension.

ParameterDescriptionTypeRequired
locationThe storage locationstringYes
Example
import { KeyHandler } from "@activeledger/sdk";

const keyHandler = new KeyHandler();
keyHandler.importKey(`./${key.name}.json`).then((importedKey: IKey) => {
  // Do something with the key
});

TransactionHandler

The Transaction Handler is used to sign and send transactions.

You can use the IBaseTransaction as a helper when building a transaction to be sent to the ledger.

Signing a transaction

When signing a transaction you must send the finished version of it. No changes can be made after signing as this will cause the ledger to reject it.

You must pass the transaction and the correct key to this function. The key must be one that has been successfully onboarded to the ledger which the transaction is being sent to.

It is also possible to send the transaction to be signed as a string, the signing function will then return just the signature as a string.

Example
import { TransactionHandler, IBaseTransaction } from "@activeledger/sdk";

// Connection and key code goes here if needed

// Create a transaction. In this example a namespace onboarding transaction
const txHandler = new TransactionHandler();
const tx: IBaseTransaction = {
  $sigs: {},
  $tx: {
    $contract: "namespace",
    $i: {},
    $namespace: "default",
  },
};

// The identity of the key that the namespace will be linked to
tx.$tx.$i[key.identity] = {
  namespace: "example-namespace",
};

// Sign the transaction
txHandler
  .signTransaction(tx, key)
  .then((signedTx: IBaseTransaction) => {
    tx = signedTx;
  })
  .catch();

// Sign a string transaction
txHandler
  .signTransaction("Hello world", key)
  .then((signature: string) => {
    // Do something with the signature
  })
  .catch();

Sending a transaction

Example
import { TransactionHandler, IBaseTransaction } from "@activeledger/sdk";

// Connection setup, Transaction building and signing here

// Send the transaction
txHandler
  .sendTransaction(tx, connection)
  .then((response: ILedgerResponse) => {
    // Do something with the response
  })
  .catch();

Events

The event class of the SDK provides the caller with easy access to the server side events provided by ActiveCore.

Example usage

Initialise
import { LedgerEvents } from "@activeledger/sdk";

const events = new LedgerEvents("{ActiveCore URL}");
Subscribe to all Activities
const reference = events.subscribeToActivity(eventData => {
  // Do something with event data
});
Subscribe to a specific Activity
const reference = events.subscribeToActivity("{activityStream}", eventData => {
  // Do something with event data
});
Subscribe to all events
const reference = events.subscribeToEvent(eventData => {
  // Do something with event data
});
Subscribe to all events of a specific contract
const config: IEventConfig {
  contract: "{contractId}"
};

const reference = events.subscribeToEvent(eventData => {
    // Do something with event data
  },
  config
);
Subscribe to a specific event of a specific contract
const config: IEventConfig {
  contract: "{contractId}",
  event: "{contractId}"
};

const reference = events.subscribeToEvent(eventData => {
    // Do something with event data
  },
  config
);
Unsubscribe from an event

This is the same for both Activity events and Events

// Create a subscription and store the returned reference number
const reference = events.subscribeToActivity(eventData => {
  // Do something with event data
});

// Unsubscribe
events.unsubscribe(reference);

Further Documentation

You can read further documentation here.

Activeledger

Visit Activeledger.io

Read Activeledgers documentation

License


This project is licensed under the MIT License

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文