@waku/core 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/bundle/{index-691c0be6.js → index-a67d7136.js} +1 -1
  3. package/bundle/{index-0a4bdddc.js → index-f7e049ad.js} +1 -1
  4. package/bundle/index.js +24853 -3555
  5. package/bundle/lib/peer_discovery_static_list.js +18 -4
  6. package/bundle/lib/predefined_bootstrap_nodes.js +1 -1
  7. package/bundle/lib/wait_for_remote_peer.js +2 -3
  8. package/bundle/lib/waku_message/topic_only_message.js +2 -3
  9. package/bundle/lib/waku_message/version_0.js +317 -4
  10. package/bundle/{message-e2db79d7.js → message-049c8b67.js} +861 -2
  11. package/bundle/{topic_only_message-34f36fa6.js → topic_only_message-5ad3a869.js} +1 -1
  12. package/dist/index.d.ts +0 -3
  13. package/dist/index.js +0 -3
  14. package/dist/index.js.map +1 -1
  15. package/dist/lib/waku_filter/index.d.ts +2 -2
  16. package/dist/lib/waku_filter/index.js.map +1 -1
  17. package/dist/lib/waku_message/version_0.d.ts +3 -2
  18. package/dist/lib/waku_message/version_0.js +2 -1
  19. package/dist/lib/waku_message/version_0.js.map +1 -1
  20. package/dist/lib/waku_relay/index.d.ts +4 -3
  21. package/dist/lib/waku_relay/index.js.map +1 -1
  22. package/dist/lib/waku_store/index.d.ts +4 -4
  23. package/package.json +4 -123
  24. package/src/index.ts +0 -10
  25. package/src/lib/waku_filter/index.ts +4 -3
  26. package/src/lib/waku_message/version_0.ts +5 -3
  27. package/src/lib/waku_relay/index.ts +4 -3
  28. package/src/lib/waku_store/index.ts +5 -5
  29. package/bundle/crypto-8551d579.js +0 -2585
  30. package/bundle/crypto-b00764b7.js +0 -1772
  31. package/bundle/enr-564d4a51.js +0 -20785
  32. package/bundle/enr-9fc5eed8.js +0 -20786
  33. package/bundle/enr-f6e82a53.js +0 -20785
  34. package/bundle/events-fcbda4dc.js +0 -76
  35. package/bundle/index-02d21809.js +0 -20
  36. package/bundle/index-2ae915be.js +0 -1854
  37. package/bundle/index-a013a259.js +0 -20
  38. package/bundle/index-ba42b4fc.js +0 -862
  39. package/bundle/lib/enr.js +0 -8
  40. package/bundle/lib/peer_discovery_dns.js +0 -5018
  41. package/bundle/lib/utils.js +0 -1
  42. package/bundle/lib/waku_message/version_1.js +0 -463
  43. package/bundle/multiaddr_to_peer_info-c406b1e1.js +0 -19
  44. package/bundle/multiaddr_to_peer_info-fd1de516.js +0 -19
  45. package/bundle/utils-9a3221f2.js +0 -815
  46. package/bundle/version_0-e6fe440c.js +0 -317
  47. package/dist/lib/crypto.d.ts +0 -34
  48. package/dist/lib/crypto.js +0 -79
  49. package/dist/lib/crypto.js.map +0 -1
  50. package/dist/lib/enr/constants.d.ts +0 -4
  51. package/dist/lib/enr/constants.js +0 -8
  52. package/dist/lib/enr/constants.js.map +0 -1
  53. package/dist/lib/enr/enr.d.ts +0 -90
  54. package/dist/lib/enr/enr.js +0 -432
  55. package/dist/lib/enr/enr.js.map +0 -1
  56. package/dist/lib/enr/index.d.ts +0 -5
  57. package/dist/lib/enr/index.js +0 -6
  58. package/dist/lib/enr/index.js.map +0 -1
  59. package/dist/lib/enr/keypair/index.d.ts +0 -8
  60. package/dist/lib/enr/keypair/index.js +0 -53
  61. package/dist/lib/enr/keypair/index.js.map +0 -1
  62. package/dist/lib/enr/keypair/secp256k1.d.ts +0 -13
  63. package/dist/lib/enr/keypair/secp256k1.js +0 -57
  64. package/dist/lib/enr/keypair/secp256k1.js.map +0 -1
  65. package/dist/lib/enr/keypair/types.d.ts +0 -13
  66. package/dist/lib/enr/keypair/types.js +0 -7
  67. package/dist/lib/enr/keypair/types.js.map +0 -1
  68. package/dist/lib/enr/multiaddr_from_fields.d.ts +0 -2
  69. package/dist/lib/enr/multiaddr_from_fields.js +0 -8
  70. package/dist/lib/enr/multiaddr_from_fields.js.map +0 -1
  71. package/dist/lib/enr/multiaddrs_codec.d.ts +0 -3
  72. package/dist/lib/enr/multiaddrs_codec.js +0 -32
  73. package/dist/lib/enr/multiaddrs_codec.js.map +0 -1
  74. package/dist/lib/enr/types.d.ts +0 -8
  75. package/dist/lib/enr/types.js +0 -3
  76. package/dist/lib/enr/types.js.map +0 -1
  77. package/dist/lib/enr/v4.d.ts +0 -3
  78. package/dist/lib/enr/v4.js +0 -14
  79. package/dist/lib/enr/v4.js.map +0 -1
  80. package/dist/lib/enr/waku2_codec.d.ts +0 -8
  81. package/dist/lib/enr/waku2_codec.js +0 -36
  82. package/dist/lib/enr/waku2_codec.js.map +0 -1
  83. package/dist/lib/peer_discovery_dns/dns.d.ts +0 -48
  84. package/dist/lib/peer_discovery_dns/dns.js +0 -158
  85. package/dist/lib/peer_discovery_dns/dns.js.map +0 -1
  86. package/dist/lib/peer_discovery_dns/dns_over_https.d.ts +0 -32
  87. package/dist/lib/peer_discovery_dns/dns_over_https.js +0 -87
  88. package/dist/lib/peer_discovery_dns/dns_over_https.js.map +0 -1
  89. package/dist/lib/peer_discovery_dns/enrtree.d.ts +0 -33
  90. package/dist/lib/peer_discovery_dns/enrtree.js +0 -76
  91. package/dist/lib/peer_discovery_dns/enrtree.js.map +0 -1
  92. package/dist/lib/peer_discovery_dns/fetch_nodes.d.ts +0 -14
  93. package/dist/lib/peer_discovery_dns/fetch_nodes.js +0 -133
  94. package/dist/lib/peer_discovery_dns/fetch_nodes.js.map +0 -1
  95. package/dist/lib/peer_discovery_dns/index.d.ts +0 -30
  96. package/dist/lib/peer_discovery_dns/index.js +0 -54
  97. package/dist/lib/peer_discovery_dns/index.js.map +0 -1
  98. package/dist/lib/utils.d.ts +0 -22
  99. package/dist/lib/utils.js +0 -40
  100. package/dist/lib/utils.js.map +0 -1
  101. package/dist/lib/waku_message/constants.d.ts +0 -12
  102. package/dist/lib/waku_message/constants.js +0 -10
  103. package/dist/lib/waku_message/constants.js.map +0 -1
  104. package/dist/lib/waku_message/ecies.d.ts +0 -17
  105. package/dist/lib/waku_message/ecies.js +0 -126
  106. package/dist/lib/waku_message/ecies.js.map +0 -1
  107. package/dist/lib/waku_message/symmetric.d.ts +0 -3
  108. package/dist/lib/waku_message/symmetric.js +0 -18
  109. package/dist/lib/waku_message/symmetric.js.map +0 -1
  110. package/dist/lib/waku_message/version_1.d.ts +0 -93
  111. package/dist/lib/waku_message/version_1.js +0 -325
  112. package/dist/lib/waku_message/version_1.js.map +0 -1
  113. package/src/lib/crypto.ts +0 -100
  114. package/src/lib/enr/constants.ts +0 -10
  115. package/src/lib/enr/enr.ts +0 -516
  116. package/src/lib/enr/index.ts +0 -5
  117. package/src/lib/enr/keypair/index.ts +0 -76
  118. package/src/lib/enr/keypair/secp256k1.ts +0 -69
  119. package/src/lib/enr/keypair/types.ts +0 -14
  120. package/src/lib/enr/multiaddr_from_fields.ts +0 -18
  121. package/src/lib/enr/multiaddrs_codec.ts +0 -50
  122. package/src/lib/enr/types.ts +0 -11
  123. package/src/lib/enr/v4.ts +0 -22
  124. package/src/lib/enr/waku2_codec.ts +0 -39
  125. package/src/lib/peer_discovery_dns/dns.ts +0 -223
  126. package/src/lib/peer_discovery_dns/dns_over_https.ts +0 -98
  127. package/src/lib/peer_discovery_dns/enrtree.ts +0 -123
  128. package/src/lib/peer_discovery_dns/fetch_nodes.ts +0 -180
  129. package/src/lib/peer_discovery_dns/index.ts +0 -84
  130. package/src/lib/utils.ts +0 -50
  131. package/src/lib/waku_message/constants.ts +0 -10
  132. package/src/lib/waku_message/ecies.ts +0 -194
  133. package/src/lib/waku_message/symmetric.ts +0 -33
  134. package/src/lib/waku_message/version_1.ts +0 -457
@@ -1,180 +0,0 @@
1
- import debug from "debug";
2
-
3
- import { ENR, Waku2 } from "../enr";
4
-
5
- import { NodeCapabilityCount } from "./dns";
6
-
7
- const log = debug("waku:discovery:fetch_nodes");
8
-
9
- /**
10
- * Fetch nodes using passed [[getNode]] until all wanted capabilities are
11
- * fulfilled or the number of [[getNode]] call exceeds the sum of
12
- * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].
13
- */
14
- export async function fetchNodesUntilCapabilitiesFulfilled(
15
- wantedNodeCapabilityCount: Partial<NodeCapabilityCount>,
16
- errorTolerance: number,
17
- getNode: () => Promise<ENR | null>
18
- ): Promise<ENR[]> {
19
- const wanted = {
20
- relay: wantedNodeCapabilityCount.relay ?? 0,
21
- store: wantedNodeCapabilityCount.store ?? 0,
22
- filter: wantedNodeCapabilityCount.filter ?? 0,
23
- lightPush: wantedNodeCapabilityCount.lightPush ?? 0,
24
- };
25
-
26
- const maxSearches =
27
- wanted.relay + wanted.store + wanted.filter + wanted.lightPush;
28
-
29
- const actual = {
30
- relay: 0,
31
- store: 0,
32
- filter: 0,
33
- lightPush: 0,
34
- };
35
-
36
- let totalSearches = 0;
37
- const peers: ENR[] = [];
38
-
39
- while (
40
- !isSatisfied(wanted, actual) &&
41
- totalSearches < maxSearches + errorTolerance
42
- ) {
43
- const peer = await getNode();
44
- if (peer && isNewPeer(peer, peers)) {
45
- // ENRs without a waku2 key are ignored.
46
- if (peer.waku2) {
47
- if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {
48
- addCapabilities(peer.waku2, actual);
49
- peers.push(peer);
50
- }
51
- }
52
- log(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
53
- }
54
-
55
- totalSearches++;
56
- }
57
- return peers;
58
- }
59
-
60
- /**
61
- * Fetch nodes using passed [[getNode]] until all wanted capabilities are
62
- * fulfilled or the number of [[getNode]] call exceeds the sum of
63
- * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].
64
- */
65
- export async function* yieldNodesUntilCapabilitiesFulfilled(
66
- wantedNodeCapabilityCount: Partial<NodeCapabilityCount>,
67
- errorTolerance: number,
68
- getNode: () => Promise<ENR | null>
69
- ): AsyncGenerator<ENR> {
70
- const wanted = {
71
- relay: wantedNodeCapabilityCount.relay ?? 0,
72
- store: wantedNodeCapabilityCount.store ?? 0,
73
- filter: wantedNodeCapabilityCount.filter ?? 0,
74
- lightPush: wantedNodeCapabilityCount.lightPush ?? 0,
75
- };
76
-
77
- const maxSearches =
78
- wanted.relay + wanted.store + wanted.filter + wanted.lightPush;
79
-
80
- const actual = {
81
- relay: 0,
82
- store: 0,
83
- filter: 0,
84
- lightPush: 0,
85
- };
86
-
87
- let totalSearches = 0;
88
- const peerNodeIds = new Set();
89
-
90
- while (
91
- !isSatisfied(wanted, actual) &&
92
- totalSearches < maxSearches + errorTolerance
93
- ) {
94
- const peer = await getNode();
95
- if (peer && peer.nodeId && !peerNodeIds.has(peer.nodeId)) {
96
- peerNodeIds.add(peer.nodeId);
97
- // ENRs without a waku2 key are ignored.
98
- if (peer.waku2) {
99
- if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {
100
- addCapabilities(peer.waku2, actual);
101
- yield peer;
102
- }
103
- }
104
- log(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
105
- }
106
- totalSearches++;
107
- }
108
- }
109
-
110
- function isSatisfied(
111
- wanted: NodeCapabilityCount,
112
- actual: NodeCapabilityCount
113
- ): boolean {
114
- return (
115
- actual.relay >= wanted.relay &&
116
- actual.store >= wanted.store &&
117
- actual.filter >= wanted.filter &&
118
- actual.lightPush >= wanted.lightPush
119
- );
120
- }
121
-
122
- function isNewPeer(peer: ENR, peers: ENR[]): boolean {
123
- if (!peer.nodeId) return false;
124
-
125
- for (const existingPeer of peers) {
126
- if (peer.nodeId === existingPeer.nodeId) {
127
- return false;
128
- }
129
- }
130
-
131
- return true;
132
- }
133
-
134
- function addCapabilities(node: Waku2, total: NodeCapabilityCount): void {
135
- if (node.relay) total.relay += 1;
136
- if (node.store) total.store += 1;
137
- if (node.filter) total.filter += 1;
138
- if (node.lightPush) total.lightPush += 1;
139
- }
140
-
141
- /**
142
- * Checks if the proposed ENR [[node]] helps satisfy the [[wanted]] capabilities,
143
- * considering the [[actual]] capabilities of nodes retrieved so far..
144
- *
145
- * @throws If the function is called when the wanted capabilities are already fulfilled.
146
- */
147
- function helpsSatisfyCapabilities(
148
- node: Waku2,
149
- wanted: NodeCapabilityCount,
150
- actual: NodeCapabilityCount
151
- ): boolean {
152
- if (isSatisfied(wanted, actual)) {
153
- throw "Internal Error: Waku2 wanted capabilities are already fulfilled";
154
- }
155
-
156
- const missing = missingCapabilities(wanted, actual);
157
-
158
- return (
159
- (missing.relay && node.relay) ||
160
- (missing.store && node.store) ||
161
- (missing.filter && node.filter) ||
162
- (missing.lightPush && node.lightPush)
163
- );
164
- }
165
-
166
- /**
167
- * Return a [[Waku2]] Object for which capabilities are set to true if they are
168
- * [[wanted]] yet missing from [[actual]].
169
- */
170
- function missingCapabilities(
171
- wanted: NodeCapabilityCount,
172
- actual: NodeCapabilityCount
173
- ): Waku2 {
174
- return {
175
- relay: actual.relay < wanted.relay,
176
- store: actual.store < wanted.store,
177
- filter: actual.filter < wanted.filter,
178
- lightPush: actual.lightPush < wanted.lightPush,
179
- };
180
- }
@@ -1,84 +0,0 @@
1
- import type {
2
- PeerDiscovery,
3
- PeerDiscoveryEvents,
4
- } from "@libp2p/interface-peer-discovery";
5
- import { symbol } from "@libp2p/interface-peer-discovery";
6
- import type { PeerInfo } from "@libp2p/interface-peer-info";
7
- import { CustomEvent, EventEmitter } from "@libp2p/interfaces/events";
8
- import debug from "debug";
9
-
10
- import { ENR } from "../enr";
11
- import { multiaddrsToPeerInfo } from "../multiaddr_to_peer_info";
12
-
13
- import { DnsNodeDiscovery, NodeCapabilityCount } from "./dns";
14
-
15
- const log = debug("waku:peer-discovery-dns");
16
-
17
- /**
18
- * Parse options and expose function to return bootstrap peer addresses.
19
- *
20
- * @throws if an invalid combination of options is passed, see [[BootstrapOptions]] for details.
21
- */
22
- export class PeerDiscoveryDns
23
- extends EventEmitter<PeerDiscoveryEvents>
24
- implements PeerDiscovery
25
- {
26
- private readonly nextPeer: () => AsyncGenerator<ENR>;
27
- private _started: boolean;
28
-
29
- /**
30
- * @param enrUrl An EIP-1459 ENR Tree URL. For example:
31
- * "enrtree://AOFTICU2XWDULNLZGRMQS4RIZPAZEHYMV4FYHAPW563HNRAOERP7C@test.nodes.vac.dev"
32
- * @param wantedNodeCapabilityCount Specifies what node capabilities
33
- * (protocol) must be returned.
34
- */
35
- constructor(
36
- enrUrl: string,
37
- wantedNodeCapabilityCount: Partial<NodeCapabilityCount>
38
- ) {
39
- super();
40
- this._started = false;
41
- log("Use following EIP-1459 ENR Tree URL: ", enrUrl);
42
-
43
- const dns = DnsNodeDiscovery.dnsOverHttp();
44
-
45
- this.nextPeer = dns.getNextPeer.bind(
46
- {},
47
- [enrUrl],
48
- wantedNodeCapabilityCount
49
- );
50
- }
51
-
52
- /**
53
- * Start discovery process
54
- */
55
- async start(): Promise<void> {
56
- log("Starting peer discovery via dns");
57
-
58
- this._started = true;
59
- for await (const peer of this.nextPeer()) {
60
- if (!this._started) return;
61
- const peerInfos = multiaddrsToPeerInfo(peer.getFullMultiaddrs());
62
- peerInfos.forEach((peerInfo) => {
63
- this.dispatchEvent(
64
- new CustomEvent<PeerInfo>("peer", { detail: peerInfo })
65
- );
66
- });
67
- }
68
- }
69
-
70
- /**
71
- * Stop emitting events
72
- */
73
- stop(): void {
74
- this._started = false;
75
- }
76
-
77
- get [symbol](): true {
78
- return true;
79
- }
80
-
81
- get [Symbol.toStringTag](): string {
82
- return "@waku/bootstrap";
83
- }
84
- }
package/src/lib/utils.ts DELETED
@@ -1,50 +0,0 @@
1
- import { fromString } from "uint8arrays/from-string";
2
- import { toString } from "uint8arrays/to-string";
3
-
4
- /**
5
- * Convert input to a byte array.
6
- *
7
- * Handles both `0x` prefixed and non-prefixed strings.
8
- */
9
- export function hexToBytes(hex: string | Uint8Array): Uint8Array {
10
- if (typeof hex === "string") {
11
- const _hex = hex.replace(/^0x/i, "");
12
- return fromString(_hex.toLowerCase(), "base16");
13
- }
14
- return hex;
15
- }
16
-
17
- /**
18
- * Convert byte array to hex string (no `0x` prefix).
19
- */
20
- export const bytesToHex = (bytes: Uint8Array): string =>
21
- toString(bytes, "base16");
22
-
23
- /**
24
- * Decode byte array to utf-8 string.
25
- */
26
- export const bytesToUtf8 = (b: Uint8Array): string => toString(b, "utf8");
27
-
28
- /**
29
- * Encode utf-8 string to byte array.
30
- */
31
- export const utf8ToBytes = (s: string): Uint8Array => fromString(s, "utf8");
32
-
33
- /**
34
- * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
35
- */
36
- export function concat(
37
- byteArrays: Uint8Array[],
38
- totalLength?: number
39
- ): Uint8Array {
40
- const len =
41
- totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
42
- const res = new Uint8Array(len);
43
-
44
- let offset = 0;
45
- for (const bytes of byteArrays) {
46
- res.set(bytes, offset);
47
- offset += bytes.length;
48
- }
49
- return res;
50
- }
@@ -1,10 +0,0 @@
1
- export const Symmetric = {
2
- keySize: 32,
3
- ivSize: 12,
4
- tagSize: 16,
5
- algorithm: { name: "AES-GCM", length: 128 },
6
- };
7
-
8
- export const Asymmetric = {
9
- keySize: 32,
10
- };
@@ -1,194 +0,0 @@
1
- import * as secp from "@noble/secp256k1";
2
-
3
- import { getSubtle, randomBytes, sha256 } from "../crypto";
4
- import { concat, hexToBytes } from "../utils";
5
- /**
6
- * HKDF as implemented in go-ethereum.
7
- */
8
- function kdf(secret: Uint8Array, outputLength: number): Promise<Uint8Array> {
9
- let ctr = 1;
10
- let written = 0;
11
- let willBeResult = Promise.resolve(new Uint8Array());
12
- while (written < outputLength) {
13
- const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);
14
- const countersSecret = concat(
15
- [counters, secret],
16
- counters.length + secret.length
17
- );
18
- const willBeHashResult = sha256(countersSecret);
19
- willBeResult = willBeResult.then((result) =>
20
- willBeHashResult.then((hashResult) => {
21
- const _hashResult = new Uint8Array(hashResult);
22
- return concat(
23
- [result, _hashResult],
24
- result.length + _hashResult.length
25
- );
26
- })
27
- );
28
- written += 32;
29
- ctr += 1;
30
- }
31
- return willBeResult;
32
- }
33
-
34
- function aesCtrEncrypt(
35
- counter: Uint8Array,
36
- key: ArrayBufferLike,
37
- data: ArrayBufferLike
38
- ): Promise<Uint8Array> {
39
- return getSubtle()
40
- .importKey("raw", key, "AES-CTR", false, ["encrypt"])
41
- .then((cryptoKey) =>
42
- getSubtle().encrypt(
43
- { name: "AES-CTR", counter: counter, length: 128 },
44
- cryptoKey,
45
- data
46
- )
47
- )
48
- .then((bytes) => new Uint8Array(bytes));
49
- }
50
-
51
- function aesCtrDecrypt(
52
- counter: Uint8Array,
53
- key: ArrayBufferLike,
54
- data: ArrayBufferLike
55
- ): Promise<Uint8Array> {
56
- return getSubtle()
57
- .importKey("raw", key, "AES-CTR", false, ["decrypt"])
58
- .then((cryptoKey) =>
59
- getSubtle().decrypt(
60
- { name: "AES-CTR", counter: counter, length: 128 },
61
- cryptoKey,
62
- data
63
- )
64
- )
65
- .then((bytes) => new Uint8Array(bytes));
66
- }
67
-
68
- function hmacSha256Sign(
69
- key: ArrayBufferLike,
70
- msg: ArrayBufferLike
71
- ): PromiseLike<Uint8Array> {
72
- const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
73
- return getSubtle()
74
- .importKey("raw", key, algorithm, false, ["sign"])
75
- .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))
76
- .then((bytes) => new Uint8Array(bytes));
77
- }
78
-
79
- function hmacSha256Verify(
80
- key: ArrayBufferLike,
81
- msg: ArrayBufferLike,
82
- sig: ArrayBufferLike
83
- ): Promise<boolean> {
84
- const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
85
- const _key = getSubtle().importKey("raw", key, algorithm, false, ["verify"]);
86
- return _key.then((cryptoKey) =>
87
- getSubtle().verify(algorithm, cryptoKey, sig, msg)
88
- );
89
- }
90
-
91
- /**
92
- * Derive shared secret for given private and public keys.
93
- *
94
- * @param privateKeyA Sender's private key (32 bytes)
95
- * @param publicKeyB Recipient's public key (65 bytes)
96
- * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)
97
- * @throws Error If arguments are invalid
98
- */
99
- function derive(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array {
100
- if (privateKeyA.length !== 32) {
101
- throw new Error(
102
- `Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`
103
- );
104
- } else if (publicKeyB.length !== 65) {
105
- throw new Error(
106
- `Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`
107
- );
108
- } else if (publicKeyB[0] !== 4) {
109
- throw new Error("Bad public key, a valid public key would begin with 4");
110
- } else {
111
- const px = secp.getSharedSecret(privateKeyA, publicKeyB, true);
112
- // Remove the compression prefix
113
- return new Uint8Array(hexToBytes(px).slice(1));
114
- }
115
- }
116
-
117
- /**
118
- * Encrypt message for given recipient's public key.
119
- *
120
- * @param publicKeyTo Recipient's public key (65 bytes)
121
- * @param msg The message being encrypted
122
- * @return A promise that resolves with the ECIES structure serialized
123
- */
124
- export async function encrypt(
125
- publicKeyTo: Uint8Array,
126
- msg: Uint8Array
127
- ): Promise<Uint8Array> {
128
- const ephemPrivateKey = randomBytes(32);
129
-
130
- const sharedPx = await derive(ephemPrivateKey, publicKeyTo);
131
-
132
- const hash = await kdf(sharedPx, 32);
133
-
134
- const iv = randomBytes(16);
135
- const encryptionKey = hash.slice(0, 16);
136
- const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);
137
-
138
- const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);
139
-
140
- const macKey = await sha256(hash.slice(16));
141
- const hmac = await hmacSha256Sign(macKey, ivCipherText);
142
- const ephemPublicKey = secp.getPublicKey(ephemPrivateKey, false);
143
-
144
- return concat(
145
- [ephemPublicKey, ivCipherText, hmac],
146
- ephemPublicKey.length + ivCipherText.length + hmac.length
147
- );
148
- }
149
-
150
- const metaLength = 1 + 64 + 16 + 32;
151
-
152
- /**
153
- * Decrypt message using given private key.
154
- *
155
- * @param privateKey A 32-byte private key of recipient of the message
156
- * @param encrypted ECIES serialized structure (result of ECIES encryption)
157
- * @returns The clear text
158
- * @throws Error If decryption fails
159
- */
160
- export async function decrypt(
161
- privateKey: Uint8Array,
162
- encrypted: Uint8Array
163
- ): Promise<Uint8Array> {
164
- if (encrypted.length <= metaLength) {
165
- throw new Error(
166
- `Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`
167
- );
168
- } else if (encrypted[0] !== 4) {
169
- throw new Error(
170
- `Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`
171
- );
172
- } else {
173
- // deserialize
174
- const ephemPublicKey = encrypted.slice(0, 65);
175
- const cipherTextLength = encrypted.length - metaLength;
176
- const iv = encrypted.slice(65, 65 + 16);
177
- const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);
178
- const ciphertext = cipherAndIv.slice(16);
179
- const msgMac = encrypted.slice(65 + 16 + cipherTextLength);
180
-
181
- // check HMAC
182
- const px = derive(privateKey, ephemPublicKey);
183
- const hash = await kdf(px, 32);
184
- const [encryptionKey, macKey] = await sha256(hash.slice(16)).then(
185
- (macKey) => [hash.slice(0, 16), macKey]
186
- );
187
-
188
- if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {
189
- throw new Error("Incorrect MAC");
190
- }
191
-
192
- return aesCtrDecrypt(iv, encryptionKey, ciphertext);
193
- }
194
- }
@@ -1,33 +0,0 @@
1
- import { getSubtle, randomBytes } from "../crypto";
2
-
3
- import { Symmetric } from "./constants";
4
-
5
- export async function encrypt(
6
- iv: Uint8Array,
7
- key: Uint8Array,
8
- clearText: Uint8Array
9
- ): Promise<Uint8Array> {
10
- return getSubtle()
11
- .importKey("raw", key, Symmetric.algorithm, false, ["encrypt"])
12
- .then((cryptoKey) =>
13
- getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)
14
- )
15
- .then((cipher) => new Uint8Array(cipher));
16
- }
17
-
18
- export async function decrypt(
19
- iv: Uint8Array,
20
- key: Uint8Array,
21
- cipherText: Uint8Array
22
- ): Promise<Uint8Array> {
23
- return getSubtle()
24
- .importKey("raw", key, Symmetric.algorithm, false, ["decrypt"])
25
- .then((cryptoKey) =>
26
- getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)
27
- )
28
- .then((clear) => new Uint8Array(clear));
29
- }
30
-
31
- export function generateIv(): Uint8Array {
32
- return randomBytes(Symmetric.ivSize);
33
- }