Compare commits

..
22 Commits
Author SHA1 Message Date
github-actions[bot] 27bef46818 [CI Skip] release/stable 4.5.1
skip-checks: true
2021-12-03 11:48:36 +00:00
Jaco 2b4ed56dcb 4.5.1 (#245)
* 4.5.1

* Bump deps
2021-12-03 13:43:15 +02:00
github-actions[bot] e167eba7d8 [CI Skip] release/beta 4.4.2-9
skip-checks: true
2021-12-03 09:54:40 +00:00
Jaco 272050938f Local variable cleanups (#244)
* Local variable cleanups

* Fixup

* Revert res moves
2021-12-03 11:49:41 +02:00
github-actions[bot] 3ee381512b [CI Skip] release/beta 4.4.2-8
skip-checks: true
2021-12-03 07:11:06 +00:00
Jaco a2d5affb88 Adjust formatting (#243)
* Adjust formatting

* Remove all unwrap

* Err(_) => _
2021-12-03 09:05:43 +02:00
github-actions[bot] 2b759aab12 [CI Skip] release/beta 4.4.2-7
skip-checks: true
2021-12-03 04:54:44 +00:00
Jaco 223d7bf514 publicKey from slice in secp256k1 compress/expand (#242) 2021-12-03 06:48:02 +02:00
github-actions[bot] fa2eb4e214 [CI Skip] release/beta 4.4.2-6
skip-checks: true
2021-12-02 12:24:51 +00:00
Jaco 7689afb616 Add secp256k1 interfaces (#241)
* Add secp256k1 functions

* features for rand

* JS tests

* signing

* CHANGELOG

* Add secp256k1 seed
2021-12-02 14:19:33 +02:00
github-actions[bot] 10002e9ec5 [CI Skip] release/beta 4.4.2-5
skip-checks: true
2021-12-01 08:12:11 +00:00
Jaco b2a0af0df4 Adjust stale cron (#240) 2021-12-01 10:07:03 +02:00
github-actions[bot] 4966fd2837 [CI Skip] release/beta 4.4.2-4
skip-checks: true
2021-11-30 11:24:34 +00:00
Jaco 421d36d159 Simplify base64 bytes decoding (#239) 2021-11-30 13:19:24 +02:00
github-actions[bot] 74270adba7 [CI Skip] release/beta 4.4.2-3
skip-checks: true
2021-11-30 09:23:58 +00:00
Jaco 2b97759fa7 WASM function JS interface construction (#238) 2021-11-30 11:17:08 +02:00
github-actions[bot] b8b9784763 [CI Skip] release/beta 4.4.2-2
skip-checks: true
2021-11-28 07:17:05 +00:00
Jaco 8439d5c668 Bump common (#237) 2021-11-28 09:12:15 +02:00
Github Actions cb3a0f667a [CI Skip] release/beta 4.4.2-1
skip-checks: true
2021-11-24 14:57:49 +00:00
Jaco adf21a5fc2 Adjust stale schedule (#236) 2021-11-24 16:52:47 +02:00
Github Actions 4c28fadc07 [CI Skip] release/beta 4.4.2-0
skip-checks: true
2021-11-22 06:27:27 +00:00
Jaco 2849a05507 Bump dev & common (#235) 2021-11-22 08:22:24 +02:00
29 changed files with 1389 additions and 1083 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ name: 'Lock Threads'
on:
schedule:
- cron: '30 1/2 * * *'
- cron: '20 1/3 * * *'
jobs:
lock:
+1 -1
View File
@@ -1,7 +1,7 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '30 2/2 * * *'
- cron: '35 1/3 * * *'
jobs:
stale:
+10
View File
@@ -1,5 +1,15 @@
# CHANGELOG
## 4.5.1 Dec 3, 2021
Changes:
- Add `secp256k1{Compress, Expand, Recover, Sign}` functions
- Remove all occurences of `.unwrap()` (match everywhere)
- Adjust and optimize WASM function JS interface construction
- Simplify base64 bytes decoding on construction
## 4.4.1 Nov 22, 2021
Changes:
+2 -2
View File
@@ -10,7 +10,7 @@
"url": "https://github.com/polkadot-js/wasm.git"
},
"sideEffects": false,
"version": "4.4.1",
"version": "4.5.1",
"workspaces": [
"packages/*"
],
@@ -30,7 +30,7 @@
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@polkadot/dev": "^0.63.29",
"@polkadot/dev": "^0.63.35",
"fflate": "^0.7.1",
"override-require": "^1.1.1"
},
+1 -1
View File
@@ -17,7 +17,7 @@
},
"sideEffects": false,
"type": "module",
"version": "4.4.1",
"version": "4.5.1",
"browser": "empty.js",
"main": "empty.js",
"react-native": "data.js",
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/wasm-crypto-asmjs', version: '4.4.1' };
export const packageInfo = { name: '@polkadot/wasm-crypto-asmjs', version: '4.5.1' };
+1 -1
View File
@@ -17,7 +17,7 @@
},
"sideEffects": false,
"type": "module",
"version": "4.4.1",
"version": "4.5.1",
"browser": "data.js",
"main": "data.js",
"react-native": "data.js",
+13 -77
View File
@@ -1,86 +1,22 @@
// Copyright 2019-2021 @polkadot/wasm-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
// MIT License
//
// Copyright (c) 2014 Jameson Little
//
// https://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js
// This only contains the toByteArray function (no encoding)
//
// Only tweaks make here are some TS adjustments (we use strict null checks), the code is otherwise as-is with
// only the single required function provided
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const CODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
export function base64Decode (data: string): Uint8Array {
const bytes = [];
let byte = 0;
let bits = 0;
const lookup: string[] = [];
const revLookup: number[] = [];
for (let i = 0; i < data.length && data[i] !== '='; i++) {
// each character represents 6 bits
byte = (byte << 6) | chars.indexOf(data[i]);
for (let i = 0; i < CODE.length; ++i) {
lookup[i] = CODE[i];
revLookup[CODE.charCodeAt(i)] = i;
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
function getLens (b64: string): [number, number] {
const len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4');
// each byte needs to contain 8 bits
if ((bits += 6) >= 8) {
bytes.push((byte >>> (bits -= 8)) & 0xff);
}
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
const validLen = b64.indexOf('=');
return validLen === -1
? [len, 0]
: [validLen, 4 - (validLen % 4)];
}
export function toByteArray (b64: string): Uint8Array {
const [validLen, placeHoldersLen] = getLens(b64);
const arr = new Uint8Array(((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen);
let curByte = 0;
let i: number;
let tmp: number;
// if there are placeholders, only get up to the last complete 4 chars
const len = placeHoldersLen > 0
? validLen - 4
: validLen;
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = (tmp >> 16) & 0xFF;
arr[curByte++] = (tmp >> 8) & 0xFF;
arr[curByte++] = tmp & 0xFF;
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4);
arr[curByte++] = tmp & 0xFF;
} else if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2);
arr[curByte++] = (tmp >> 8) & 0xFF;
arr[curByte++] = tmp & 0xFF;
}
return arr;
return Uint8Array.from(bytes);
}
+2 -2
View File
@@ -1,8 +1,8 @@
// Copyright 2019-2021 @polkadot/wasm-crypto-wasm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { toByteArray } from './base64';
import { base64Decode } from './base64';
import { bytes, sizeUncompressed } from './bytes';
import { unzlibSync } from './fflate';
export const wasmBytes = unzlibSync(toByteArray(bytes), new Uint8Array(sizeUncompressed));
export const wasmBytes = unzlibSync(base64Decode(bytes), new Uint8Array(sizeUncompressed));
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/wasm-crypto-wasm', version: '4.4.1' };
export const packageInfo = { name: '@polkadot/wasm-crypto-wasm', version: '4.5.1' };
+270 -42
View File
@@ -45,13 +45,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46254cf2fdcdf1badb5934448c1bcbe046a56537b3987d96c51a7afc5d03f293"
dependencies = [
"addr2line",
"cfg-if",
"cfg-if 0.1.10",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
]
[[package]]
name = "base64"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bitflags"
version = "1.2.1"
@@ -77,7 +83,16 @@ dependencies = [
"block-padding",
"byte-tools",
"byteorder",
"generic-array",
"generic-array 0.12.3",
]
[[package]]
name = "block-buffer"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
dependencies = [
"generic-array 0.14.4",
]
[[package]]
@@ -113,6 +128,12 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cloudabi"
version = "0.0.3"
@@ -128,6 +149,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "cpufeatures"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95059428f66df56b63431fdb4e1947ed2190586af5c5a8a8b71122bdf5a7f469"
dependencies = [
"libc",
]
[[package]]
name = "crunchy"
version = "0.2.2"
@@ -140,10 +170,20 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5"
dependencies = [
"generic-array",
"generic-array 0.12.3",
"subtle 1.0.0",
]
[[package]]
name = "crypto-mac"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab"
dependencies = [
"generic-array 0.14.4",
"subtle 2.2.3",
]
[[package]]
name = "curve25519-dalek"
version = "2.1.0"
@@ -151,8 +191,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d85653f070353a16313d0046f173f70d1aadd5b42600a14de626f0dfb3473a5"
dependencies = [
"byteorder",
"digest",
"rand_core",
"digest 0.8.1",
"rand_core 0.5.1",
"subtle 2.2.3",
"zeroize",
]
@@ -163,7 +203,16 @@ version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5"
dependencies = [
"generic-array",
"generic-array 0.12.3",
]
[[package]]
name = "digest"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
dependencies = [
"generic-array 0.14.4",
]
[[package]]
@@ -183,9 +232,9 @@ checksum = "21a8a37f4e8b35af971e6db5e3897e7a6344caa3f92f6544f88125a1f5f0035a"
dependencies = [
"curve25519-dalek",
"ed25519",
"rand",
"rand 0.7.3",
"serde",
"sha2",
"sha2 0.8.2",
"zeroize",
]
@@ -226,15 +275,38 @@ dependencies = [
"typenum",
]
[[package]]
name = "generic-array"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb"
dependencies = [
"cfg-if",
"cfg-if 0.1.10",
"libc",
"wasi",
"wasi 0.9.0+wasi-snapshot-preview1",
"wasm-bindgen",
]
[[package]]
name = "getrandom"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"
dependencies = [
"cfg-if 1.0.0",
"js-sys",
"libc",
"wasi 0.10.2+wasi-snapshot-preview1",
"wasm-bindgen",
]
@@ -269,8 +341,38 @@ version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5dcb5e64cda4c23119ab41ba960d1e170a774c8e4b9d9e6a9bc18aabf5e59695"
dependencies = [
"crypto-mac",
"digest",
"crypto-mac 0.7.0",
"digest 0.8.1",
]
[[package]]
name = "hmac"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "126888268dcc288495a26bf004b38c5fdbb31682f992c84ceb046a1f0fe38840"
dependencies = [
"crypto-mac 0.8.0",
"digest 0.9.0",
]
[[package]]
name = "hmac-drbg"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17ea0a1394df5b6574da6e0c1ade9e78868c9fb0a4e5ef4428e32da4676b85b1"
dependencies = [
"digest 0.9.0",
"generic-array 0.14.4",
"hmac 0.8.1",
]
[[package]]
name = "js-sys"
version = "0.3.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52732a3d3ad72c58ad2dc70624f9c17b46ecd0943b9a4f1ee37c4c18c5d983e2"
dependencies = [
"wasm-bindgen",
]
[[package]]
@@ -287,9 +389,58 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.74"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2f02823cf78b754822df5f7f268fb59822e7296276d3e069d8e8cb26a14bd10"
checksum = "8521a1b57e76b1ec69af7599e75e38e7b7fad6610f037db8c79b127201b5d119"
[[package]]
name = "libsecp256k1"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0452aac8bab02242429380e9b2f94ea20cea2b37e2c1777a1358799bbe97f37"
dependencies = [
"arrayref",
"base64",
"digest 0.9.0",
"hmac-drbg",
"lazy_static",
"libsecp256k1-core",
"libsecp256k1-gen-ecmult",
"libsecp256k1-gen-genmult",
"rand 0.8.4",
"serde",
"sha2 0.9.8",
"typenum",
]
[[package]]
name = "libsecp256k1-core"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451"
dependencies = [
"crunchy",
"digest 0.9.0",
"subtle 2.2.3",
]
[[package]]
name = "libsecp256k1-gen-ecmult"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809"
dependencies = [
"libsecp256k1-core",
]
[[package]]
name = "libsecp256k1-gen-genmult"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c"
dependencies = [
"libsecp256k1-core",
]
[[package]]
name = "lock_api"
@@ -306,7 +457,7 @@ version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b"
dependencies = [
"cfg-if",
"cfg-if 0.1.10",
]
[[package]]
@@ -323,7 +474,7 @@ checksum = "c6feca46f4fa3443a01769d768727f10c10a20fdb65e52dc16a81f0c8269bb78"
dependencies = [
"byteorder",
"keccak",
"rand_core",
"rand_core 0.5.1",
"zeroize",
]
@@ -363,6 +514,12 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c"
[[package]]
name = "opaque-debug"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "parking_lot"
version = "0.10.2"
@@ -379,7 +536,7 @@ version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"
dependencies = [
"cfg-if",
"cfg-if 0.1.10",
"cloudabi",
"libc",
"redox_syscall",
@@ -394,7 +551,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9"
dependencies = [
"byteorder",
"crypto-mac",
"crypto-mac 0.7.0",
]
[[package]]
@@ -433,13 +590,24 @@ version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom",
"getrandom 0.1.14",
"libc",
"rand_chacha",
"rand_core",
"rand_chacha 0.2.2",
"rand_core 0.5.1",
"rand_hc",
]
[[package]]
name = "rand"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8"
dependencies = [
"libc",
"rand_chacha 0.3.1",
"rand_core 0.6.3",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
@@ -447,7 +615,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.5.1",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core 0.6.3",
]
[[package]]
@@ -456,7 +634,16 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom",
"getrandom 0.1.14",
]
[[package]]
name = "rand_core"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
dependencies = [
"getrandom 0.2.3",
]
[[package]]
@@ -465,7 +652,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
dependencies = [
"rand_core",
"rand_core 0.5.1",
]
[[package]]
@@ -495,11 +682,11 @@ dependencies = [
"arrayref",
"arrayvec 0.5.1",
"curve25519-dalek",
"getrandom",
"getrandom 0.1.14",
"merlin",
"rand",
"rand_core",
"sha2",
"rand 0.7.3",
"rand_core 0.5.1",
"sha2 0.8.2",
"subtle 2.2.3",
"zeroize",
]
@@ -518,9 +705,9 @@ checksum = "656c79d0e90d0ab28ac86bf3c3d10bfbbac91450d3f190113b4e76d9fec3cfdd"
dependencies = [
"byte-tools",
"byteorder",
"hmac",
"hmac 0.7.1",
"pbkdf2",
"sha2",
"sha2 0.8.2",
]
[[package]]
@@ -528,6 +715,20 @@ name = "serde"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5317f7588f0a5078ee60ef675ef96735a1442132dc645eb1d12c018620ed8cd3"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0be94b04690fbaed37cddffc5c134bf537c8e3329d53e982fe04c374978f8e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "sha2"
@@ -535,10 +736,23 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69"
dependencies = [
"block-buffer",
"digest",
"block-buffer 0.7.3",
"digest 0.8.1",
"fake-simd",
"opaque-debug",
"opaque-debug 0.2.3",
]
[[package]]
name = "sha2"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b69f9a4c9740d74c5baa3fd2e547f9525fa8088a8a958e0ca2409a514e33f5fa"
dependencies = [
"block-buffer 0.9.0",
"cfg-if 1.0.0",
"cpufeatures",
"digest 0.9.0",
"opaque-debug 0.3.0",
]
[[package]]
@@ -595,12 +809,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0165e045cc2ae1660270ca65e1676dbaab60feb0f91b10f7d0665e9b47e31f2"
dependencies = [
"failure",
"hmac",
"hmac 0.7.1",
"once_cell",
"pbkdf2",
"rand",
"rand 0.7.3",
"rustc-hash",
"sha2",
"sha2 0.8.2",
"unicode-normalization",
]
@@ -625,7 +839,7 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bfd5b7557925ce778ff9b9ef90e3ade34c524b5ff10e239c69a42d546d2af56"
dependencies = [
"rand",
"rand 0.7.3",
]
[[package]]
@@ -649,12 +863,24 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "version_check"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "wasi"
version = "0.10.2+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
[[package]]
name = "wasm"
version = "0.0.0"
@@ -663,14 +889,16 @@ dependencies = [
"byteorder",
"curve25519-dalek",
"ed25519-dalek",
"getrandom 0.2.3",
"hex-literal",
"hmac",
"hmac 0.7.1",
"libsecp256k1",
"merlin",
"pbkdf2",
"rand",
"rand 0.7.3",
"schnorrkel",
"scrypt",
"sha2",
"sha2 0.8.2",
"tiny-bip39",
"tiny-keccak",
"twox-hash",
@@ -684,7 +912,7 @@ version = "0.2.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3edbcc9536ab7eababcc6d2374a0b7bfe13a2b6d562c5e07f370456b1a8f33d"
dependencies = [
"cfg-if",
"cfg-if 0.1.10",
"wasm-bindgen-macro",
]
@@ -738,7 +966,7 @@ version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e"
dependencies = [
"cfg-if",
"cfg-if 0.1.10",
"libc",
"memory_units",
"winapi",
+5 -2
View File
@@ -9,6 +9,7 @@ license = "Apache-2.0"
name = "wasm"
publish = false
repository = "https://github.com/polkadot-js/wasm/"
resolver = "2"
version = "0.0.0"
[lib]
@@ -17,12 +18,14 @@ crate-type = ["cdylib"]
[dependencies]
blake2-rfc = "0.2.18"
byteorder = "1.3.1"
curve25519-dalek = { version = "2.1.0", default-features = false }
ed25519-dalek = { version = "1.0.0-pre.4", features = [] }
getrandom = { version="0.2.3", features = ["js"] }
hmac = "0.7.0"
# libsecp256k1 = "0.2.2"
libsecp256k1 = { version = "0.7.0", default-features = false, features=["hmac", "lazy-static-context"] }
merlin = { version = "2.0", default-features = false }
pbkdf2 = { version = "0.3.0", default-features = false }
curve25519-dalek = { version = "2.1.0", default-features = false }
rand = { version="0.7.3", default-features = false, features = ["wasm-bindgen"] }
schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated", "u64_backend"] }
scrypt = { version = "0.2", default-features = false }
sha2 = "0.8.1"
+5 -5
View File
@@ -20,16 +20,16 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "4.4.1",
"version": "4.5.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.3",
"@polkadot/wasm-crypto-asmjs": "^4.4.1",
"@polkadot/wasm-crypto-wasm": "^4.4.1"
"@polkadot/wasm-crypto-asmjs": "^4.5.1",
"@polkadot/wasm-crypto-wasm": "^4.5.1"
},
"devDependencies": {
"@polkadot/util": "^7.9.1",
"@polkadot/x-randomvalues": "^7.9.1"
"@polkadot/util": "^8.0.5",
"@polkadot/x-randomvalues": "^8.0.5"
},
"peerDependencies": {
"@polkadot/util": "*",
+9 -6
View File
@@ -7,6 +7,11 @@ import type { AsmCreator, WasmCryptoInstance } from './types';
import { assert, stringToU8a, u8aToString } from '@polkadot/util';
type PopFirst<T extends unknown[]> =
T extends [WasmCryptoInstance, ...infer N]
? N
: [];
let wasm: WasmCryptoInstance | null = null;
let cachegetInt32: Int32Array | null = null;
let cachegetUint8: Uint8Array | null = null;
@@ -31,14 +36,12 @@ export async function initWasm (wasmBytes: Uint8Array | null, asmFn: AsmCreator
}
}
// FIXME We really would love to clean this up and have a sign like (wasm, ...params) => T
// Alas, TypeScript foo is not that great today, so we sadly have an extra closure here
export function withWasm <T, F extends (...params: never[]) => T> (fn: (wasm: WasmCryptoInstance) => F): F {
return ((...params: never[]): T => {
export function withWasm <T, F extends (wasm: WasmCryptoInstance, ...params: never[]) => T> (fn: F): (...params: PopFirst<Parameters<F>>) => ReturnType<F> {
return (...params: PopFirst<Parameters<F>>): ReturnType<F> => {
assert(wasm, 'The WASM interface has not been initialized. Ensure that you wait for the initialization Promise with waitReady() from @polkadot/wasm-crypto (or cryptoWaitReady() from @polkadot/util-crypto) before attempting to use WASM-only interfaces.');
return fn(wasm)(...params);
}) as unknown as F;
return fn(wasm, ...params) as ReturnType<F>;
};
}
export function getWasm (): WasmCryptoInstance {
+128 -228
View File
@@ -9,299 +9,199 @@ import * as imports from './imports';
export { packageInfo } from './packageInfo';
const PTR_VEC = 8;
const wasmPromise = initWasm(wasmBytes, asmJsInit, imports).catch(() => null);
export const bip39Generate = withWasm((wasm) =>
(words: 12 | 15 | 18 | 21 | 24): string => {
wasm.ext_bip39_generate(PTR_VEC, words);
export const bip39Generate = withWasm((wasm, words: 12 | 15 | 18 | 21 | 24): string => {
wasm.ext_bip39_generate(8, words);
return resultString();
}
);
return resultString();
});
export const bip39ToEntropy = withWasm((wasm) =>
(phrase: string): Uint8Array => {
const [ptr0, len0] = allocString(phrase);
export const bip39ToEntropy = withWasm((wasm, phrase: string): Uint8Array => {
wasm.ext_bip39_to_entropy(8, ...allocString(phrase));
wasm.ext_bip39_to_entropy(PTR_VEC, ptr0, len0);
return resultU8a();
});
return resultU8a();
}
);
export const bip39ToMiniSecret = withWasm((wasm, phrase: string, password: string): Uint8Array => {
wasm.ext_bip39_to_mini_secret(8, ...allocString(phrase), ...allocString(password));
export const bip39ToMiniSecret = withWasm((wasm) =>
(phrase: string, password: string): Uint8Array => {
const [ptr0, len0] = allocString(phrase);
const [ptr1, len1] = allocString(password);
return resultU8a();
});
wasm.ext_bip39_to_mini_secret(PTR_VEC, ptr0, len0, ptr1, len1);
export const bip39ToSeed = withWasm((wasm, phrase: string, password: string): Uint8Array => {
wasm.ext_bip39_to_seed(8, ...allocString(phrase), ...allocString(password));
return resultU8a();
}
);
return resultU8a();
});
export const bip39ToSeed = withWasm((wasm) =>
(phrase: string, password: string): Uint8Array => {
const [ptr0, len0] = allocString(phrase);
const [ptr1, len1] = allocString(password);
export const bip39Validate = withWasm((wasm, phrase: string): boolean => {
const ret = wasm.ext_bip39_validate(...allocString(phrase));
wasm.ext_bip39_to_seed(PTR_VEC, ptr0, len0, ptr1, len1);
return ret !== 0;
});
return resultU8a();
}
);
export const ed25519KeypairFromSeed = withWasm((wasm, seed: Uint8Array): Uint8Array => {
wasm.ext_ed_from_seed(8, ...allocU8a(seed));
export const bip39Validate = withWasm((wasm) =>
(phrase: string): boolean => {
const [ptr0, len0] = allocString(phrase);
const ret = wasm.ext_bip39_validate(ptr0, len0);
return resultU8a();
});
return ret !== 0;
}
);
export const ed25519Sign = withWasm((wasm, pubkey: Uint8Array, seckey: Uint8Array, message: Uint8Array): Uint8Array => {
wasm.ext_ed_sign(8, ...allocU8a(pubkey), ...allocU8a(seckey), ...allocU8a(message));
export const ed25519KeypairFromSeed = withWasm((wasm) =>
(seed: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(seed);
return resultU8a();
});
wasm.ext_ed_from_seed(PTR_VEC, ptr0, len0);
export const ed25519Verify = withWasm((wasm, signature: Uint8Array, message: Uint8Array, pubkey: Uint8Array): boolean => {
const ret = wasm.ext_ed_verify(...allocU8a(signature), ...allocU8a(message), ...allocU8a(pubkey));
return resultU8a();
}
);
return ret !== 0;
});
export const ed25519Sign = withWasm((wasm) =>
(pubkey: Uint8Array, seckey: Uint8Array, message: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pubkey);
const [ptr1, len1] = allocU8a(seckey);
const [ptr2, len2] = allocU8a(message);
export const secp256k1FromSeed = withWasm((wasm, seckey: Uint8Array): Uint8Array => {
wasm.ext_secp_from_seed(8, ...allocU8a(seckey));
wasm.ext_ed_sign(PTR_VEC, ptr0, len0, ptr1, len1, ptr2, len2);
return resultU8a();
});
return resultU8a();
}
);
export const secp256k1Compress = withWasm((wasm, pubkey: Uint8Array): Uint8Array => {
wasm.ext_secp_pub_compress(8, ...allocU8a(pubkey));
export const ed25519Verify = withWasm((wasm) =>
(signature: Uint8Array, message: Uint8Array, pubkey: Uint8Array): boolean => {
const [ptr0, len0] = allocU8a(signature);
const [ptr1, len1] = allocU8a(message);
const [ptr2, len2] = allocU8a(pubkey);
const ret = wasm.ext_ed_verify(ptr0, len0, ptr1, len1, ptr2, len2);
return resultU8a();
});
return ret !== 0;
}
);
export const secp256k1Expand = withWasm((wasm, pubkey: Uint8Array): Uint8Array => {
wasm.ext_secp_pub_expand(8, ...allocU8a(pubkey));
export const sr25519DeriveKeypairHard = withWasm((wasm) =>
(pair: Uint8Array, cc: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pair);
const [ptr1, len1] = allocU8a(cc);
return resultU8a();
});
wasm.ext_sr_derive_keypair_hard(PTR_VEC, ptr0, len0, ptr1, len1);
return resultU8a();
}
);
export const secp256k1Recover = withWasm((wasm, msgHash: Uint8Array, sig: Uint8Array, recovery: number): Uint8Array => {
wasm.ext_secp_recover(8, ...allocU8a(msgHash), ...allocU8a(sig), recovery);
export const sr25519DeriveKeypairSoft = withWasm((wasm) =>
(pair: Uint8Array, cc: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pair);
const [ptr1, len1] = allocU8a(cc);
return resultU8a();
});
wasm.ext_sr_derive_keypair_soft(PTR_VEC, ptr0, len0, ptr1, len1);
return resultU8a();
}
);
export const secp256k1Sign = withWasm((wasm, msgHash: Uint8Array, seckey: Uint8Array): Uint8Array => {
wasm.ext_secp_sign(8, ...allocU8a(msgHash), ...allocU8a(seckey));
export const sr25519DerivePublicSoft = withWasm((wasm) =>
(pubkey: Uint8Array, cc: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pubkey);
const [ptr1, len1] = allocU8a(cc);
return resultU8a();
});
wasm.ext_sr_derive_public_soft(PTR_VEC, ptr0, len0, ptr1, len1);
export const sr25519DeriveKeypairHard = withWasm((wasm, pair: Uint8Array, cc: Uint8Array): Uint8Array => {
wasm.ext_sr_derive_keypair_hard(8, ...allocU8a(pair), ...allocU8a(cc));
return resultU8a();
}
);
return resultU8a();
});
export const sr25519KeypairFromSeed = withWasm((wasm) =>
(seed: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(seed);
export const sr25519DeriveKeypairSoft = withWasm((wasm, pair: Uint8Array, cc: Uint8Array): Uint8Array => {
wasm.ext_sr_derive_keypair_soft(8, ...allocU8a(pair), ...allocU8a(cc));
wasm.ext_sr_from_seed(PTR_VEC, ptr0, len0);
return resultU8a();
});
return resultU8a();
}
);
export const sr25519DerivePublicSoft = withWasm((wasm, pubkey: Uint8Array, cc: Uint8Array): Uint8Array => {
wasm.ext_sr_derive_public_soft(8, ...allocU8a(pubkey), ...allocU8a(cc));
export const sr25519Sign = withWasm((wasm) =>
(pubkey: Uint8Array, secret: Uint8Array, message: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pubkey);
const [ptr1, len1] = allocU8a(secret);
const [ptr2, len2] = allocU8a(message);
return resultU8a();
});
wasm.ext_sr_sign(PTR_VEC, ptr0, len0, ptr1, len1, ptr2, len2);
export const sr25519KeypairFromSeed = withWasm((wasm, seed: Uint8Array): Uint8Array => {
wasm.ext_sr_from_seed(8, ...allocU8a(seed));
return resultU8a();
}
);
return resultU8a();
});
export const sr25519Verify = withWasm((wasm) =>
(signature: Uint8Array, message: Uint8Array, pubkey: Uint8Array): boolean => {
const [ptr0, len0] = allocU8a(signature);
const [ptr1, len1] = allocU8a(message);
const [ptr2, len2] = allocU8a(pubkey);
const ret = wasm.ext_sr_verify(ptr0, len0, ptr1, len1, ptr2, len2);
export const sr25519Sign = withWasm((wasm, pubkey: Uint8Array, secret: Uint8Array, message: Uint8Array): Uint8Array => {
wasm.ext_sr_sign(8, ...allocU8a(pubkey), ...allocU8a(secret), ...allocU8a(message));
return ret !== 0;
}
);
return resultU8a();
});
export const sr25519Agree = withWasm((wasm) =>
(pubkey: Uint8Array, secret: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(pubkey);
const [ptr1, len1] = allocU8a(secret);
export const sr25519Verify = withWasm((wasm, signature: Uint8Array, message: Uint8Array, pubkey: Uint8Array): boolean => {
const ret = wasm.ext_sr_verify(...allocU8a(signature), ...allocU8a(message), ...allocU8a(pubkey));
wasm.ext_sr_agree(PTR_VEC, ptr0, len0, ptr1, len1);
return ret !== 0;
});
return resultU8a();
}
);
export const sr25519Agree = withWasm((wasm, pubkey: Uint8Array, secret: Uint8Array): Uint8Array => {
wasm.ext_sr_agree(8, ...allocU8a(pubkey), ...allocU8a(secret));
export const vrfSign = withWasm((wasm) =>
(secret: Uint8Array, context: Uint8Array, message: Uint8Array, extra: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(secret);
const [ptr1, len1] = allocU8a(context);
const [ptr2, len2] = allocU8a(message);
const [ptr3, len3] = allocU8a(extra);
return resultU8a();
});
wasm.ext_vrf_sign(PTR_VEC, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3);
export const vrfSign = withWasm((wasm, secret: Uint8Array, context: Uint8Array, message: Uint8Array, extra: Uint8Array): Uint8Array => {
wasm.ext_vrf_sign(8, ...allocU8a(secret), ...allocU8a(context), ...allocU8a(message), ...allocU8a(extra));
return resultU8a();
}
);
return resultU8a();
});
export const vrfVerify = withWasm((wasm) =>
(pubkey: Uint8Array, context: Uint8Array, message: Uint8Array, extra: Uint8Array, outAndProof: Uint8Array): boolean => {
const [ptr0, len0] = allocU8a(pubkey);
const [ptr1, len1] = allocU8a(context);
const [ptr2, len2] = allocU8a(message);
const [ptr3, len3] = allocU8a(extra);
const [ptr4, len4] = allocU8a(outAndProof);
const ret = wasm.ext_vrf_verify(ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3, ptr4, len4);
export const vrfVerify = withWasm((wasm, pubkey: Uint8Array, context: Uint8Array, message: Uint8Array, extra: Uint8Array, outAndProof: Uint8Array): boolean => {
const ret = wasm.ext_vrf_verify(...allocU8a(pubkey), ...allocU8a(context), ...allocU8a(message), ...allocU8a(extra), ...allocU8a(outAndProof));
return ret !== 0;
}
);
return ret !== 0;
});
export const blake2b = withWasm((wasm) =>
(data: Uint8Array, key: Uint8Array, size: number): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
const [ptr1, len1] = allocU8a(key);
export const blake2b = withWasm((wasm, data: Uint8Array, key: Uint8Array, size: number): Uint8Array => {
wasm.ext_blake2b(8, ...allocU8a(data), ...allocU8a(key), size);
wasm.ext_blake2b(PTR_VEC, ptr0, len0, ptr1, len1, size);
return resultU8a();
});
return resultU8a();
}
);
export const hmacSha256 = withWasm((wasm, key: Uint8Array, data: Uint8Array): Uint8Array => {
wasm.ext_hmac_sha256(8, ...allocU8a(key), ...allocU8a(data));
export const hmacSha256 = withWasm((wasm) =>
(key: Uint8Array, data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(key);
const [ptr1, len1] = allocU8a(data);
return resultU8a();
});
wasm.ext_hmac_sha256(PTR_VEC, ptr0, len0, ptr1, len1);
export const hmacSha512 = withWasm((wasm, key: Uint8Array, data: Uint8Array): Uint8Array => {
wasm.ext_hmac_sha512(8, ...allocU8a(key), ...allocU8a(data));
return resultU8a();
}
);
return resultU8a();
});
export const hmacSha512 = withWasm((wasm) =>
(key: Uint8Array, data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(key);
const [ptr1, len1] = allocU8a(data);
export const keccak256 = withWasm((wasm, data: Uint8Array): Uint8Array => {
wasm.ext_keccak256(8, ...allocU8a(data));
wasm.ext_hmac_sha512(PTR_VEC, ptr0, len0, ptr1, len1);
return resultU8a();
});
return resultU8a();
}
);
export const keccak512 = withWasm((wasm, data: Uint8Array): Uint8Array => {
wasm.ext_keccak512(8, ...allocU8a(data));
export const keccak256 = withWasm((wasm) =>
(data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
return resultU8a();
});
wasm.ext_keccak256(PTR_VEC, ptr0, len0);
export const pbkdf2 = withWasm((wasm, data: Uint8Array, salt: Uint8Array, rounds: number): Uint8Array => {
wasm.ext_pbkdf2(8, ...allocU8a(data), ...allocU8a(salt), rounds);
return resultU8a();
}
);
return resultU8a();
});
export const keccak512 = withWasm((wasm) =>
(data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
export const scrypt = withWasm((wasm, password: Uint8Array, salt: Uint8Array, log2n: number, r: number, p: number): Uint8Array => {
wasm.ext_scrypt(8, ...allocU8a(password), ...allocU8a(salt), log2n, r, p);
wasm.ext_keccak512(PTR_VEC, ptr0, len0);
return resultU8a();
});
return resultU8a();
}
);
export const sha256 = withWasm((wasm, data: Uint8Array): Uint8Array => {
wasm.ext_sha256(8, ...allocU8a(data));
export const pbkdf2 = withWasm((wasm) =>
(data: Uint8Array, salt: Uint8Array, rounds: number): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
const [ptr1, len1] = allocU8a(salt);
return resultU8a();
});
wasm.ext_pbkdf2(PTR_VEC, ptr0, len0, ptr1, len1, rounds);
export const sha512 = withWasm((wasm, data: Uint8Array): Uint8Array => {
wasm.ext_sha512(8, ...allocU8a(data));
return resultU8a();
}
);
return resultU8a();
});
export const scrypt = withWasm((wasm) =>
(password: Uint8Array, salt: Uint8Array, log2n: number, r: number, p: number): Uint8Array => {
const [ptr0, len0] = allocU8a(password);
const [ptr1, len1] = allocU8a(salt);
export const twox = withWasm((wasm, data: Uint8Array, rounds: number) => {
wasm.ext_twox(8, ...allocU8a(data), rounds);
wasm.ext_scrypt(PTR_VEC, ptr0, len0, ptr1, len1, log2n, r, p);
return resultU8a();
}
);
export const sha256 = withWasm((wasm) =>
(data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
wasm.ext_sha256(PTR_VEC, ptr0, len0);
return resultU8a();
}
);
export const sha512 = withWasm((wasm) =>
(data: Uint8Array): Uint8Array => {
const [ptr0, len0] = allocU8a(data);
wasm.ext_sha512(PTR_VEC, ptr0, len0);
return resultU8a();
}
);
export const twox = withWasm((wasm) =>
(data: Uint8Array, rounds: number) => {
const [ptr0, len0] = allocU8a(data);
wasm.ext_twox(PTR_VEC, ptr0, len0, rounds);
return resultU8a();
}
);
return resultU8a();
});
export function isReady (): boolean {
return !!getWasm();
+4
View File
@@ -51,6 +51,10 @@ export function __wbindgen_is_undefined (idx: number): boolean {
return getObject(idx) === undefined;
}
export function __wbindgen_throw (ptr: number, len: number): boolean {
throw new Error(getString(ptr, len));
}
export function __wbg_self_1b7a39e3a92c949c (): number {
return addObject(DEFAULT_SELF);
}
+3
View File
@@ -14,6 +14,9 @@ pub mod ed25519;
#[path = "rs/hashing.rs"]
pub mod hashing;
#[path = "rs/secp256k1.rs"]
pub mod secp256k1;
#[path = "rs/sr25519.rs"]
pub mod sr25519;
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/wasm-crypto', version: '4.4.1' };
export const packageInfo = { name: '@polkadot/wasm-crypto', version: '4.5.1' };
+37 -24
View File
@@ -14,8 +14,11 @@ use wasm_bindgen::prelude::*;
/// Returns the bip 39 phrase
#[wasm_bindgen]
pub fn ext_bip39_generate(words: u32) -> String {
Mnemonic::new(MnemonicType::for_word_count(words as usize).unwrap(), Language::English)
.into_phrase()
match MnemonicType::for_word_count(words as usize) {
Ok(p) => Mnemonic::new(p, Language::English)
.into_phrase(),
_ => panic!("Invalid count provided.")
}
}
/// Create entropy from a bip39 phrase
@@ -25,10 +28,12 @@ pub fn ext_bip39_generate(words: u32) -> String {
/// Returns the entropy
#[wasm_bindgen]
pub fn ext_bip39_to_entropy(phrase: &str) -> Vec<u8> {
Mnemonic::from_phrase(phrase, Language::English)
.unwrap()
.entropy()
.to_vec()
match Mnemonic::from_phrase(phrase, Language::English) {
Ok(m) => m
.entropy()
.to_vec(),
_ => panic!("Invalid phrase provided.")
}
}
/// Create a mini-secret from a bip39 phrase
@@ -38,13 +43,20 @@ pub fn ext_bip39_to_entropy(phrase: &str) -> Vec<u8> {
/// Returns the 32-byte mini-secret via entropy
#[wasm_bindgen]
pub fn ext_bip39_to_mini_secret(phrase: &str, password: &str) -> Vec<u8> {
let salt = format!("mnemonic{}", password);
let mnemonic = Mnemonic::from_phrase(phrase, Language::English).unwrap();
let mut result = [0u8; 64];
match Mnemonic::from_phrase(phrase, Language::English) {
Ok(m) => {
let mut res = [0u8; 64];
let mut seed = vec![];
pbkdf2::<Hmac<Sha512>>(mnemonic.entropy(), salt.as_bytes(), 2048, &mut result);
seed.extend_from_slice(b"mnemonic");
seed.extend_from_slice(password.as_bytes());
result[..32].to_vec()
pbkdf2::<Hmac<Sha512>>(m.entropy(), &seed, 2048, &mut res);
res[..32].to_vec()
},
_ => panic!("Invalid phrase provided.")
}
}
/// Creates a BTC/ETH compatible seed from a bip-39 phrase
@@ -54,11 +66,12 @@ pub fn ext_bip39_to_mini_secret(phrase: &str, password: &str) -> Vec<u8> {
/// Returns a 32-byte seed
#[wasm_bindgen]
pub fn ext_bip39_to_seed(phrase: &str, password: &str) -> Vec<u8> {
let mnemonic = Mnemonic::from_phrase(phrase, Language::English).unwrap();
Seed::new(&mnemonic, password)
.as_bytes()[..32]
.to_vec()
match Mnemonic::from_phrase(phrase, Language::English) {
Ok(m) => Seed::new(&m, password)
.as_bytes()[..32]
.to_vec(),
_ => panic!("Invalid phrase provided.")
}
}
/// Validates a bip39 phrase
@@ -69,8 +82,8 @@ pub fn ext_bip39_to_seed(phrase: &str, password: &str) -> Vec<u8> {
#[wasm_bindgen]
pub fn ext_bip39_validate(phrase: &str) -> bool {
match Mnemonic::validate(phrase, Language::English) {
Err(_) => false,
_ => true
Ok(_) => true,
_ => false
}
}
@@ -83,9 +96,9 @@ pub mod tests {
fn can_bip39_entropy() {
let phrase = "legal winner thank year wave sausage worth useful legal winner thank yellow";
let entropy = hex!("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f");
let result = ext_bip39_to_entropy(phrase);
let res = ext_bip39_to_entropy(phrase);
assert_eq!(result, entropy);
assert_eq!(res, entropy);
}
#[test]
@@ -93,18 +106,18 @@ pub mod tests {
let phrase = "legal winner thank year wave sausage worth useful legal winner thank yellow";
let password = "Substrate";
let mini = hex!("4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b78041685");
let result = ext_bip39_to_mini_secret(phrase, password);
let res = ext_bip39_to_mini_secret(phrase, password);
assert_eq!(result[..], mini[..]);
assert_eq!(res[..], mini[..]);
}
#[test]
fn can_bip39_seed() {
let phrase = "seed sock milk update focus rotate barely fade car face mechanic mercy";
let seed = hex!("3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027");
let result = ext_bip39_to_seed(phrase, "");
let res = ext_bip39_to_seed(phrase, "");
assert_eq!(result[..], seed[..]);
assert_eq!(res[..], seed[..]);
}
#[test]
+25 -23
View File
@@ -6,36 +6,40 @@ use ed25519_dalek::{Keypair, PublicKey, SecretKey, Signature, Signer as _, Verif
use wasm_bindgen::prelude::*;
/// Keypair helper function.
fn create_from_pair(pair: &[u8]) -> Keypair {
fn new_from_pair(pair: &[u8]) -> Keypair {
match Keypair::from_bytes(pair) {
Ok(pair) => return pair,
Err(_) => panic!("Provided pair is invalid.")
Ok(p) => p,
_ => panic!("Provided pair is invalid.")
}
}
/// Keypair helper function
fn create_from_parts(pubkey: &[u8], seckey: &[u8]) -> Keypair {
fn new_from_parts(pubkey: &[u8], seckey: &[u8]) -> Keypair {
let mut pair = vec![];
pair.extend_from_slice(seckey);
pair.extend_from_slice(pubkey);
create_from_pair(&pair)
new_from_pair(&pair)
}
/// Keypair helper function.
fn create_from_seed(seed: &[u8]) -> Keypair {
let seckey = SecretKey::from_bytes(seed).unwrap();
let pubkey: PublicKey = (&seckey).into();
fn new_from_seed(seed: &[u8]) -> Keypair {
match &SecretKey::from_bytes(seed) {
Ok(s) => {
let pubkey: PublicKey = s.into();
create_from_parts(pubkey.as_bytes(), seed)
new_from_parts(pubkey.as_bytes(), seed)
},
_ => panic!("Invalid seed provided.")
}
}
/// PublicKey helper
fn create_public(pubkey: &[u8]) -> PublicKey {
fn new_public(pubkey: &[u8]) -> PublicKey {
match PublicKey::from_bytes(pubkey) {
Ok(pubkey) => return pubkey,
Err(_) => panic!("Provided public key is invalid.")
Ok(p) => p,
_ => panic!("Provided public key is invalid.")
}
}
@@ -47,7 +51,7 @@ fn create_public(pubkey: &[u8]) -> PublicKey {
/// followed by the public key (32) bytes.
#[wasm_bindgen]
pub fn ext_ed_from_seed(seed: &[u8]) -> Vec<u8> {
create_from_seed(seed)
new_from_seed(seed)
.to_bytes()
.to_vec()
}
@@ -64,7 +68,7 @@ pub fn ext_ed_from_seed(seed: &[u8]) -> Vec<u8> {
/// * returned vector is the signature consisting of 64 bytes.
#[wasm_bindgen]
pub fn ext_ed_sign(pubkey: &[u8], seckey: &[u8], message: &[u8]) -> Vec<u8> {
create_from_parts(pubkey, seckey)
new_from_parts(pubkey, seckey)
.sign(message)
.to_bytes()
.to_vec()
@@ -77,14 +81,12 @@ pub fn ext_ed_sign(pubkey: &[u8], seckey: &[u8], message: &[u8]) -> Vec<u8> {
/// * pubkey: UIntArray with 32 element
#[wasm_bindgen]
pub fn ext_ed_verify(signature: &[u8], message: &[u8], pubkey: &[u8]) -> bool {
let signature = match Signature::try_from(signature) {
Ok(signature) => signature,
Err(_) => return false
};
create_public(pubkey)
.verify(message, &signature)
.is_ok()
match Signature::try_from(signature) {
Ok(s) => new_public(pubkey)
.verify(message, &s)
.is_ok(),
_ => false
}
}
#[cfg(test)]
@@ -100,7 +102,7 @@ pub mod tests {
}
#[test]
fn can_create_keypair() {
fn can_new_keypair() {
let seed = generate_random_seed();
let keypair = ext_ed_from_seed(seed.as_slice());
+37 -41
View File
@@ -11,21 +11,6 @@ use tiny_keccak::{Hasher, Keccak};
use twox_hash::XxHash;
use wasm_bindgen::prelude::*;
/// helper function for a single twox round with a seed
fn create_twox(data: &[u8], seed: u64) -> [u8; 8] {
use ::std::hash::Hasher;
let mut hasher = XxHash::with_seed(seed);
hasher.write(data);
let hash64 = hasher.finish();
let mut result = [0u8; 8];
LittleEndian::write_u64(&mut result, hash64);
result
}
/// blake2b hash for the specified input
///
/// * data: Arbitrary data to be hashed
@@ -44,16 +29,16 @@ pub fn ext_blake2b(data: &[u8], key: &[u8], size: u32) -> Vec<u8> {
/// hmac with sha256
#[wasm_bindgen]
pub fn ext_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
match Hmac::<Sha256>::new_varkey(key){
Ok(mut mac) => {
mac.input(data);
match Hmac::<Sha256>::new_varkey(key) {
Ok(mut m) => {
m.input(data);
mac
m
.result()
.code()
.to_vec()
},
Err(_) => panic!("Invalid key provided.")
_ => panic!("Invalid key provided.")
}
}
@@ -61,15 +46,15 @@ pub fn ext_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
#[wasm_bindgen]
pub fn ext_hmac_sha512(key: &[u8], data: &[u8]) -> Vec<u8> {
match Hmac::<Sha512>::new_varkey(key) {
Ok(mut mac) => {
mac.input(data);
Ok(mut m) => {
m.input(data);
mac
m
.result()
.code()
.to_vec()
},
Err(_) => panic!("Invalid key provided.")
_ => panic!("Invalid key provided.")
}
}
@@ -82,12 +67,12 @@ pub fn ext_hmac_sha512(key: &[u8], data: &[u8]) -> Vec<u8> {
#[wasm_bindgen]
pub fn ext_keccak256(data: &[u8]) -> Vec<u8> {
let mut keccak = Keccak::v256();
let mut result = [0u8; 32];
let mut res = [0u8; 32];
keccak.update(data);
keccak.finalize(&mut result);
keccak.finalize(&mut res);
result.to_vec()
res.to_vec()
}
/// Create a keccak512 hash for the specified input
@@ -98,12 +83,12 @@ pub fn ext_keccak256(data: &[u8]) -> Vec<u8> {
#[wasm_bindgen]
pub fn ext_keccak512(data: &[u8]) -> Vec<u8> {
let mut keccak = Keccak::v512();
let mut result = [0u8; 64];
let mut res = [0u8; 64];
keccak.update(data);
keccak.finalize(&mut result);
keccak.finalize(&mut res);
result.to_vec()
res.to_vec()
}
/// pbkdf2 kdf from an input, salt for the number of specified rounds
@@ -115,12 +100,12 @@ pub fn ext_keccak512(data: &[u8]) -> Vec<u8> {
/// Returns a vector with the hashed result
#[wasm_bindgen]
pub fn ext_pbkdf2(data: &[u8], salt: &[u8], rounds: u32) -> Vec<u8> {
let mut result = [0u8; 64];
let mut res = [0u8; 64];
// we cast to usize here - due to the WASM, we'd rather have u32 inputs
pbkdf2::<Hmac::<Sha512>>(data, salt, rounds as usize, &mut result);
pbkdf2::<Hmac::<Sha512>>(data, salt, rounds as usize, &mut res);
result.to_vec()
res.to_vec()
}
/// scrypt kdf from input, salt and config
@@ -134,13 +119,18 @@ pub fn ext_pbkdf2(data: &[u8], salt: &[u8], rounds: u32) -> Vec<u8> {
/// Returns vector with the hashed result
#[wasm_bindgen]
pub fn ext_scrypt(password: &[u8], salt: &[u8], log2_n: u8, r: u32, p: u32) -> Vec<u8> {
let params = ScryptParams::new(log2_n, r, p).unwrap();
let mut result = [0u8; 64];
match ScryptParams::new(log2_n, r, p) {
Ok(p) => {
let mut res = [0u8; 64];
match scrypt(password, salt, &params, &mut result) {
Ok(_) => result.to_vec(),
Err(_) => panic!("Invalid scrypt hash.")
match scrypt(password, salt, &p, &mut res) {
Ok(_) => res.to_vec(),
_ => panic!("Invalid scrypt hash.")
}
},
_ => panic!("Invalid scrypt params.")
}
}
/// sha256 hash for the specified input
@@ -183,14 +173,20 @@ pub fn ext_sha512(data: &[u8]) -> Vec<u8> {
/// Returns a vector with the hash result
#[wasm_bindgen]
pub fn ext_twox(data: &[u8], rounds: u32) -> Vec<u8> {
let mut vec = vec![];
use ::std::hash::Hasher;
let mut res = vec![];
let mut buf = [0u8; 8];
for round in 0..rounds {
// we cast to u64 here - due to the WASM, we'd rather have u32 inputs
vec.extend_from_slice(&create_twox(data, round as u64));
let mut hasher = XxHash::with_seed(round as u64);
hasher.write(data);
LittleEndian::write_u64(&mut buf, hasher.finish());
res.extend_from_slice(&buf);
}
vec
res
}
#[cfg(test)]
+126
View File
@@ -0,0 +1,126 @@
// Copyright 2019-2021 @polkadot/wasm-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
use libsecp256k1::{Message, PublicKey, RecoveryId, SecretKey, Signature, recover, sign};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn ext_secp_pub_compress(pubkey: &[u8]) -> Vec<u8> {
match PublicKey::parse_slice(&pubkey, None) {
Ok(p) => p
.serialize_compressed()
.to_vec(),
_ => panic!("Invalid pubkey provided.")
}
}
#[wasm_bindgen]
pub fn ext_secp_pub_expand(pubkey: &[u8]) -> Vec<u8> {
match PublicKey::parse_slice(&pubkey, None) {
Ok(p) => p
.serialize()
.to_vec(),
_ => panic!("Invalid pubkey provided.")
}
}
#[wasm_bindgen]
pub fn ext_secp_from_seed(seed: &[u8]) -> Vec<u8> {
match SecretKey::parse_slice(seed) {
Ok(s) => {
let mut res = vec![];
let pubkey = PublicKey::from_secret_key(&s);
res.extend_from_slice(&s.serialize());
res.extend_from_slice(&pubkey.serialize_compressed());
res
},
_ => panic!("Incalid seed provided.")
}
}
#[wasm_bindgen]
pub fn ext_secp_recover(hash: &[u8], sig: &[u8], rec: u8) -> Vec<u8> {
match (Message::parse_slice(hash), Signature::parse_standard_slice(sig), RecoveryId::parse(rec)) {
(Ok(m), Ok(s), Ok(r)) =>
match recover(&m, &s, &r) {
Ok(k) => k
.serialize_compressed()
.to_vec(),
_ => panic!("Invalid message provided.")
},
_ => panic!("Invalid recovery data provided.")
}
}
#[wasm_bindgen]
pub fn ext_secp_sign(hash: &[u8], seckey: &[u8]) -> Vec<u8> {
match (Message::parse_slice(hash), SecretKey::parse_slice(seckey)) {
(Ok(m), Ok(s)) => {
let mut res = vec![];
let (sig, rec) = sign(&m, &s);
res.extend_from_slice(&sig.serialize());
res.push(rec.into());
res
},
_ => panic!("Invalid message or secret provided.")
}
}
#[cfg(test)]
pub mod tests {
use hex_literal::hex;
use super::*;
#[test]
fn can_create_pair() {
let seckey = hex!("4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae");
let expected = hex!("4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae03fd8c74f795ced92064b86191cb2772b1e3a0947740aa0a5a6e379592471fd85b");
let res = ext_secp_from_seed(&seckey);
assert_eq!(res[..], expected[..]);
}
#[test]
fn can_pub_compress_full() {
let pubkey = hex!("04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af");
let expected = hex!("03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077");
let res = ext_secp_pub_compress(&pubkey);
assert_eq!(res[..], expected[..]);
}
#[test]
fn can_pub_expand_comp() {
let pubkey = hex!("03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077");
let expected = hex!("04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af");
let res = ext_secp_pub_expand(&pubkey);
assert_eq!(res[..], expected[..]);
}
#[test]
fn can_recover() {
let expected = hex!("028d13da15a02f3a70677339d51b14177ee9b49657662b35e56a9d9dee17db1d30");
let sig = hex!("7505f2880114da51b3f5d535f8687953c0ab9af4ab81e592eaebebf53b728d2b6dfd9b5bcd70fee412b1f31360e7c2774009305cb84fc50c1d0ff8034dfa5fff");
let msg = hex!("a30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9");
let res = ext_secp_recover(&msg, &sig, 0);
assert_eq!(res[..], expected[..]);
}
#[test]
fn can_sign() {
// JS expectiation - doesn't match?
// let expected = hex!("df92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba8c4efa521361678d9b8582744d77aa4b8d886d7380b7808a683174afad9c4700300");
let expected = hex!("df92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba83b105adec9e9872647a7d8bb28855b45e22805aea3d097953cbb1391f671d13e01");
let seckey = hex!("4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae");
let msg = hex!("68c731589a583d08b70861683b59ce3dd56284cb2f0da5b6cd83e6641dac3aab");
let res = ext_secp_sign(&msg, &seckey);
assert_eq!(res[..], expected[..]);
}
}
+65 -51
View File
@@ -15,10 +15,10 @@ use schnorrkel::{
use wasm_bindgen::prelude::*;
// We must make sure that this is the same as declared in the substrate source code.
const SIGNING_CTX: &'static [u8] = b"substrate";
const CTX: &'static [u8] = b"substrate";
/// ChainCode construction helper
fn create_cc(data: &[u8]) -> ChainCode {
fn new_cc(data: &[u8]) -> ChainCode {
let mut cc = [0u8; CHAIN_CODE_LENGTH];
cc.copy_from_slice(&data);
@@ -34,13 +34,14 @@ fn create_cc(data: &[u8]) -> ChainCode {
/// returned vector the derived keypair as a array of 96 bytes
#[wasm_bindgen]
pub fn ext_sr_derive_keypair_hard(pair: &[u8], cc: &[u8]) -> Vec<u8> {
Keypair::from_half_ed25519_bytes(pair)
.unwrap()
.secret
.hard_derive_mini_secret_key(Some(create_cc(cc)), &[]).0
.expand_to_keypair(ExpansionMode::Ed25519)
.to_half_ed25519_bytes()
.to_vec()
match Keypair::from_half_ed25519_bytes(pair) {
Ok(p) => p.secret
.hard_derive_mini_secret_key(Some(new_cc(cc)), &[]).0
.expand_to_keypair(ExpansionMode::Ed25519)
.to_half_ed25519_bytes()
.to_vec(),
_ => panic!("Invalid pair provided.")
}
}
/// Perform a derivation on a secret
@@ -51,11 +52,13 @@ pub fn ext_sr_derive_keypair_hard(pair: &[u8], cc: &[u8]) -> Vec<u8> {
/// returned vector the derived keypair as a array of 96 bytes
#[wasm_bindgen]
pub fn ext_sr_derive_keypair_soft(pair: &[u8], cc: &[u8]) -> Vec<u8> {
Keypair::from_half_ed25519_bytes(pair)
.unwrap()
.derived_key_simple(create_cc(cc), &[]).0
.to_half_ed25519_bytes()
.to_vec()
match Keypair::from_half_ed25519_bytes(pair) {
Ok(p) => p
.derived_key_simple(new_cc(cc), &[]).0
.to_half_ed25519_bytes()
.to_vec(),
_ => panic!("Invalid pair provided.")
}
}
/// Perform a derivation on a publicKey
@@ -66,11 +69,13 @@ pub fn ext_sr_derive_keypair_soft(pair: &[u8], cc: &[u8]) -> Vec<u8> {
/// returned vector is the derived publicKey as a array of 32 bytes
#[wasm_bindgen]
pub fn ext_sr_derive_public_soft(pubkey: &[u8], cc: &[u8]) -> Vec<u8> {
PublicKey::from_bytes(pubkey)
.unwrap()
.derived_key_simple(create_cc(cc), &[]).0
.to_bytes()
.to_vec()
match PublicKey::from_bytes(pubkey) {
Ok(k) => k
.derived_key_simple(new_cc(cc), &[]).0
.to_bytes()
.to_vec(),
_ => panic!("Invalid pubkey provided.")
}
}
/// Generate a key pair.
@@ -81,11 +86,13 @@ pub fn ext_sr_derive_public_soft(pubkey: &[u8], cc: &[u8]) -> Vec<u8> {
/// followed by the public key (32) bytes.
#[wasm_bindgen]
pub fn ext_sr_from_seed(seed: &[u8]) -> Vec<u8> {
MiniSecretKey::from_bytes(seed)
.unwrap()
.expand_to_keypair(ExpansionMode::Ed25519)
.to_half_ed25519_bytes()
.to_vec()
match MiniSecretKey::from_bytes(seed) {
Ok(s) => s
.expand_to_keypair(ExpansionMode::Ed25519)
.to_half_ed25519_bytes()
.to_vec(),
_ => panic!("Invalid seed provided.")
}
}
/// Generate a key pair from a known pair. (This is not exposed via WASM)
@@ -95,10 +102,12 @@ pub fn ext_sr_from_seed(seed: &[u8]) -> Vec<u8> {
/// returned vector is the concatenation of first the private key (64 bytes)
/// followed by the public key (32) bytes.
pub fn ext_sr_from_pair(pair: &[u8]) -> Vec<u8> {
Keypair::from_half_ed25519_bytes(pair)
.unwrap()
.to_half_ed25519_bytes()
.to_vec()
match Keypair::from_half_ed25519_bytes(pair) {
Ok(p) => p
.to_half_ed25519_bytes()
.to_vec(),
_ => panic!("Invalid pair provided.")
}
}
/// Sign a message
@@ -113,11 +122,13 @@ pub fn ext_sr_from_pair(pair: &[u8]) -> Vec<u8> {
/// * returned vector is the signature consisting of 64 bytes.
#[wasm_bindgen]
pub fn ext_sr_sign(pubkey: &[u8], secret: &[u8], message: &[u8]) -> Vec<u8> {
SecretKey::from_ed25519_bytes(secret)
.unwrap()
.sign_simple(SIGNING_CTX, message, &PublicKey::from_bytes(pubkey).unwrap())
.to_bytes()
.to_vec()
match (SecretKey::from_ed25519_bytes(secret), PublicKey::from_bytes(pubkey)) {
(Ok(s), Ok(k)) => s
.sign_simple(CTX, message, &k)
.to_bytes()
.to_vec(),
_ => panic!("Invalid secret or pubkey provided.")
}
}
/// Verify a message and its corresponding against a public key;
@@ -127,11 +138,11 @@ pub fn ext_sr_sign(pubkey: &[u8], secret: &[u8], message: &[u8]) -> Vec<u8> {
/// * pubkey: UIntArray with 32 element
#[wasm_bindgen]
pub fn ext_sr_verify(signature: &[u8], message: &[u8], pubkey: &[u8]) -> bool {
match Signature::from_bytes(signature) {
Ok(signature) => PublicKey::from_bytes(pubkey).unwrap()
.verify_simple(SIGNING_CTX, message, &signature)
match (Signature::from_bytes(signature), PublicKey::from_bytes(pubkey)) {
(Ok(s), Ok(k)) => k
.verify_simple(CTX, message, &s)
.is_ok(),
Err(_) => false
_ => false
}
}
@@ -143,19 +154,22 @@ pub fn ext_sr_verify(signature: &[u8], message: &[u8], pubkey: &[u8]) -> bool {
/// * returned vector is the generated secret of 32 bytes.
#[wasm_bindgen]
pub fn ext_sr_agree(pubkey: &[u8], secret: &[u8]) -> Vec<u8> {
// The first 32 bytes holds the canonical private key
let mut key = [0u8; 32];
match SecretKey::from_ed25519_bytes(secret) {
Ok(s) => {
// The first 32 bytes holds the canonical private key
let mut key = [0u8; 32];
key.copy_from_slice(
&SecretKey::from_ed25519_bytes(secret)
.unwrap()
.to_bytes()[0..32]
);
key.copy_from_slice(&s.to_bytes()[0..32]);
(
&Scalar::from_canonical_bytes(key).unwrap() *
PublicKey::from_bytes(pubkey).unwrap().as_point()
).compress().0.to_vec()
match (Scalar::from_canonical_bytes(key), PublicKey::from_bytes(pubkey)) {
(Some(n), Ok(k)) => (&n * k.as_point())
.compress().0
.to_vec(),
_ => panic!("Invalid scalar or pubkey provided.")
}
},
_ => panic!("Invalid secret provided.")
}
}
#[cfg(test)]
@@ -168,11 +182,11 @@ pub mod tests {
use schnorrkel::{SIGNATURE_LENGTH, KEYPAIR_LENGTH, SECRET_KEY_LENGTH};
fn generate_random_seed() -> Vec<u8> {
(0..32).map(|_| rand::random::<u8>() ).collect()
(0..32).map(|_| rand::random::<u8>()).collect()
}
#[test]
fn can_create_keypair() {
fn can_new_keypair() {
let seed = generate_random_seed();
let keypair = ext_sr_from_seed(seed.as_slice());
@@ -190,7 +204,7 @@ pub mod tests {
}
#[test]
fn create_pair_from_known_pair() {
fn new_pair_from_known_pair() {
let input = hex!("28b0ae221c6bb06856b287f60d7ea0d98552ea5a16db16956849aa371db3eb51fd190cce74df356432b410bd64682309d6dedb27c76845daf388557cbac3ca3446ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a");
let keypair = ext_sr_from_pair(&input);
let expected = hex!("46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a");
+37 -46
View File
@@ -12,21 +12,21 @@ use schnorrkel::{signing_context, vrf::{VRFOutput, VRFProof}, PublicKey, SecretK
use wasm_bindgen::prelude::*;
/// Size of VRF output, bytes
pub const VRF_OUTPUT_SIZE: usize = 32;
pub const OUTPUT_SIZE: usize = 32;
/// Size of VRF proof, bytes
pub const VRF_PROOF_SIZE: usize = 64;
pub const PROOF_SIZE: usize = 64;
/// Size of VRF raw output, bytes
pub const VRF_RAW_OUTPUT_SIZE: usize = 16;
pub const RAW_OUTPUT_SIZE: usize = 16;
/// Size of VRF limit, bytes
pub const VRF_THRESHOLD_SIZE: usize = 16;
pub const THRESHOLD_SIZE: usize = 16;
/// Size of the final full output
pub const VRF_RESULT_SIZE: usize = VRF_OUTPUT_SIZE + VRF_PROOF_SIZE;
pub const RESULT_SIZE: usize = OUTPUT_SIZE + PROOF_SIZE;
pub fn create_transcript(extra: &[u8]) -> Transcript {
pub fn new_transcript(extra: &[u8]) -> Transcript {
let mut transcript = Transcript::new(b"VRF");
// if is important that we don't append when empty, since the
@@ -38,7 +38,7 @@ pub fn create_transcript(extra: &[u8]) -> Transcript {
transcript
}
// We don't use the non-extra vrf_sign and vrf_verify internally since in sr25519 they only wrap -
// We don't use the non-extra sign and verify internally since in sr25519 they only wrap -
//
// https://github.com/w3f/schnorrkel/blob/8fa2ad3e9fbf0b652c724df6a87a4b3c5500f759/src/vrf.rs#L660
@@ -53,15 +53,21 @@ pub fn create_transcript(extra: &[u8]) -> Transcript {
///
/// * returned vector is the 32-byte output (signature) and 64-byte proof.
#[wasm_bindgen]
pub fn ext_vrf_sign(secret: &[u8], context: &[u8], message: &[u8], extra: &[u8]) -> Vec<u8> {
let keypair = SecretKey::from_ed25519_bytes(secret).unwrap().to_keypair();
let transcript = create_transcript(extra);
let (io, proof, _) = keypair.vrf_sign_extra(signing_context(context).bytes(message), transcript);
let mut result: [u8; VRF_RESULT_SIZE] = [0u8; VRF_RESULT_SIZE];
pub fn ext_vrf_sign(secret: &[u8], ctx: &[u8], msg: &[u8], extra: &[u8]) -> Vec<u8> {
match SecretKey::from_ed25519_bytes(secret) {
Ok(s) => {
let mut res: [u8; RESULT_SIZE] = [0u8; RESULT_SIZE];
let (io, proof, _) = s
.to_keypair()
.vrf_sign_extra(signing_context(ctx).bytes(msg), new_transcript(extra));
result[..VRF_OUTPUT_SIZE].copy_from_slice(io.as_output_bytes());
result[VRF_OUTPUT_SIZE..].copy_from_slice(&proof.to_bytes());
result.to_vec()
res[..OUTPUT_SIZE].copy_from_slice(io.as_output_bytes());
res[OUTPUT_SIZE..].copy_from_slice(&proof.to_bytes());
res.to_vec()
},
_ => panic!("Invalid secret provided.")
}
}
/// Verify VRF proof for one single input transcript, and an extra message transcript,
@@ -71,24 +77,13 @@ pub fn ext_vrf_sign(secret: &[u8], context: &[u8], message: &[u8], extra: &[u8])
/// * context: Arbitrary length UIntArray
/// * message: Arbitrary length UIntArray
/// * extra: Arbitrary length UIntArray
/// * out_and_proof: 96-byte output & proof array from the ext_vrf_sign function.
/// * out_and_proof: 96-byte output & proof array from the ext_sign function.
#[wasm_bindgen]
pub fn ext_vrf_verify(pubkey: &[u8], context: &[u8], message: &[u8], extra: &[u8], out_and_proof: &[u8]) -> bool {
match (
PublicKey::from_bytes(pubkey),
VRFOutput::from_bytes(&out_and_proof[..VRF_OUTPUT_SIZE]),
VRFProof::from_bytes(&out_and_proof[VRF_OUTPUT_SIZE..VRF_RESULT_SIZE])
) {
(Ok(public), Ok(out), Ok(proof)) => {
public
.vrf_verify_extra(
signing_context(context).bytes(message),
&out,
&proof,
create_transcript(extra)
)
.is_ok()
}
pub fn ext_vrf_verify(pubkey: &[u8], ctx: &[u8], msg: &[u8], extra: &[u8], out: &[u8]) -> bool {
match (PublicKey::from_bytes(pubkey), VRFOutput::from_bytes(&out[..OUTPUT_SIZE]), VRFProof::from_bytes(&out[OUTPUT_SIZE..RESULT_SIZE])) {
(Ok(k), Ok(o), Ok(p)) => k
.vrf_verify_extra(signing_context(ctx).bytes(msg), &o, &p, new_transcript(extra))
.is_ok(),
_ => false,
}
}
@@ -107,7 +102,7 @@ pub mod tests {
}
#[test]
fn vrf_sign_extra_and_verify() {
fn sign_extra_and_verify() {
let seed = generate_random_seed();
let keypair = ext_sr_from_seed(seed.as_slice());
let private = &keypair[0..SECRET_KEY_LENGTH];
@@ -116,23 +111,19 @@ pub mod tests {
let message = b"this is a message";
let extra = b"this is an extra";
// Perform multiple vrf_sign_extra calls w/ same context, message, extra args
let out_and_proof1 = ext_vrf_sign(private, context, message, extra);
let out_and_proof2 = ext_vrf_sign(private, context, message, extra);
// Perform multiple sign_extra calls w/ same context, message, extra args
let out1 = ext_vrf_sign(private, context, message, extra);
let out2 = ext_vrf_sign(private, context, message, extra);
// Basic size checks
assert!(out_and_proof1.len() == VRF_RESULT_SIZE);
assert!(out_and_proof2.len() == VRF_RESULT_SIZE);
assert!(out1.len() == RESULT_SIZE);
assert!(out2.len() == RESULT_SIZE);
// Given the same context, message & extra, output should be deterministic
let out1 = &out_and_proof1[..VRF_OUTPUT_SIZE];
let out2 = &out_and_proof2[..VRF_OUTPUT_SIZE];
assert_eq!(out1, out2);
assert_eq!(&out1[..OUTPUT_SIZE], &out2[..OUTPUT_SIZE]);
// But proof is non-deterministic
let proof1 = &out_and_proof1[VRF_OUTPUT_SIZE..];
let proof2 = &out_and_proof2[VRF_OUTPUT_SIZE..];
assert_ne!(proof1, proof2);
assert_ne!(&out1[OUTPUT_SIZE..], &out2[OUTPUT_SIZE..]);
// VRF outputs can verified w/ original context, message & extra args
assert!(ext_vrf_verify(
@@ -140,14 +131,14 @@ pub mod tests {
context,
message,
extra,
&out_and_proof1
&out1
));
assert!(ext_vrf_verify(
public,
context,
message,
extra,
&out_and_proof2
&out2
));
}
}
+10
View File
@@ -55,6 +55,16 @@ export interface WasmCryptoInstance {
ext_twox(resLen: 8, ptrData: number, lenData: number, rounds: number): void;
ext_secp_from_seed(reslen: 8, ptrSec: number, lenSec: number): void;
ext_secp_pub_compress(resLen: 8, ptrPub: number, lenPub: number): void;
ext_secp_pub_expand(resLen: 8, ptrPub: number, lenPub: number): void;
ext_secp_recover(resLen: 8, ptrMsgHash: number, lenMsgHash: number, ptrSig: number, lenSig: number, recovery: number): void;
ext_secp_sign(resLen: 8, ptrMsgHash: number, lenMsgHash: number, ptrSec: number, lenSec: number): void;
ext_sr_derive_keypair_hard(resLen: 8, ptrPair: number, lenPair: number, ptrCc: number, lenCc: number): void;
ext_sr_derive_keypair_soft(resLen: 8, ptrPub: number, lenPub: number, ptrCc: number, lenCc: number): void;
+2
View File
@@ -5,6 +5,7 @@ const wasm = require('../../build/index.cjs');
const bip39 = require('./bip39.cjs');
const ed25519 = require('./ed25519.cjs');
const hashing = require('./hashing.cjs');
const secp256k1 = require('./secp256k1.cjs');
const sr25519 = require('./sr25519.cjs');
const vrf = require('./vrf.cjs');
@@ -12,6 +13,7 @@ const tests = {
...bip39,
...ed25519,
...hashing,
...secp256k1,
...sr25519,
...vrf
};
@@ -0,0 +1,59 @@
// Copyright 2019-2021 @polkadot/wasm-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
const { assert, hexToU8a, u8aToHex } = require('@polkadot/util');
function secp256k1Compress (wasm) {
const pubkey = '0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af';
const result = u8aToHex(wasm.secp256k1Compress(hexToU8a(pubkey)));
console.log('\tRES', result);
assert(result === '0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077', 'ERROR: secp256k1Compress does not match');
}
function secp256k1Expand (wasm) {
const pubkey = '0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077';
const result = u8aToHex(wasm.secp256k1Expand(hexToU8a(pubkey)));
console.log('\tRES', result);
assert(result === '0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af', 'ERROR: secp256k1Expand does not match');
}
function secp256k1FromSeed (wasm) {
const seckey = '0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae';
const result = u8aToHex(wasm.secp256k1FromSeed(hexToU8a(seckey)));
console.log('\tRES', result);
assert(result === '0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae03fd8c74f795ced92064b86191cb2772b1e3a0947740aa0a5a6e379592471fd85b', 'ERROR: secp256k1FromSeed does not match');
}
function secp256k1Recover (wasm) {
const sig = '0x7505f2880114da51b3f5d535f8687953c0ab9af4ab81e592eaebebf53b728d2b6dfd9b5bcd70fee412b1f31360e7c2774009305cb84fc50c1d0ff8034dfa5fff';
const msg = '0xa30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9';
const result = u8aToHex(wasm.secp256k1Recover(hexToU8a(msg), hexToU8a(sig), 0));
console.log('\tRES', result);
assert(result === '0x028d13da15a02f3a70677339d51b14177ee9b49657662b35e56a9d9dee17db1d30', 'ERROR: secp256k1Recover does not match');
}
function secp256k1Sign (wasm) {
const sec = '0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae';
const msg = '0x68c731589a583d08b70861683b59ce3dd56284cb2f0da5b6cd83e6641dac3aab';
const result = u8aToHex(wasm.secp256k1Sign(hexToU8a(msg), hexToU8a(sec)));
console.log('\tRES', result);
assert(result === '0xdf92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba83b105adec9e9872647a7d8bb28855b45e22805aea3d097953cbb1391f671d13e01', 'ERROR: secp256k1Sign does not match');
}
module.exports = {
secp256k1Compress,
secp256k1Expand,
secp256k1FromSeed,
secp256k1Recover,
secp256k1Sign
};
+1 -1
View File
@@ -3,5 +3,5 @@
# This software may be modified and distributed under the terms
# of the Apache-2.0 license. See the LICENSE file for details.
RUST_VER=nightly-2020-10-25
RUST_VER=nightly-2021-12-02
# RUST_VER=stable
+532 -526
View File
File diff suppressed because it is too large Load Diff