diff --git a/.yarn/cache/@learntheropes-node-rsa-npm-1.1.3-f4fcd76179-d35d8efe2a.zip b/.yarn/cache/@learntheropes-node-rsa-npm-1.1.3-f4fcd76179-d35d8efe2a.zip deleted file mode 100644 index 27930069..00000000 Binary files a/.yarn/cache/@learntheropes-node-rsa-npm-1.1.3-f4fcd76179-d35d8efe2a.zip and /dev/null differ diff --git a/.yarn/cache/@peculiar-asn1-schema-npm-2.3.8-cc6ab012ff-1f4dd421f1.zip b/.yarn/cache/@peculiar-asn1-schema-npm-2.3.8-cc6ab012ff-1f4dd421f1.zip new file mode 100644 index 00000000..4f14df43 Binary files /dev/null and b/.yarn/cache/@peculiar-asn1-schema-npm-2.3.8-cc6ab012ff-1f4dd421f1.zip differ diff --git a/.yarn/cache/@peculiar-json-schema-npm-1.1.12-f914d2ea65-b26ececdc2.zip b/.yarn/cache/@peculiar-json-schema-npm-1.1.12-f914d2ea65-b26ececdc2.zip new file mode 100644 index 00000000..8887235d Binary files /dev/null and b/.yarn/cache/@peculiar-json-schema-npm-1.1.12-f914d2ea65-b26ececdc2.zip differ diff --git a/.yarn/cache/@peculiar-webcrypto-npm-1.4.6-bae8244a02-27201a9b8a.zip b/.yarn/cache/@peculiar-webcrypto-npm-1.4.6-bae8244a02-27201a9b8a.zip new file mode 100644 index 00000000..d45fec1b Binary files /dev/null and b/.yarn/cache/@peculiar-webcrypto-npm-1.4.6-bae8244a02-27201a9b8a.zip differ diff --git a/.yarn/cache/asn1-npm-0.2.4-219dd49411-aa5d6f77b1.zip b/.yarn/cache/asn1-npm-0.2.4-219dd49411-aa5d6f77b1.zip deleted file mode 100644 index b7078b1f..00000000 Binary files a/.yarn/cache/asn1-npm-0.2.4-219dd49411-aa5d6f77b1.zip and /dev/null differ diff --git a/.yarn/cache/asn1js-npm-3.0.5-cf5558af33-3b6af1bbad.zip b/.yarn/cache/asn1js-npm-3.0.5-cf5558af33-3b6af1bbad.zip new file mode 100644 index 00000000..22a8145d Binary files /dev/null and b/.yarn/cache/asn1js-npm-3.0.5-cf5558af33-3b6af1bbad.zip differ diff --git a/.yarn/cache/buffer-npm-6.0.3-cd90dfedfe-5ad23293d9.zip b/.yarn/cache/buffer-npm-6.0.3-cd90dfedfe-5ad23293d9.zip deleted file mode 100644 index dbf2748b..00000000 Binary files a/.yarn/cache/buffer-npm-6.0.3-cd90dfedfe-5ad23293d9.zip and /dev/null differ diff --git a/.yarn/cache/pvtsutils-npm-1.3.5-b3122eabea-e734516b3c.zip b/.yarn/cache/pvtsutils-npm-1.3.5-b3122eabea-e734516b3c.zip new file mode 100644 index 00000000..6f498460 Binary files /dev/null and b/.yarn/cache/pvtsutils-npm-1.3.5-b3122eabea-e734516b3c.zip differ diff --git a/.yarn/cache/pvutils-npm-1.1.3-da8b07d6cf-2ee26a9e51.zip b/.yarn/cache/pvutils-npm-1.1.3-da8b07d6cf-2ee26a9e51.zip new file mode 100644 index 00000000..0df7fa84 Binary files /dev/null and b/.yarn/cache/pvutils-npm-1.1.3-da8b07d6cf-2ee26a9e51.zip differ diff --git a/.yarn/cache/tslib-npm-2.6.2-4fc8c068d9-329ea56123.zip b/.yarn/cache/tslib-npm-2.6.2-4fc8c068d9-329ea56123.zip new file mode 100644 index 00000000..3424b444 Binary files /dev/null and b/.yarn/cache/tslib-npm-2.6.2-4fc8c068d9-329ea56123.zip differ diff --git a/.yarn/cache/webcrypto-core-npm-1.7.9-5e551fbc82-05aa125516.zip b/.yarn/cache/webcrypto-core-npm-1.7.9-5e551fbc82-05aa125516.zip new file mode 100644 index 00000000..9473ebcd Binary files /dev/null and b/.yarn/cache/webcrypto-core-npm-1.7.9-5e551fbc82-05aa125516.zip differ diff --git a/README.md b/README.md index fe60adfa..72a598fc 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,12 @@ Encointer JavaScript API monorepo # Installation +## Crypto library +The worker uses the webcrypto api if it is run in the browser. This library is only +defined if you access the webpage with `localhost` in firefox. It is not available +on `127.0.0.1` or `0.0.0.0` due to browser security policies. + + ```bash yarn add @encointer/node-api @encointer/worker-api ``` diff --git a/lerna.json b/lerna.json index d7598416..c66bfd98 100644 --- a/lerna.json +++ b/lerna.json @@ -7,5 +7,5 @@ "publishConfig": { "directory": "build" }, - "version": "0.12.4" + "version": "0.12.5-alpha.9" } diff --git a/packages/node-api/package.json b/packages/node-api/package.json index f14dacc6..73e8100c 100644 --- a/packages/node-api/package.json +++ b/packages/node-api/package.json @@ -18,10 +18,10 @@ }, "sideEffects": false, "type": "module", - "version": "0.12.4", + "version": "0.12.5-alpha.9", "main": "index.js", "dependencies": { - "@encointer/types": "^0.12.4", + "@encointer/types": "^0.12.5-alpha.9", "@polkadot/api": "^10.9.1", "tslib": "^2.5.3" }, diff --git a/packages/types/package.json b/packages/types/package.json index 63db7bb9..5e2d6893 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -18,7 +18,7 @@ }, "sideEffects": false, "type": "module", - "version": "0.12.4", + "version": "0.12.5-alpha.9", "main": "index.js", "scripts": { "generate:defs": "node --experimental-specifier-resolution=node --loader ts-node/esm ../../node_modules/.bin/polkadot-types-from-defs --package @encointer/types/interfaces --input ./src/interfaces", diff --git a/packages/util/package.json b/packages/util/package.json index 80063221..3be9501c 100644 --- a/packages/util/package.json +++ b/packages/util/package.json @@ -20,7 +20,7 @@ "sideEffects": false, "type": "module", "types": "./index.d.ts", - "version": "0.12.4", + "version": "0.12.5-alpha.9", "main": "index.js", "dependencies": { "@babel/runtime": "^7.18.9", diff --git a/packages/util/src/assignment.ts b/packages/util/src/assignment.ts index 5745d601..ba135622 100644 --- a/packages/util/src/assignment.ts +++ b/packages/util/src/assignment.ts @@ -11,7 +11,7 @@ import { parseDegree } from "@encointer/types"; import {u64, Vec} from "@polkadot/types"; import {Option} from "@polkadot/types-codec"; import type {Moment} from "@polkadot/types/interfaces/runtime"; -import assert from "assert"; +// import assert from "assert"; /** * Performs the same meetup assignment as the encointer-ceremonies pallet. @@ -234,7 +234,7 @@ export function assignmentFnInverse( } // never observed in practice - assert(t3 >= 0, `[assignment_fn_inverse]: t3 smaller 0: ${t3}`); + // assert(t3 >= 0, `[assignment_fn_inverse]: t3 smaller 0: ${t3}`); participants.push(t3) diff --git a/packages/util/src/common.ts b/packages/util/src/common.ts index 6e1fa9e3..770bc23a 100644 --- a/packages/util/src/common.ts +++ b/packages/util/src/common.ts @@ -1,19 +1,18 @@ -import assert from 'assert'; import type { KeyringPair } from "@polkadot/keyring/types"; import { Keyring } from "@polkadot/keyring"; import BN from "bn.js"; -interface assertLengthFunc { - (upper: number, lower: number): number -} - -export const assertLength: assertLengthFunc = function (upper, lower) { - const len = upper + lower; - assert(len >= 8, `Bit length can't be less than 8, provided ${len}`); - assert(len <= 128, `Bit length can't be bigger than 128, provided ${len}`); - assert(!(len & (len - 1)), `Bit length should be power of 2, provided ${len}`); - return len; -}; +// interface assertLengthFunc { +// (upper: number, lower: number): number +// } +// +// export const assertLength: assertLengthFunc = function (upper, lower) { +// const len = upper + lower; +// assert(len >= 8, `Bit length can't be less than 8, provided ${len}`); +// assert(len <= 128, `Bit length can't be bigger than 128, provided ${len}`); +// assert(!(len & (len - 1)), `Bit length should be power of 2, provided ${len}`); +// return len; +// }; export interface PubKeyPinPair { pubKey: string, diff --git a/packages/util/src/parserFixPoint.ts b/packages/util/src/parserFixPoint.ts index 5aa1cdc1..35788e10 100644 --- a/packages/util/src/parserFixPoint.ts +++ b/packages/util/src/parserFixPoint.ts @@ -1,7 +1,7 @@ import BN from "bn.js"; -import assert from "assert"; +// import assert from "assert"; -import { assertLength } from "./common.js"; +// import { assertLength } from "./common.js"; export interface ParserFixPointFn { (raw: BN, precision?: number): number; @@ -25,9 +25,10 @@ export interface ParserFixPointFactory { /// raw: substrate_fixed::types::IF as I /// precision: 0..lower number bits in fractional part to process export const parserFixPoint: ParserFixPointFactory = function (upper, lower) { - const len = assertLength(upper, lower); + // const len = assertLength(upper, lower); + const len = upper + lower; return (raw: BN, precision: number = lower): number => { - assert(raw.bitLength() <= len, "Bit length is not equal to " + len); + // assert(raw.bitLength() <= len, "Bit length is not equal to " + len); raw = raw.fromTwos(len); diff --git a/packages/util/src/toFixPoint.ts b/packages/util/src/toFixPoint.ts index 36a298ab..dd4db1b6 100644 --- a/packages/util/src/toFixPoint.ts +++ b/packages/util/src/toFixPoint.ts @@ -1,7 +1,6 @@ -import assert from 'assert'; import BN from 'bn.js'; -import {assertLength, fractionalToRadix2, safeIntegerToRadix2} from './common.js'; +import {fractionalToRadix2, safeIntegerToRadix2} from './common.js'; export interface ToFixPointFn { (num: number): BN; @@ -20,7 +19,7 @@ export interface StringToFixPointFactory { } export const toFixPoint: ToFixPointFactory = function (upper, lower) { - assertLength(upper, lower); + // assertLength(upper, lower); return (num: number): BN => { const [upperBits, lowerBits] = num.toString(2).split('.'); @@ -29,7 +28,7 @@ export const toFixPoint: ToFixPointFactory = function (upper, lower) { }; export const stringToFixPoint: StringToFixPointFactory = function (upper, lower) { - assertLength(upper, lower); + // assertLength(upper, lower); return (num: string): BN => { let [integers, fractions] = num.split('.'); @@ -52,9 +51,9 @@ export const stringToFixPoint: StringToFixPointFactory = function (upper, lower) * @param fractions_count amount of fractional bits in the fixed-point type. */ const toFixed = function(integers: string, fractions: string, integer_count: number, fractions_count: number): BN { - assertLength(integer_count, fractions_count); + // assertLength(integer_count, fractions_count); - assert(integers.length <= integer_count, 'Number is larger than maximum in '.concat(integer_count.toString(), 'bit')); + // assert(integers.length <= integer_count, 'Number is larger than maximum in '.concat(integer_count.toString(), 'bit')); if (fractions !== undefined) { const bits = integers.concat(fractions.length > fractions_count ? fractions.substring(0, fractions_count) : fractions.padEnd(fractions_count, '0')); diff --git a/packages/worker-api/package.json b/packages/worker-api/package.json index 95995e8e..79c5b08a 100644 --- a/packages/worker-api/package.json +++ b/packages/worker-api/package.json @@ -19,13 +19,13 @@ "sideEffects": false, "type": "module", "types": "./index.d.ts", - "version": "0.12.4", + "version": "0.12.5-alpha.9", "main": "index.js", "dependencies": { - "@encointer/node-api": "^0.12.4", - "@encointer/types": "^0.12.4", - "@encointer/util": "^0.12.4", - "@learntheropes/node-rsa": "^1.1.3", + "@encointer/node-api": "^0.12.5-alpha.9", + "@encointer/types": "^0.12.5-alpha.9", + "@encointer/util": "^0.12.5-alpha.9", + "@peculiar/webcrypto": "^1.4.6", "@polkadot/api": "^10.9.1", "@polkadot/keyring": "^12.3.2", "@polkadot/types": "^10.9.1", diff --git a/packages/worker-api/src/encointerWorker.ts b/packages/worker-api/src/encointerWorker.ts index 07b37ce1..9a6a2c3c 100644 --- a/packages/worker-api/src/encointerWorker.ts +++ b/packages/worker-api/src/encointerWorker.ts @@ -1,9 +1,6 @@ import type {u32, u64, Vec} from '@polkadot/types'; import {communityIdentifierFromString} from '@encointer/util'; -// @ts-ignore -import NodeRSA from '@learntheropes/node-rsa'; - import type { CommunityIdentifier, MeetupIndexType, diff --git a/packages/worker-api/src/integriteeWorker.spec.ts b/packages/worker-api/src/integriteeWorker.spec.ts index bc62d19f..d7884e4e 100644 --- a/packages/worker-api/src/integriteeWorker.spec.ts +++ b/packages/worker-api/src/integriteeWorker.spec.ts @@ -91,13 +91,14 @@ describe('worker', () => { describe('balance unshield should work', () => { it('should return value', async () => { const shard = network.chosenCid; + const result = await worker.balanceUnshieldFunds( alice, shard, network.mrenclave, alice.address, charlie.address, - 1100000000000 + 1100000000000, ); console.log('balance unshield result', result.toHuman()); expect(result).toBeDefined(); diff --git a/packages/worker-api/src/integriteeWorker.ts b/packages/worker-api/src/integriteeWorker.ts index 6ece7893..e4419944 100644 --- a/packages/worker-api/src/integriteeWorker.ts +++ b/packages/worker-api/src/integriteeWorker.ts @@ -1,9 +1,5 @@ import type {u32} from '@polkadot/types'; -// @ts-ignore -import NodeRSA from '@learntheropes/node-rsa'; - - import type {KeyringPair} from '@polkadot/keyring/types'; import type {Balance, Hash} from '@polkadot/types/interfaces/runtime'; import type { diff --git a/packages/worker-api/src/interface.ts b/packages/worker-api/src/interface.ts index fae60c6f..64af01e8 100644 --- a/packages/worker-api/src/interface.ts +++ b/packages/worker-api/src/interface.ts @@ -11,7 +11,7 @@ export interface IWorker extends WebSocketAsPromised { keyring: () => Keyring | undefined; createType: (apiType: string, obj?: any) => any; open: () => Promise; - encrypt: (data: Uint8Array) => Vec + encrypt: (data: Uint8Array) => Promise> registry: () => TypeRegistry } @@ -49,8 +49,8 @@ export interface PublicGetterArgs { export type RequestArgs = PublicGetterArgs | TrustedGetterArgs | { } export interface CallOptions { - timeout: number; - debug: boolean; + timeout?: number; + debug?: boolean; } export enum Request { diff --git a/packages/worker-api/src/parsers.ts b/packages/worker-api/src/parsers.ts index 75e643a5..80738d18 100644 --- a/packages/worker-api/src/parsers.ts +++ b/packages/worker-api/src/parsers.ts @@ -1,12 +1,8 @@ -import { parseI64F64 } from '@encointer/util'; -import { u8aToBn } from '@polkadot/util'; +import {parseI64F64} from '@encointer/util'; +import {u8aToBn} from '@polkadot/util'; -// @ts-ignore -import NodeRSA from '@learntheropes/node-rsa'; - -import type { IWorker } from './interface.js'; -import type { BalanceEntry } from "@encointer/types"; -import BN from "bn.js"; +import type {IWorker} from './interface.js'; +import type {BalanceEntry} from "@encointer/types"; export function parseBalance(self: IWorker, data: any): BalanceEntry { const balanceEntry = self.createType('BalanceEntry', data); @@ -23,44 +19,4 @@ export function parseBalanceType(data: any): number { return parseI64F64(u8aToBn(data)); } -/** - * Parse a public key retrieved from the worker into `NodeRsa`. - * - * Note: This code is relatively sensitive: Changes here could lead - * to errors parsing and encryption errors in the browser, probably - * because of inconsistencies of node's `Buffer and the `buffer` - * polyfill in browser. - * @param data - */ -export function parseNodeRSA(data: any): NodeRSA { - const keyJson = JSON.parse(data); - keyJson.n = new BN(keyJson.n, 'le'); - keyJson.e = new BN(keyJson.e); - const key = new NodeRSA(); - setKeyOpts(key); - key.importKey({ - // Important: use string here, not buffer, otherwise the browser will - // misinterpret the `n`. - n: keyJson.n.toString(10), - // Important: use number here, not buffer, otherwise the browser will - // misinterpret the `e`. - e: keyJson.e.toNumber() - }, 'components-public'); - return key; -} -function setKeyOpts(key: NodeRSA) { - key.setOptions( - { - // Enforce using the pure javascript implementations by - // setting the `browser` environment, as compatibility - // with node's crypto is broken and leads to bad outputs. - environment: 'browser', - encryptionScheme: { - scheme: 'pkcs1_oaep', - hash: 'sha256', - label: '' - } - } - ); -} diff --git a/packages/worker-api/src/sendRequest.ts b/packages/worker-api/src/sendRequest.ts index 533256c9..6f31ea95 100644 --- a/packages/worker-api/src/sendRequest.ts +++ b/packages/worker-api/src/sendRequest.ts @@ -77,7 +77,7 @@ export const sendTrustedCall = async (self: IWorker, call: IntegriteeTrustedC console.log(`TrustedOperation: ${JSON.stringify(top)}`); - const cyphertext = self.encrypt(top.toU8a()); + const cyphertext = await self.encrypt(top.toU8a()); const r = self.createType( 'Request', { shard, cyphertext: cyphertext } diff --git a/packages/worker-api/src/testUtils/networks.ts b/packages/worker-api/src/testUtils/networks.ts index 67b3e4eb..cd471590 100644 --- a/packages/worker-api/src/testUtils/networks.ts +++ b/packages/worker-api/src/testUtils/networks.ts @@ -39,8 +39,8 @@ export const localDockerNetwork = () => { chain: 'ws://127.0.0.1:9944', worker: 'wss://127.0.0.1:2000', genesisHash: '0x388c446a804e24e77ae89f5bb099edb60cacc2ac7c898ce175bdaa08629c1439', - mrenclave: 'HjkQuPjBn531Hkji2Dsj4CEYCGpqCc3aXqETMCM7x7z4', - chosenCid: 'HjkQuPjBn531Hkji2Dsj4CEYCGpqCc3aXqETMCM7x7z4', + mrenclave: '9jm9Wm4DwGxsUUPA1cvcWWxyTuynpJ2YeEcNGnm8nztk', + chosenCid: '9jm9Wm4DwGxsUUPA1cvcWWxyTuynpJ2YeEcNGnm8nztk', customTypes: {}, palletOverrides: {} }; diff --git a/packages/worker-api/src/webCryptoRSA.ts b/packages/worker-api/src/webCryptoRSA.ts new file mode 100644 index 00000000..d6bc3427 --- /dev/null +++ b/packages/worker-api/src/webCryptoRSA.ts @@ -0,0 +1,76 @@ +import BN from "bn.js"; + +/** + * Provides crypto the browser via the native crypto, and in the node-js environment (like our tests) + * via the `@peculiar/webcrypto` polyfill. + */ +let cryptoProvider: any; + +if (typeof window !== "undefined" && typeof window.crypto !== "undefined") { + cryptoProvider = window.crypto; +} else { + const { Crypto } = require("@peculiar/webcrypto"); + cryptoProvider = new Crypto(); +} + +/** + * Type depending on our environment browser vs. node-js. + */ +type CryptoKey = import("crypto").KeyObject | import("@peculiar/webcrypto").CryptoKey; + + +export async function parseWebCryptoRSA(data: any): Promise { + const keyJson = JSON.parse(data); + + // Convert Base64url-encoded components to ArrayBuffer + const nArrayBuffer = new Uint8Array(new BN(keyJson.n, 'le').toArray()); + const eArrayBuffer = new Uint8Array(new BN(keyJson.e, 'le').toArray()); + + // Import the components into CryptoKey + const publicKey = await cryptoProvider.subtle.importKey( + "jwk", + { + kty: "RSA", + e: uint8ArrayToBase64Url(eArrayBuffer), + n: uint8ArrayToBase64Url(nArrayBuffer), + ext: true, + }, + { + name: "RSA-OAEP", + hash: "SHA-256", + }, + true, + ["encrypt"] + ); + + console.log(`PublicKey: ${JSON.stringify(publicKey)}`); + + return publicKey; +} + +export async function encryptWithPublicKey(data: Uint8Array, publicKey: CryptoKey): Promise { + const encryptedData = await cryptoProvider.subtle.encrypt( + { + name: "RSA-OAEP", + }, + publicKey, + data + ); + + // console.log(`EncryptedData: ${JSON.stringify({encrypted: buf2hex(encryptedData)})}`); + + return encryptedData; +} + + +function uint8ArrayToBase64Url(uint8Array: Uint8Array): string { + const base64String = btoa(String.fromCharCode(...uint8Array)); + return base64String + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +export function buf2hex(buffer: ArrayBuffer) { // buffer is an ArrayBuffer + return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); +} diff --git a/packages/worker-api/src/worker.ts b/packages/worker-api/src/worker.ts index 5d5378a5..9bcf3100 100644 --- a/packages/worker-api/src/worker.ts +++ b/packages/worker-api/src/worker.ts @@ -2,24 +2,21 @@ import type {Vec} from '@polkadot/types'; import {TypeRegistry} from '@polkadot/types'; import type {RegistryTypes} from '@polkadot/types/types'; import {Keyring} from '@polkadot/keyring' -import {bufferToU8a, compactAddLength, hexToU8a, u8aToBuffer} from '@polkadot/util'; +import {compactAddLength, hexToU8a} from '@polkadot/util'; import WebSocketAsPromised from 'websocket-as-promised'; import {options as encointerOptions} from '@encointer/node-api'; import {parseI64F64} from '@encointer/util'; -// @ts-ignore -import NodeRSA from '@learntheropes/node-rsa'; - -import type { - Vault -} from '@encointer/types'; +import type {Vault} from '@encointer/types'; import {type CallOptions, type IWorker, Request, type WorkerOptions} from './interface.js'; -import {parseBalance, parseNodeRSA} from './parsers.js'; +import {parseBalance} from './parsers.js'; import {callGetter} from './sendRequest.js'; +import {encryptWithPublicKey, parseWebCryptoRSA} from "./webCryptoRSA.js"; import type {u8} from "@polkadot/types-codec"; +import BN from "bn.js"; const unwrapWorkerResponse = (self: IWorker, data: string) => { /// Defaults to return `[]`, which is fine as `createType(api.registry, , [])` @@ -59,12 +56,12 @@ const parseGetterResponse = (self: IWorker, responseType: string, data: string) parsedData = unwrapWorkerResponse(self, returnValue.value); parsedData = parseI64F64(self.createType('i128', parsedData)); break; - case 'NodeRSA': + case 'CryptoKey': const jsonStr = self.createType('String', returnValue.value); // Todo: For some reason there are 2 non-utf characters, where I don't know where // they come from currently. console.log(`Got shielding key: ${jsonStr.toJSON().substring(2)}`); - parsedData = parseNodeRSA(jsonStr.toJSON().substring(2)); + parsedData = parseWebCryptoRSA(jsonStr.toJSON().substring(2)); break case 'Vault': parsedData = self.createType(responseType, returnValue.value); @@ -91,7 +88,7 @@ export class Worker extends WebSocketAsPromised implements IWorker { #keyring?: Keyring; - #shieldingKey?: NodeRSA + #shieldingKey?: CryptoKey rsCount: number; @@ -117,11 +114,19 @@ export class Worker extends WebSocketAsPromised implements IWorker { } } - public encrypt(data: Uint8Array): Vec { - const buffer = u8aToBuffer(data); - const cypherTextBuffer = this.shieldingKey().encrypt(buffer); - const cypherArray = bufferToU8a(cypherTextBuffer); - return this.createType('Vec', compactAddLength(cypherArray)) + public async encrypt(data: Uint8Array): Promise> { + const dataBE = new BN(data); + const dataArrayBE = new Uint8Array(dataBE.toArray()); + + const cypherTextBuffer = await encryptWithPublicKey(dataArrayBE, this.shieldingKey() as CryptoKey); + + const outputData = new Uint8Array(cypherTextBuffer); + const be = new BN(outputData) + const beArray = new Uint8Array(be.toArray()); + + // console.log(`${JSON.stringify({encrypted_array: beArray})}`) + + return this.createType('Vec', compactAddLength(beArray)) } public registry(): TypeRegistry { @@ -140,16 +145,16 @@ export class Worker extends WebSocketAsPromised implements IWorker { this.#keyring = keyring; } - public shieldingKey(): NodeRSA | undefined { + public shieldingKey(): CryptoKey | undefined { return this.#shieldingKey; } - public setShieldingKey(shieldingKey: NodeRSA): void { + public setShieldingKey(shieldingKey: CryptoKey): void { this.#shieldingKey = shieldingKey; } - public async getShieldingKey(options: CallOptions = {} as CallOptions): Promise { - const key = await callGetter(this, [Request.Worker, 'author_getShieldingKey', 'NodeRSA'], {}, options) + public async getShieldingKey(options: CallOptions = {} as CallOptions): Promise { + const key = await callGetter(this, [Request.Worker, 'author_getShieldingKey', 'CryptoKey'], {}, options) this.setShieldingKey(key); return key; } diff --git a/yarn.lock b/yarn.lock index 9687dbac..74536f46 100644 --- a/yarn.lock +++ b/yarn.lock @@ -755,18 +755,18 @@ __metadata: languageName: node linkType: hard -"@encointer/node-api@^0.12.4, @encointer/node-api@workspace:packages/node-api": +"@encointer/node-api@^0.12.5-alpha.9, @encointer/node-api@workspace:packages/node-api": version: 0.0.0-use.local resolution: "@encointer/node-api@workspace:packages/node-api" dependencies: - "@encointer/types": ^0.12.4 + "@encointer/types": ^0.12.5-alpha.9 "@polkadot/api": ^10.9.1 "@polkadot/util-crypto": ^12.3.2 tslib: ^2.5.3 languageName: unknown linkType: soft -"@encointer/types@^0.12.4, @encointer/types@workspace:packages/types": +"@encointer/types@^0.12.5-alpha.9, @encointer/types@workspace:packages/types": version: 0.0.0-use.local resolution: "@encointer/types@workspace:packages/types" dependencies: @@ -781,7 +781,7 @@ __metadata: languageName: unknown linkType: soft -"@encointer/util@^0.12.4, @encointer/util@workspace:packages/util": +"@encointer/util@^0.12.5-alpha.9, @encointer/util@workspace:packages/util": version: 0.0.0-use.local resolution: "@encointer/util@workspace:packages/util" dependencies: @@ -798,10 +798,10 @@ __metadata: version: 0.0.0-use.local resolution: "@encointer/worker-api@workspace:packages/worker-api" dependencies: - "@encointer/node-api": ^0.12.4 - "@encointer/types": ^0.12.4 - "@encointer/util": ^0.12.4 - "@learntheropes/node-rsa": ^1.1.3 + "@encointer/node-api": ^0.12.5-alpha.9 + "@encointer/types": ^0.12.5-alpha.9 + "@encointer/util": ^0.12.5-alpha.9 + "@peculiar/webcrypto": ^1.4.6 "@polkadot/api": ^10.9.1 "@polkadot/keyring": ^12.3.2 "@polkadot/types": ^10.9.1 @@ -1277,16 +1277,6 @@ __metadata: languageName: node linkType: hard -"@learntheropes/node-rsa@npm:^1.1.3": - version: 1.1.3 - resolution: "@learntheropes/node-rsa@npm:1.1.3" - dependencies: - asn1: ^0.2.4 - buffer: ^6.0.3 - checksum: d35d8efe2ade9b5502b541e3c5b13c5959b400b1213c49bc926c6c6fb5147d7f89bcb58b5f539214f5e065d16071ec90bca6513fb7fb61d4e0ad39fff4cc8c49 - languageName: node - linkType: hard - "@leichtgewicht/ip-codec@npm:^2.0.1": version: 2.0.4 resolution: "@leichtgewicht/ip-codec@npm:2.0.4" @@ -2560,6 +2550,39 @@ __metadata: languageName: node linkType: hard +"@peculiar/asn1-schema@npm:^2.3.8": + version: 2.3.8 + resolution: "@peculiar/asn1-schema@npm:2.3.8" + dependencies: + asn1js: ^3.0.5 + pvtsutils: ^1.3.5 + tslib: ^2.6.2 + checksum: 1f4dd421f1411df8bc52bca12b1cef710434c13ff0a8b5746ede42b10d62b5ad06a3925c4a6db53102aaf1e589947539a6955fa8554a9b8ebb1ffa38b0155a24 + languageName: node + linkType: hard + +"@peculiar/json-schema@npm:^1.1.12": + version: 1.1.12 + resolution: "@peculiar/json-schema@npm:1.1.12" + dependencies: + tslib: ^2.0.0 + checksum: b26ececdc23c5ef25837f8be8d1eb5e1c8bb6e9ae7227ac59ffea57fff56bd05137734e7685e9100595d3d88d906dff638ef8d1df54264c388d3eac1b05aa060 + languageName: node + linkType: hard + +"@peculiar/webcrypto@npm:^1.4.6": + version: 1.4.6 + resolution: "@peculiar/webcrypto@npm:1.4.6" + dependencies: + "@peculiar/asn1-schema": ^2.3.8 + "@peculiar/json-schema": ^1.1.12 + pvtsutils: ^1.3.5 + tslib: ^2.6.2 + webcrypto-core: ^1.7.9 + checksum: 27201a9b8abf95ec70db151dc62548736e87fbacc5e534e972b1187d328826a13fd5fb1b02994dc46ab819667e5020e01893d6d143b937e6dbb99e81b3b87c90 + languageName: node + linkType: hard + "@pkgr/utils@npm:^2.3.1": version: 2.4.1 resolution: "@pkgr/utils@npm:2.4.1" @@ -4580,12 +4603,14 @@ __metadata: languageName: node linkType: hard -"asn1@npm:^0.2.4": - version: 0.2.4 - resolution: "asn1@npm:0.2.4" +"asn1js@npm:^3.0.1, asn1js@npm:^3.0.5": + version: 3.0.5 + resolution: "asn1js@npm:3.0.5" dependencies: - safer-buffer: ~2.1.0 - checksum: aa5d6f77b1e0597df53824c68cfe82d1d89ce41cb3520148611f025fbb3101b2d25dd6a40ad34e4fac10f6b19ed5e8628cd4b7d212261e80e83f02b39ee5663c + pvtsutils: ^1.3.2 + pvutils: ^1.1.3 + tslib: ^2.4.0 + checksum: 3b6af1bbadd5762ef8ead5daf2f6bda1bc9e23bc825c4dcc996aa1f9521ad7390a64028565d95d98090d69c8431f004c71cccb866004759169d7c203cf9075eb languageName: node linkType: hard @@ -4976,16 +5001,6 @@ __metadata: languageName: node linkType: hard -"buffer@npm:^6.0.3": - version: 6.0.3 - resolution: "buffer@npm:6.0.3" - dependencies: - base64-js: ^1.3.1 - ieee754: ^1.2.1 - checksum: 5ad23293d9a731e4318e420025800b42bf0d264004c0286c8cc010af7a270c7a0f6522e84f54b9ad65cbd6db20b8badbfd8d2ebf4f80fa03dab093b89e68c3f9 - languageName: node - linkType: hard - "bufferutil@npm:^4.0.1": version: 4.0.5 resolution: "bufferutil@npm:4.0.5" @@ -8731,7 +8746,7 @@ __metadata: languageName: node linkType: hard -"ieee754@npm:^1.1.13, ieee754@npm:^1.2.1": +"ieee754@npm:^1.1.13": version: 1.2.1 resolution: "ieee754@npm:1.2.1" checksum: 5144c0c9815e54ada181d80a0b810221a253562422e7c6c3a60b1901154184f49326ec239d618c416c1c5945a2e197107aee8d986a3dd836b53dffefd99b5e7e @@ -12686,6 +12701,22 @@ __metadata: languageName: node linkType: hard +"pvtsutils@npm:^1.3.2, pvtsutils@npm:^1.3.5": + version: 1.3.5 + resolution: "pvtsutils@npm:1.3.5" + dependencies: + tslib: ^2.6.1 + checksum: e734516b3cb26086c18bd9c012fefe818928a5073178842ab7e62885a090f1dd7bda9c7bb8cd317167502cb8ec86c0b1b0ccd71dac7ab469382a4518157b0d12 + languageName: node + linkType: hard + +"pvutils@npm:^1.1.3": + version: 1.1.3 + resolution: "pvutils@npm:1.1.3" + checksum: 2ee26a9e5176c348977d6ec00d8ee80bff62f51743b1c5fe8abeeb4c5d29d9959cdfe0ce146707a9e6801bce88190fed3002d720b072dc87d031c692820b44c9 + languageName: node + linkType: hard + "q@npm:^1.5.1": version: 1.5.1 resolution: "q@npm:1.5.1" @@ -13337,7 +13368,7 @@ __metadata: languageName: node linkType: hard -"safer-buffer@npm:>= 2.1.2 < 3, safer-buffer@npm:>= 2.1.2 < 3.0.0, safer-buffer@npm:~2.1.0": +"safer-buffer@npm:>= 2.1.2 < 3, safer-buffer@npm:>= 2.1.2 < 3.0.0": version: 2.1.2 resolution: "safer-buffer@npm:2.1.2" checksum: cab8f25ae6f1434abee8d80023d7e72b598cf1327164ddab31003c51215526801e40b66c5e65d658a0af1e9d6478cadcb4c745f4bd6751f97d8644786c0978b0 @@ -14606,6 +14637,13 @@ __metadata: languageName: node linkType: hard +"tslib@npm:^2.0.0, tslib@npm:^2.4.0, tslib@npm:^2.6.1, tslib@npm:^2.6.2": + version: 2.6.2 + resolution: "tslib@npm:2.6.2" + checksum: 329ea56123005922f39642318e3d1f0f8265d1e7fcb92c633e0809521da75eeaca28d2cf96d7248229deb40e5c19adf408259f4b9640afd20d13aecc1430f3ad + languageName: node + linkType: hard + "tslib@npm:^2.1.0": version: 2.3.1 resolution: "tslib@npm:2.3.1" @@ -15137,6 +15175,19 @@ __metadata: languageName: node linkType: hard +"webcrypto-core@npm:^1.7.9": + version: 1.7.9 + resolution: "webcrypto-core@npm:1.7.9" + dependencies: + "@peculiar/asn1-schema": ^2.3.8 + "@peculiar/json-schema": ^1.1.12 + asn1js: ^3.0.1 + pvtsutils: ^1.3.5 + tslib: ^2.6.2 + checksum: 05aa125516bcd91372873c42b9121edd19c8de82f81db2acfba1168745fd4d06ad7d8001b706e4b92063da8a6f52f4e24fb29e7259cba72c0e70a126c22f4199 + languageName: node + linkType: hard + "webidl-conversions@npm:^3.0.0": version: 3.0.1 resolution: "webidl-conversions@npm:3.0.1"