@pkcprotocol/pkc-js 0.0.153 → 0.0.155
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.
- package/README.md +23 -3
- package/dist/browser/clients/rpc-client/schema.js +2 -2
- package/dist/browser/clients/rpc-client/schema.js.map +1 -1
- package/dist/browser/community/remote-community.js +8 -2
- package/dist/browser/community/remote-community.js.map +1 -1
- package/dist/browser/community/schema.js +4 -0
- package/dist/browser/community/schema.js.map +1 -1
- package/dist/browser/community-list/community-list.js +3 -2
- package/dist/browser/community-list/community-list.js.map +1 -1
- package/dist/browser/errors.d.ts +18 -2
- package/dist/browser/errors.js +18 -2
- package/dist/browser/errors.js.map +1 -1
- package/dist/browser/generated-version.d.ts +1 -1
- package/dist/browser/generated-version.js +1 -1
- package/dist/browser/pkc/pkc.js +13 -4
- package/dist/browser/pkc/pkc.js.map +1 -1
- package/dist/browser/pkc-error.d.ts +1 -1
- package/dist/browser/publications/comment/comment.d.ts +1 -0
- package/dist/browser/publications/comment/comment.js +82 -21
- package/dist/browser/publications/comment/comment.js.map +1 -1
- package/dist/browser/publications/comment/crosspost-runtime.js +10 -2
- package/dist/browser/publications/comment/crosspost-runtime.js.map +1 -1
- package/dist/browser/publications/comment/schema.d.ts +1 -1
- package/dist/browser/publications/comment/schema.js +30 -1
- package/dist/browser/publications/comment/schema.js.map +1 -1
- package/dist/browser/publications/publication.d.ts +12 -1
- package/dist/browser/publications/publication.js +511 -167
- package/dist/browser/publications/publication.js.map +1 -1
- package/dist/browser/publications/types.d.ts +1 -0
- package/dist/browser/rpc/src/index.js +15 -8
- package/dist/browser/rpc/src/index.js.map +1 -1
- package/dist/browser/runtime/browser/util.d.ts +3 -1
- package/dist/browser/runtime/browser/util.js +8 -2
- package/dist/browser/runtime/browser/util.js.map +1 -1
- package/dist/browser/runtime/node/blockstore.d.ts +2 -2
- package/dist/browser/runtime/node/blockstore.js +2 -2
- package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js +2 -1
- package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
- package/dist/browser/runtime/node/community/communities-registry.d.ts +96 -0
- package/dist/browser/runtime/node/community/communities-registry.js +964 -0
- package/dist/browser/runtime/node/community/communities-registry.js.map +1 -0
- package/dist/browser/runtime/node/community/db-handler.d.ts +8 -7
- package/dist/browser/runtime/node/community/db-handler.js +128 -84
- package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
- package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
- package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
- package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/editing.js +84 -27
- package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
- package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
- package/dist/browser/runtime/node/community/local-community/lifecycle.js +88 -61
- package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community/publication-validation.d.ts +1 -2
- package/dist/browser/runtime/node/community/local-community/publication-validation.js +23 -0
- package/dist/browser/runtime/node/community/local-community/publication-validation.js.map +1 -1
- package/dist/browser/runtime/node/community/local-community.d.ts +6 -3
- package/dist/browser/runtime/node/community/local-community.js +16 -16
- package/dist/browser/runtime/node/community/local-community.js.map +1 -1
- package/dist/browser/runtime/node/community/pkc-instance-lock.d.ts +17 -0
- package/dist/browser/runtime/node/community/pkc-instance-lock.js +142 -0
- package/dist/browser/runtime/node/community/pkc-instance-lock.js.map +1 -0
- package/dist/browser/runtime/node/storage.js +5 -0
- package/dist/browser/runtime/node/storage.js.map +1 -1
- package/dist/browser/runtime/node/util.d.ts +4 -6
- package/dist/browser/runtime/node/util.js +32 -270
- package/dist/browser/runtime/node/util.js.map +1 -1
- package/dist/browser/schema/schema-util.js +18 -4
- package/dist/browser/schema/schema-util.js.map +1 -1
- package/dist/browser/signer/author-wallet-proof.d.ts +19 -0
- package/dist/browser/signer/author-wallet-proof.js +89 -0
- package/dist/browser/signer/author-wallet-proof.js.map +1 -0
- package/dist/browser/signer/signatures.js +29 -0
- package/dist/browser/signer/signatures.js.map +1 -1
- package/dist/browser/test/test-util.d.ts +12 -0
- package/dist/browser/test/test-util.js +23 -0
- package/dist/browser/test/test-util.js.map +1 -1
- package/dist/browser/unknown-props.d.ts +24 -0
- package/dist/browser/unknown-props.js +95 -0
- package/dist/browser/unknown-props.js.map +1 -0
- package/dist/browser/util.js +7 -0
- package/dist/browser/util.js.map +1 -1
- package/dist/browser/version.js +1 -1
- package/dist/bundled/bundle-manifest.json +47 -49
- package/dist/bundled/challenges.js +1 -1
- package/dist/bundled/chunks/{helia-for-pkc-COJ3xMF9.js → helia-for-pkc-Oiy9zYBR.js} +4 -4
- package/dist/bundled/chunks/{local-community-BTx2HxIm.js → local-community-BlJfnxcr.js} +1 -1
- package/dist/bundled/chunks/{local-community-CflGu_ET.js → local-community-PMJTbzmG.js} +293 -167
- package/dist/bundled/chunks/{node-B0b6lAIX.js → node-Bf1DjAFe.js} +488 -208
- package/dist/bundled/chunks/{page-sort-scoring-DAMnUmDY.js → page-sort-scoring-DVAvzj4W.js} +1 -1
- package/dist/bundled/chunks/{rpc-local-community-Cy03QajY.js → rpc-local-community-BqJ_olvR.js} +4529 -3007
- package/dist/bundled/chunks/{util-C4y8KHmp.js → util-BpiQT2hV.js} +1 -1
- package/dist/bundled/chunks/{util-D7AtfLYH.js → util-N_HlPQHv.js} +66 -18
- package/dist/bundled/chunks/{validate-package-factories-EH9ydbPR.js → validate-package-factories-DoC8xXMu.js} +2 -2
- package/dist/bundled/index.js +1 -1
- package/dist/bundled/page-sorts.js +1 -1
- package/dist/bundled/rpc/src/index.js +15 -11
- package/dist/node/clients/rpc-client/schema.js +2 -2
- package/dist/node/clients/rpc-client/schema.js.map +1 -1
- package/dist/node/community/remote-community.js +8 -2
- package/dist/node/community/remote-community.js.map +1 -1
- package/dist/node/community/schema.js +4 -0
- package/dist/node/community/schema.js.map +1 -1
- package/dist/node/community-list/community-list.js +3 -2
- package/dist/node/community-list/community-list.js.map +1 -1
- package/dist/node/errors.d.ts +18 -2
- package/dist/node/errors.js +18 -2
- package/dist/node/errors.js.map +1 -1
- package/dist/node/generated-version.d.ts +1 -1
- package/dist/node/generated-version.js +1 -1
- package/dist/node/pkc/pkc.js +13 -4
- package/dist/node/pkc/pkc.js.map +1 -1
- package/dist/node/pkc-error.d.ts +1 -1
- package/dist/node/publications/comment/comment.d.ts +1 -0
- package/dist/node/publications/comment/comment.js +82 -21
- package/dist/node/publications/comment/comment.js.map +1 -1
- package/dist/node/publications/comment/crosspost-runtime.js +10 -2
- package/dist/node/publications/comment/crosspost-runtime.js.map +1 -1
- package/dist/node/publications/comment/schema.d.ts +1 -1
- package/dist/node/publications/comment/schema.js +30 -1
- package/dist/node/publications/comment/schema.js.map +1 -1
- package/dist/node/publications/publication.d.ts +12 -1
- package/dist/node/publications/publication.js +511 -167
- package/dist/node/publications/publication.js.map +1 -1
- package/dist/node/publications/types.d.ts +1 -0
- package/dist/node/rpc/src/index.js +15 -8
- package/dist/node/rpc/src/index.js.map +1 -1
- package/dist/node/runtime/browser/util.d.ts +3 -1
- package/dist/node/runtime/browser/util.js +8 -2
- package/dist/node/runtime/browser/util.js.map +1 -1
- package/dist/node/runtime/node/blockstore.d.ts +2 -2
- package/dist/node/runtime/node/blockstore.js +2 -2
- package/dist/node/runtime/node/community/challenges/validate-challenge-result.js +2 -1
- package/dist/node/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
- package/dist/node/runtime/node/community/communities-registry.d.ts +96 -0
- package/dist/node/runtime/node/community/communities-registry.js +964 -0
- package/dist/node/runtime/node/community/communities-registry.js.map +1 -0
- package/dist/node/runtime/node/community/db-handler.d.ts +8 -7
- package/dist/node/runtime/node/community/db-handler.js +128 -84
- package/dist/node/runtime/node/community/db-handler.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
- package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
- package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
- package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/editing.js +84 -27
- package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
- package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
- package/dist/node/runtime/node/community/local-community/lifecycle.js +88 -61
- package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
- package/dist/node/runtime/node/community/local-community/publication-validation.d.ts +1 -2
- package/dist/node/runtime/node/community/local-community/publication-validation.js +23 -0
- package/dist/node/runtime/node/community/local-community/publication-validation.js.map +1 -1
- package/dist/node/runtime/node/community/local-community.d.ts +6 -3
- package/dist/node/runtime/node/community/local-community.js +16 -16
- package/dist/node/runtime/node/community/local-community.js.map +1 -1
- package/dist/node/runtime/node/community/pkc-instance-lock.d.ts +17 -0
- package/dist/node/runtime/node/community/pkc-instance-lock.js +142 -0
- package/dist/node/runtime/node/community/pkc-instance-lock.js.map +1 -0
- package/dist/node/runtime/node/storage.js +5 -0
- package/dist/node/runtime/node/storage.js.map +1 -1
- package/dist/node/runtime/node/util.d.ts +4 -6
- package/dist/node/runtime/node/util.js +32 -270
- package/dist/node/runtime/node/util.js.map +1 -1
- package/dist/node/schema/schema-util.js +18 -4
- package/dist/node/schema/schema-util.js.map +1 -1
- package/dist/node/signer/author-wallet-proof.d.ts +19 -0
- package/dist/node/signer/author-wallet-proof.js +89 -0
- package/dist/node/signer/author-wallet-proof.js.map +1 -0
- package/dist/node/signer/signatures.js +29 -0
- package/dist/node/signer/signatures.js.map +1 -1
- package/dist/node/test/test-util.d.ts +12 -0
- package/dist/node/test/test-util.js +23 -0
- package/dist/node/test/test-util.js.map +1 -1
- package/dist/node/unknown-props.d.ts +24 -0
- package/dist/node/unknown-props.js +95 -0
- package/dist/node/unknown-props.js.map +1 -0
- package/dist/node/util.js +7 -0
- package/dist/node/util.js.map +1 -1
- package/dist/node/version.js +1 -1
- package/package.json +3 -3
- package/dist/browser/runtime/node/community/start-lock.d.ts +0 -8
- package/dist/browser/runtime/node/community/start-lock.js +0 -18
- package/dist/browser/runtime/node/community/start-lock.js.map +0 -1
- package/dist/node/runtime/node/community/start-lock.d.ts +0 -8
- package/dist/node/runtime/node/community/start-lock.js +0 -18
- package/dist/node/runtime/node/community/start-lock.js.map +0 -1
|
@@ -7,6 +7,7 @@ import { deepMergeRuntimeFields, hideClassPrivateProps, isStringDomain, shortify
|
|
|
7
7
|
import { TypedEmitter } from "tiny-typed-emitter";
|
|
8
8
|
import { Comment } from "./comment/comment.js";
|
|
9
9
|
import { PKCError } from "../pkc-error.js";
|
|
10
|
+
import { verifyAuthorWalletEntry } from "../signer/author-wallet-proof.js";
|
|
10
11
|
import { getHeliaDebugContext } from "../helia/util.js";
|
|
11
12
|
import { getBufferedPKCAddressFromPublicKey, getPKCAddressFromPublicKeySync } from "../signer/util.js";
|
|
12
13
|
import * as cborg from "cborg";
|
|
@@ -19,6 +20,9 @@ import { decodeRpcChallengeAnswerPubsubMsg, decodeRpcChallengePubsubMsg, decodeR
|
|
|
19
20
|
import { PublicationClientsManager } from "./publication-client-manager.js";
|
|
20
21
|
import { buildRuntimeAuthor } from "./publication-author.js";
|
|
21
22
|
import { buildRuntimeCommunityFields, getCommunityNameFromWire, normalizeCommunityInputFromCommunity } from "./publication-community.js";
|
|
23
|
+
import { mergeAuthorProps } from "../unknown-props.js";
|
|
24
|
+
// The providerUrl of an exchange whose request went straight to a started local community. It names no pubsub client
|
|
25
|
+
const LOCAL_COMMUNITY_PROVIDER = "publishing directly to local community instance";
|
|
22
26
|
class Publication extends TypedEmitter {
|
|
23
27
|
constructor(pkc) {
|
|
24
28
|
super();
|
|
@@ -30,12 +34,28 @@ class Publication extends TypedEmitter {
|
|
|
30
34
|
// Initialized (not just declared) so hideClassPrivateProps sees it and keeps it out of JSON.
|
|
31
35
|
this._signedWithKnownCommunityFields = undefined;
|
|
32
36
|
this._challengeExchanges = {};
|
|
37
|
+
// A publication instance runs one challenge exchange. It is spent once publish() gets past pre-flight (the community
|
|
38
|
+
// fetch, signing, the signature hook), which is the point from which a request can leave this instance, or once
|
|
39
|
+
// stop() ends a publish() that was called. From then on publish() rejects with
|
|
40
|
+
// ERR_PUBLICATION_PUBLISH_ALREADY_CALLED whatever came of the exchange, and a retry is a new instance. A second
|
|
41
|
+
// exchange on the same instance crossed with the first one's requests, watchdog, verdict and teardown. A publish()
|
|
42
|
+
// that rejected during pre-flight has no exchange to cross with, so it does not spend the instance
|
|
43
|
+
this._isPublishSpent = false;
|
|
44
|
+
// True while a publish() call is running, pre-flight included, so a second call next to it rejects too
|
|
45
|
+
this._isPublishCallRunning = false;
|
|
46
|
+
// What ended this instance's publish: the community's verdict, a failure (no response, every provider threw, an
|
|
47
|
+
// unreadable verification, a request a local community or the RPC server rejected) or stop(). Whichever is recorded
|
|
48
|
+
// first is the end. The others then change nothing, and the work publish() still has awaiting (the community fetch,
|
|
49
|
+
// the RPC publish call, the publish loop, a message being verified or decrypted) stops changing this instance.
|
|
50
|
+
// stop() is not cancellation: without this, an await that resolved after stop() overwrote the stopped states, and a
|
|
51
|
+
// verdict that arrived while a failure was being torn down was written and then overwritten by that failure
|
|
52
|
+
this._publishEndedBy = undefined; // initialised so hideClassPrivateProps hides it
|
|
33
53
|
this._rpcPublishSubscriptionId = undefined;
|
|
34
54
|
this._pkc = pkc;
|
|
35
55
|
this._updatePublishingStateWithEmission("stopped");
|
|
36
56
|
this._setStateWithEmission("stopped");
|
|
37
57
|
this._initClients();
|
|
38
|
-
this._handleChallengeExchange = this._handleChallengeExchange.bind(this);
|
|
58
|
+
this._handleChallengeExchange = this._guardDetachedHandler("_handleChallengeExchange", this._handleChallengeExchange.bind(this));
|
|
39
59
|
this.publish = this.publish.bind(this);
|
|
40
60
|
this.on("error", (...args) => this.listenerCount("error") === 1 && this._pkc.emit("error", ...args)); // only bubble up to pkc if no other listeners are attached
|
|
41
61
|
this._publishToDifferentProviderThresholdSeconds = 10;
|
|
@@ -65,7 +85,16 @@ class Publication extends TypedEmitter {
|
|
|
65
85
|
author: props.author,
|
|
66
86
|
signaturePublicKey: props.signature.publicKey
|
|
67
87
|
});
|
|
68
|
-
|
|
88
|
+
// The author object is signed by whoever published the record: names that mean something to an object
|
|
89
|
+
// (toString, constructor, __proto__, ...) must not become members of comment.author
|
|
90
|
+
const author = {};
|
|
91
|
+
const { skipped } = mergeAuthorProps({
|
|
92
|
+
target: author,
|
|
93
|
+
props: { ...runtimeAuthor, shortAddress: shortifyAddress(runtimeAuthor.address) }
|
|
94
|
+
});
|
|
95
|
+
if (skipped.length > 0)
|
|
96
|
+
Logger("pkc-js:publication:_initAuthor").error("Refused author props of a record that collide with an object", skipped);
|
|
97
|
+
this.author = author;
|
|
69
98
|
this.protocolVersion = props.protocolVersion;
|
|
70
99
|
}
|
|
71
100
|
_initUnsignedLocalProps(opts) {
|
|
@@ -159,38 +188,37 @@ class Publication extends TypedEmitter {
|
|
|
159
188
|
};
|
|
160
189
|
}
|
|
161
190
|
async _handleRpcChallengeVerification(verification, runtimeFields) {
|
|
162
|
-
|
|
163
|
-
if (verification.comment)
|
|
164
|
-
await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
|
|
165
|
-
if (this instanceof Comment && runtimeFields)
|
|
166
|
-
deepMergeRuntimeFields(this, runtimeFields);
|
|
167
|
-
this._setRpcClientState("stopped");
|
|
168
|
-
const newPublishingState = verification.challengeSuccess ? "succeeded" : "failed";
|
|
169
|
-
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
170
|
-
newPublishingState,
|
|
171
|
-
newState: "stopped",
|
|
172
|
-
event: {
|
|
173
|
-
name: "challengeverification",
|
|
174
|
-
args: [verification, this instanceof Comment && verification.comment ? this : undefined]
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
// The exchange is over. This path does its own teardown instead of going through
|
|
178
|
-
// _postSucessOrFailurePublishing, and without this every publication an RPC client verified
|
|
179
|
-
// stayed in pkc._publishingPublications (and in memory) until pkc.destroy(): Comment.stop()
|
|
180
|
-
// only reaches Publication.stop() while publishing, so nothing removed it afterwards
|
|
181
|
-
this._unregisterFromPkcOncePublishWorkSettles();
|
|
182
|
-
if (this._rpcPublishSubscriptionId) {
|
|
183
|
-
// Cleared synchronously before the awaited unsubscribe so the deferred
|
|
184
|
-
// attach-and-replay timer from _publishWithRpc (#314) sees the teardown immediately
|
|
185
|
-
const subscriptionId = this._rpcPublishSubscriptionId;
|
|
186
|
-
this._rpcPublishSubscriptionId = undefined;
|
|
191
|
+
// The caller recorded this verdict as the end of the publish, so it lands also after a stop() during the await below
|
|
192
|
+
if (verification.comment) {
|
|
187
193
|
try {
|
|
188
|
-
await this.
|
|
194
|
+
await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
|
|
189
195
|
}
|
|
190
196
|
catch (e) {
|
|
191
|
-
|
|
197
|
+
Logger("pkc-js:publication:_handleRpcChallengeVerification").error("The comment in a successful challenge verification does not verify", e);
|
|
198
|
+
await this._tearDownThenWriteFailure(e);
|
|
199
|
+
return;
|
|
192
200
|
}
|
|
193
201
|
}
|
|
202
|
+
// The exchange is over. End it through the funnel like the pubsub path does: it unsubscribes, unregisters from
|
|
203
|
+
// pkc._publishingPublications and ends the publish run. In a finally, because the emit runs the listeners of the
|
|
204
|
+
// application and one that throws must not skip it (the throw still reaches _guardDetachedHandler)
|
|
205
|
+
try {
|
|
206
|
+
if (this instanceof Comment && runtimeFields)
|
|
207
|
+
deepMergeRuntimeFields(this, runtimeFields);
|
|
208
|
+
this._setRpcClientState("stopped");
|
|
209
|
+
const newPublishingState = verification.challengeSuccess ? "succeeded" : "failed";
|
|
210
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
211
|
+
newPublishingState,
|
|
212
|
+
newState: "stopped",
|
|
213
|
+
event: {
|
|
214
|
+
name: "challengeverification",
|
|
215
|
+
args: [verification, this instanceof Comment && verification.comment ? this : undefined]
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
await this._tearDownWithoutThrowing();
|
|
221
|
+
}
|
|
194
222
|
}
|
|
195
223
|
async _handleIncomingChallengePubsubMessage(msg) {
|
|
196
224
|
const log = Logger("pkc-js:publication:_handleIncomingChallengePubsubMessage");
|
|
@@ -201,16 +229,17 @@ class Publication extends TypedEmitter {
|
|
|
201
229
|
communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
|
|
202
230
|
validateTimestampRange: true
|
|
203
231
|
});
|
|
232
|
+
if (this._hasPublishEnded())
|
|
233
|
+
return; // ended while the signature was checked
|
|
204
234
|
if (!challengeMsgValidity.valid) {
|
|
205
235
|
const error = new PKCError("ERR_CHALLENGE_SIGNATURE_IS_INVALID", {
|
|
206
236
|
pubsubMsg: msg,
|
|
207
237
|
reason: challengeMsgValidity.reason
|
|
208
238
|
});
|
|
209
|
-
|
|
210
|
-
this
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
});
|
|
239
|
+
// Anyone on the topic can read our challengeRequestId and send a challenge for it. A message the community
|
|
240
|
+
// did not sign says nothing about this exchange, so it is logged and dropped: emitting it as an "error", or
|
|
241
|
+
// moving publishingState to "failed", would let any peer raise errors on a publication that then succeeds
|
|
242
|
+
log.error("Dropping a challenge message with an invalid signature", error.toString());
|
|
214
243
|
return;
|
|
215
244
|
}
|
|
216
245
|
log(`Received encrypted challenges. Will decrypt and emit them on "challenge" event. User shoud publish solution by calling publishChallengeAnswers`);
|
|
@@ -222,6 +251,8 @@ class Publication extends TypedEmitter {
|
|
|
222
251
|
decryptedRawString = await decryptEd25519AesGcm(msg.encrypted, pubsubSigner.privateKey, this._community.encryption.publicKey);
|
|
223
252
|
}
|
|
224
253
|
catch (e) {
|
|
254
|
+
if (this._hasPublishEnded())
|
|
255
|
+
return;
|
|
225
256
|
const pkcError = new PKCError("ERR_PUBLICATION_FAILED_TO_DECRYPT_CHALLENGE", { decryptErr: e });
|
|
226
257
|
log.error("could not decrypt challengemessage.encrypted", pkcError.toString());
|
|
227
258
|
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
@@ -235,6 +266,8 @@ class Publication extends TypedEmitter {
|
|
|
235
266
|
decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
|
|
236
267
|
}
|
|
237
268
|
catch (e) {
|
|
269
|
+
if (this._hasPublishEnded())
|
|
270
|
+
return;
|
|
238
271
|
log.error("could not parse decrypted challengemessage.encrypted as a json", String(e));
|
|
239
272
|
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
240
273
|
newPublishingState: "failed",
|
|
@@ -247,6 +280,8 @@ class Publication extends TypedEmitter {
|
|
|
247
280
|
decryptedChallenge = parseDecryptedChallengeWithPKCErrorIfItFails(decryptedJson);
|
|
248
281
|
}
|
|
249
282
|
catch (e) {
|
|
283
|
+
if (this._hasPublishEnded())
|
|
284
|
+
return;
|
|
250
285
|
log.error("could not parse z challengemessage.encrypted as a json", String(e));
|
|
251
286
|
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
252
287
|
newPublishingState: "failed",
|
|
@@ -266,6 +301,8 @@ class Publication extends TypedEmitter {
|
|
|
266
301
|
log.trace("Received a copy of a challenge that was already handled, ignoring it");
|
|
267
302
|
return;
|
|
268
303
|
}
|
|
304
|
+
if (this._hasPublishEnded())
|
|
305
|
+
return; // ended while it was decrypted
|
|
269
306
|
this._challengeExchanges[msg.challengeRequestId.toString()].challenge = decryptedChallengeMsg;
|
|
270
307
|
this._updatePublishingStateWithEmission("waiting-challenge-answers");
|
|
271
308
|
const challengeTopic = this._community?.pubsubTopic;
|
|
@@ -284,16 +321,16 @@ class Publication extends TypedEmitter {
|
|
|
284
321
|
communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
|
|
285
322
|
validateTimestampRange: true
|
|
286
323
|
});
|
|
324
|
+
if (this._hasPublishEnded())
|
|
325
|
+
return; // ended while the signature was checked
|
|
287
326
|
if (!signatureValidation.valid) {
|
|
288
327
|
const error = new PKCError("ERR_CHALLENGE_VERIFICATION_SIGNATURE_IS_INVALID", {
|
|
289
328
|
pubsubMsg: msg,
|
|
290
329
|
reason: signatureValidation.reason
|
|
291
330
|
});
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
event: { name: "error", args: [error] }
|
|
296
|
-
});
|
|
331
|
+
// Like an invalid challenge: anyone on the topic can send one for our challengeRequestId, and it is not the
|
|
332
|
+
// community's verdict, so it is logged and dropped
|
|
333
|
+
log.error("Dropping a challenge verification with an invalid signature", error);
|
|
297
334
|
return;
|
|
298
335
|
}
|
|
299
336
|
let decryptedChallengeVerification;
|
|
@@ -315,7 +352,7 @@ class Publication extends TypedEmitter {
|
|
|
315
352
|
challenegVerificationMsg: msg
|
|
316
353
|
});
|
|
317
354
|
log.error("could not decrypt challengeverification.encrypted", pkcError);
|
|
318
|
-
this.
|
|
355
|
+
await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: pkcError });
|
|
319
356
|
return;
|
|
320
357
|
}
|
|
321
358
|
let decryptedJson;
|
|
@@ -324,7 +361,7 @@ class Publication extends TypedEmitter {
|
|
|
324
361
|
}
|
|
325
362
|
catch (e) {
|
|
326
363
|
log.error("could not parse decrypted challengeverification.encrypted as a json", e);
|
|
327
|
-
this.
|
|
364
|
+
await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: e });
|
|
328
365
|
return;
|
|
329
366
|
}
|
|
330
367
|
try {
|
|
@@ -332,7 +369,7 @@ class Publication extends TypedEmitter {
|
|
|
332
369
|
}
|
|
333
370
|
catch (e) {
|
|
334
371
|
log.error("could not parse challengeverification.encrypted due to invalid schema", e);
|
|
335
|
-
this.
|
|
372
|
+
await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: e });
|
|
336
373
|
return;
|
|
337
374
|
}
|
|
338
375
|
}
|
|
@@ -352,21 +389,84 @@ class Publication extends TypedEmitter {
|
|
|
352
389
|
log.trace("Received a copy of a challenge verification that was already handled, ignoring it");
|
|
353
390
|
return;
|
|
354
391
|
}
|
|
392
|
+
// The verdict is the end of this publish unless a failure or stop() ended it while it was being decrypted. Once
|
|
393
|
+
// recorded it lands, also if stop() runs during the awaits below
|
|
394
|
+
if (!this._claimPublishEnd("verification"))
|
|
395
|
+
return;
|
|
355
396
|
this._challengeExchanges[msg.challengeRequestId.toString()].challengeVerification = challengeVerificationMsg;
|
|
356
397
|
if (decryptedChallengeVerification?.comment) {
|
|
357
|
-
|
|
398
|
+
try {
|
|
399
|
+
await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
|
|
400
|
+
}
|
|
401
|
+
catch (e) {
|
|
402
|
+
log.error("The comment in a successful challenge verification does not verify", e);
|
|
403
|
+
await this._tearDownThenWriteFailure(e);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
358
406
|
log("Updated the props of this instance with challengeverification.encrypted");
|
|
359
407
|
}
|
|
360
|
-
|
|
408
|
+
// The emit runs the listeners of the application, and one that throws must not leave the exchange subscribed and
|
|
409
|
+
// the publication registered, so the teardown that ends the publish is in a finally. The throw itself still
|
|
410
|
+
// reaches _guardDetachedHandler, which reports it
|
|
411
|
+
try {
|
|
412
|
+
Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
|
|
413
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
414
|
+
newPublishingState,
|
|
415
|
+
newState: "stopped",
|
|
416
|
+
event: {
|
|
417
|
+
name: "challengeverification",
|
|
418
|
+
args: [challengeVerificationMsg, this instanceof Comment && decryptedChallengeVerification ? this : undefined]
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
finally {
|
|
423
|
+
await this._tearDownWithoutThrowing();
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
// A success verification the community signed but whose encrypted part we cannot read. The exchange is over and the
|
|
427
|
+
// no-response watchdog stopped watching once the challenge arrived, so end it here rather than stay "publishing" and
|
|
428
|
+
// subscribed for good. It ends as failed: we cannot see what the community stored, so there is no result (for a
|
|
429
|
+
// comment, not even its cid) to report as succeeded
|
|
430
|
+
async _endExchangeWithUnreadableChallengeVerification({ verification, error }) {
|
|
431
|
+
const exchange = this._challengeExchanges[verification.challengeRequestId.toString()];
|
|
432
|
+
// A copy delivered by another provider ended it already (#349), or a failure or stop() did while it was decrypted
|
|
433
|
+
if (exchange.challengeVerification || this._hasPublishEnded())
|
|
434
|
+
return;
|
|
435
|
+
exchange.challengeVerification = verification;
|
|
436
|
+
await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
437
|
+
newPublishingState: "failed",
|
|
438
|
+
event: { name: "error", args: [error] }
|
|
439
|
+
}));
|
|
440
|
+
}
|
|
441
|
+
_claimPublishEnd(endedBy) {
|
|
442
|
+
if (this._publishEndedBy)
|
|
443
|
+
return false;
|
|
444
|
+
this._publishEndedBy = endedBy;
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
// Asked by the work a publish() started, after each of its awaits, and by the handlers of incoming messages
|
|
448
|
+
_hasPublishEnded() {
|
|
449
|
+
return this._publishEndedBy !== undefined || this._pkc.destroyed;
|
|
450
|
+
}
|
|
451
|
+
// Ends the publish as a failure, unless a verdict or stop() already ended it: then nothing is written and undefined is
|
|
452
|
+
// returned. The teardown comes first and awaits an unsubscribe, during which the subscription still delivers. The end
|
|
453
|
+
// is recorded before it, so a verdict that arrives in that window is dropped instead of being written and then
|
|
454
|
+
// overwritten by writeFailure, which writes "failed" and emits the error
|
|
455
|
+
async _endPublishWithFailure(writeFailure) {
|
|
456
|
+
if (!this._claimPublishEnd("failure"))
|
|
457
|
+
return undefined;
|
|
458
|
+
await this._postSucessOrFailurePublishing();
|
|
459
|
+
return writeFailure();
|
|
460
|
+
}
|
|
461
|
+
// For a success verification that was recorded as the end of the publish and then turns out to be unusable: the
|
|
462
|
+
// comment the community returned does not verify. Like a verification that cannot be read, there is no result to
|
|
463
|
+
// report as succeeded, and nothing else would end the publication, which stayed "publishing" and subscribed
|
|
464
|
+
async _tearDownThenWriteFailure(error) {
|
|
465
|
+
await this._tearDownWithoutThrowing();
|
|
361
466
|
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
362
|
-
newPublishingState,
|
|
363
|
-
|
|
364
|
-
event: {
|
|
365
|
-
name: "challengeverification",
|
|
366
|
-
args: [challengeVerificationMsg, this instanceof Comment && decryptedChallengeVerification ? this : undefined]
|
|
367
|
-
}
|
|
467
|
+
newPublishingState: "failed",
|
|
468
|
+
event: { name: "error", args: [error] }
|
|
368
469
|
});
|
|
369
|
-
await this._postSucessOrFailurePublishing();
|
|
370
470
|
}
|
|
371
471
|
async _handleChallengeExchange(pubsubMsg) {
|
|
372
472
|
const log = Logger("pkc-js:publication:handleChallengeExchange");
|
|
@@ -433,6 +533,15 @@ class Publication extends TypedEmitter {
|
|
|
433
533
|
challengeAnswers: toEncryptAnswers.challengeAnswers
|
|
434
534
|
});
|
|
435
535
|
}
|
|
536
|
+
// A verdict, a failure or stop() ended the exchange: an answer published now would reach nobody who is waiting
|
|
537
|
+
// for it, and used to move a stopped publication to "waiting-challenge-verification"
|
|
538
|
+
if (this._publishEndedBy)
|
|
539
|
+
throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
|
|
540
|
+
publicationType: this.getType(),
|
|
541
|
+
state: this.state,
|
|
542
|
+
publishingState: this.publishingState,
|
|
543
|
+
endedBy: this._publishEndedBy
|
|
544
|
+
});
|
|
436
545
|
const challengeExchangesWithChallenge = Object.values(this._challengeExchanges).filter((exchange) => exchange.challenge);
|
|
437
546
|
if (challengeExchangesWithChallenge.length === 0)
|
|
438
547
|
throw Error("No challenge exchanges with challenge");
|
|
@@ -474,9 +583,24 @@ class Publication extends TypedEmitter {
|
|
|
474
583
|
challengeExchange.challengeAnswerPublishInFlight = false;
|
|
475
584
|
throw e;
|
|
476
585
|
}
|
|
586
|
+
const throwIfExchangeEnded = () => {
|
|
587
|
+
if (!this._publishEndedBy)
|
|
588
|
+
return;
|
|
589
|
+
challengeExchange.challengeAnswerPublishInFlight = false;
|
|
590
|
+
throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
|
|
591
|
+
publicationType: this.getType(),
|
|
592
|
+
state: this.state,
|
|
593
|
+
publishingState: this.publishingState,
|
|
594
|
+
endedBy: this._publishEndedBy
|
|
595
|
+
});
|
|
596
|
+
};
|
|
597
|
+
// The exchange can have ended while the answer was being encrypted and signed
|
|
598
|
+
throwIfExchangeEnded();
|
|
477
599
|
// TODO should be handling multiple providers with publishing challenge answer?
|
|
478
600
|
// For now, let's just publish to the provider that got us the challenge and its request
|
|
479
601
|
this._updatePublishingStateWithEmission("publishing-challenge-answer");
|
|
602
|
+
// A publishingstatechange listener can have called stop() for the state just emitted
|
|
603
|
+
throwIfExchangeEnded();
|
|
480
604
|
this._updatePubsubState("publishing-challenge-answer", challengeExchange.providerUrl);
|
|
481
605
|
if (this._publishingToLocalCommunity) {
|
|
482
606
|
try {
|
|
@@ -486,8 +610,11 @@ class Publication extends TypedEmitter {
|
|
|
486
610
|
this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError =
|
|
487
611
|
e;
|
|
488
612
|
challengeExchange.challengeAnswerPublishInFlight = false;
|
|
489
|
-
|
|
490
|
-
this.
|
|
613
|
+
// Not when the publish ended while the answer was being published: that end settled the states
|
|
614
|
+
if (!this._publishEndedBy) {
|
|
615
|
+
this._updatePublishingStateWithEmission("failed");
|
|
616
|
+
this._updatePubsubState("stopped", challengeExchange.providerUrl);
|
|
617
|
+
}
|
|
491
618
|
throw e;
|
|
492
619
|
}
|
|
493
620
|
}
|
|
@@ -499,8 +626,11 @@ class Publication extends TypedEmitter {
|
|
|
499
626
|
this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError =
|
|
500
627
|
e;
|
|
501
628
|
challengeExchange.challengeAnswerPublishInFlight = false;
|
|
502
|
-
|
|
503
|
-
this.
|
|
629
|
+
// Not when the publish ended while the answer was being published: that end settled the states
|
|
630
|
+
if (!this._publishEndedBy) {
|
|
631
|
+
this._updatePublishingStateWithEmission("failed");
|
|
632
|
+
this._updatePubsubState("stopped", challengeExchange.providerUrl);
|
|
633
|
+
}
|
|
504
634
|
throw e;
|
|
505
635
|
}
|
|
506
636
|
}
|
|
@@ -512,12 +642,18 @@ class Publication extends TypedEmitter {
|
|
|
512
642
|
decryptedChallengeAnswer;
|
|
513
643
|
this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishTimestamp =
|
|
514
644
|
timestamp();
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
645
|
+
// stop() ran while the answer was being published: the publication is stopped and waits for nothing
|
|
646
|
+
if (this._publishEndedBy === "stop")
|
|
647
|
+
return;
|
|
648
|
+
// A verdict that was recorded meanwhile already wrote the final states
|
|
649
|
+
if (!this._publishEndedBy) {
|
|
650
|
+
this._updatePublishingStateWithEmission("waiting-challenge-verification");
|
|
651
|
+
const challengeTopic = this._community?.pubsubTopic;
|
|
652
|
+
const providers = Object.entries(this._clientsManager.pubsubProviderSubscriptions)
|
|
653
|
+
.filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic))
|
|
654
|
+
.map(([provider]) => provider);
|
|
655
|
+
providers.forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
|
|
656
|
+
}
|
|
521
657
|
log(`Responded to challenge with answers`, challengeAnswers);
|
|
522
658
|
this.emit("challengeanswer", decryptedChallengeAnswer);
|
|
523
659
|
}
|
|
@@ -529,6 +665,24 @@ class Publication extends TypedEmitter {
|
|
|
529
665
|
if (typeof this.communityAddress !== "string")
|
|
530
666
|
throw new PKCError("ERR_PUBLICATION_MISSING_FIELD", { type: this.getType(), communityAddress: this.communityAddress });
|
|
531
667
|
}
|
|
668
|
+
// BSIP-22: run the check a community runs on acceptance before the exchange starts, so an author with an
|
|
669
|
+
// invalid wallet entry gets a clear error here instead of a rejection from the community. Reads the signed wire record, not the runtime fields, so it checks exactly what is sent.
|
|
670
|
+
_validateAuthorWalletProofs() {
|
|
671
|
+
const signed = this.raw.pubsubMessageToPublish;
|
|
672
|
+
const wallets = signed?.author?.wallets;
|
|
673
|
+
if (!wallets || !signed?.signature?.publicKey)
|
|
674
|
+
return;
|
|
675
|
+
const authorPublicKey = getPKCAddressFromPublicKeySync(signed.signature.publicKey);
|
|
676
|
+
for (const [chainTicker, entry] of Object.entries(wallets)) {
|
|
677
|
+
const result = verifyAuthorWalletEntry({ entry, authorPublicKey, nowSeconds: timestamp() });
|
|
678
|
+
if (result.outcome === "invalid") {
|
|
679
|
+
// Nothing was sent and the instance is not spent. Leave "publishing" unless stop() already ended the attempt
|
|
680
|
+
if (this.state === "publishing")
|
|
681
|
+
this._setStateWithEmission("stopped");
|
|
682
|
+
throw new PKCError("ERR_AUTHOR_WALLET_PROOF_IS_INVALID", { chainTicker, reason: result.reason, entry });
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
532
686
|
_validateCommunityFields() {
|
|
533
687
|
if (typeof this._community?.encryption?.publicKey !== "string")
|
|
534
688
|
throw new PKCError("ERR_COMMUNITY_MISSING_FIELD", { communityPublicKey: this._community?.encryption?.publicKey });
|
|
@@ -626,9 +780,12 @@ class Publication extends TypedEmitter {
|
|
|
626
780
|
// goes on to use it for update() after being stopped.
|
|
627
781
|
async _cancelBackgroundCommunityRefresh() {
|
|
628
782
|
this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", { publicationType: this.getType(), communityAddress: this.communityAddress }));
|
|
629
|
-
|
|
630
|
-
|
|
783
|
+
// Reset before the drain, not after it: the refresh keeps the aborted signal it was given, and a publish() or
|
|
784
|
+
// update() called right after a stop() that was not awaited must not be handed that aborted signal
|
|
785
|
+
const refresh = this._backgroundCommunityRefresh;
|
|
631
786
|
this._resetCommunityFetchAbortSignal();
|
|
787
|
+
if (refresh)
|
|
788
|
+
await refresh;
|
|
632
789
|
}
|
|
633
790
|
_resetCommunityFetchAbortSignal() {
|
|
634
791
|
this._communityFetchAbortController = undefined;
|
|
@@ -647,12 +804,6 @@ class Publication extends TypedEmitter {
|
|
|
647
804
|
this._beginPublishRun();
|
|
648
805
|
return this._publishRunWaitSignal;
|
|
649
806
|
}
|
|
650
|
-
// True once the run that handed out runSignal is over. Takes the run's own signal, not the current
|
|
651
|
-
// controller: stop() followed by publish() in the same tick installs the next run's controller before
|
|
652
|
-
// the previous run's waits wake up, and they must still see their own run as over
|
|
653
|
-
_isPublishRunOver(runSignal) {
|
|
654
|
-
return this._pkc.destroyed || runSignal.aborted;
|
|
655
|
-
}
|
|
656
807
|
// Fresh cache entry first, then a community instance this PKC keeps updating or running (its own loop
|
|
657
808
|
// keeps the record current), then a stale cache entry, which _fetchCommunityForPublishing refreshes
|
|
658
809
|
_getCommunityCache() {
|
|
@@ -741,10 +892,20 @@ class Publication extends TypedEmitter {
|
|
|
741
892
|
return this._clientsManager.fetchCommunityForPublishingWithCacheGuard();
|
|
742
893
|
}
|
|
743
894
|
async stop() {
|
|
895
|
+
// Ends the publish, unless a verdict or a failure already did: that end still lands, with its own final
|
|
896
|
+
// publishingState, which this stop() must not replace with "stopped". An instance that was never published has no
|
|
897
|
+
// publish to end and stays publishable
|
|
898
|
+
const wasPublishCalled = this._isPublishSpent || this._isPublishCallRunning;
|
|
899
|
+
if (wasPublishCalled)
|
|
900
|
+
this._isPublishSpent = true; // also a publish() that stop() catches in pre-flight
|
|
901
|
+
const endedByThisStop = wasPublishCalled ? this._claimPublishEnd("stop") : true;
|
|
744
902
|
// Abort first, so the drain below unwinds an in-flight fetch instead of waiting it out. Only
|
|
745
903
|
// stop() does this, never the success funnel: a refresh fired to warm a stale cache should
|
|
746
904
|
// still finish after a publish succeeds.
|
|
747
905
|
this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", { publicationType: this.getType(), communityAddress: this.communityAddress }));
|
|
906
|
+
// With no publish to end, a publish() may follow this stop() before it resolves, and it needs a live signal
|
|
907
|
+
if (!wasPublishCalled)
|
|
908
|
+
this._resetCommunityFetchAbortSignal();
|
|
748
909
|
try {
|
|
749
910
|
await this._postSucessOrFailurePublishing();
|
|
750
911
|
}
|
|
@@ -754,17 +915,22 @@ class Publication extends TypedEmitter {
|
|
|
754
915
|
// fast. In a finally because pkc.destroy() catches a rejecting stop() and then clears
|
|
755
916
|
// _publishingPublications, so a cleanup failure would otherwise leave the refresh
|
|
756
917
|
// running past teardown, which is the exact thing this is here to prevent.
|
|
757
|
-
|
|
918
|
+
// Only a publish this stop() ended has a refresh to drain: one that started since is not this stop()'s to wait for
|
|
919
|
+
if (wasPublishCalled && this._backgroundCommunityRefresh)
|
|
758
920
|
await this._backgroundCommunityRefresh;
|
|
759
|
-
|
|
921
|
+
// A stop() that had no publish to end leaves a publish() that started since alone
|
|
922
|
+
const publishStartedSinceThisStop = !wasPublishCalled && (this._isPublishSpent || this._isPublishCallRunning);
|
|
923
|
+
if (endedByThisStop && !publishStartedSinceThisStop)
|
|
924
|
+
this._updatePublishingStateWithEmission("stopped");
|
|
760
925
|
}
|
|
761
926
|
}
|
|
762
927
|
_isAllAttemptsExhausted(maxNumOfChallengeExchanges) {
|
|
763
928
|
// When all providers failed to publish
|
|
764
929
|
// OR they're done with waiting
|
|
765
|
-
|
|
930
|
+
const challengeExchanges = Object.values(this._challengeExchanges);
|
|
931
|
+
if (challengeExchanges.length !== maxNumOfChallengeExchanges)
|
|
766
932
|
return false;
|
|
767
|
-
return
|
|
933
|
+
return challengeExchanges.every((exchange) => {
|
|
768
934
|
// An exchange that received a challenge or a verification is alive: the community is
|
|
769
935
|
// talking to us on it, however old its request is. Request age only measures silence
|
|
770
936
|
// (issue #340).
|
|
@@ -788,8 +954,9 @@ class Publication extends TypedEmitter {
|
|
|
788
954
|
// re-established a subscription after teardown already ran its unsubscribe, so returning
|
|
789
955
|
// without undoing it leaves it dangling on the provider. Returns true when the caller should
|
|
790
956
|
// abandon this provider (issue #270).
|
|
957
|
+
// The same holds when the publish ended any other way while subscribing (a verdict on an earlier provider's request).
|
|
791
958
|
async _abandonProviderIfStoppedWhileSubscribing(providerUrl) {
|
|
792
|
-
if (!this.
|
|
959
|
+
if (!this._hasPublishEnded() && this.state !== "stopped")
|
|
793
960
|
return false;
|
|
794
961
|
const log = Logger("pkc-js:publication:publish:_abandonProviderIfStoppedWhileSubscribing");
|
|
795
962
|
log("Publication was stopped while subscribing to pubsub, will not publish a challenge request", providerUrl);
|
|
@@ -813,11 +980,67 @@ class Publication extends TypedEmitter {
|
|
|
813
980
|
else
|
|
814
981
|
this._pkc._publishingPublications.delete(this);
|
|
815
982
|
}
|
|
983
|
+
// Wraps an entry point nothing awaits (a pubsub or RPC subscription handler, a listener on a local community):
|
|
984
|
+
// a throw there is an unhandled rejection, which ends a Node process, and with it every other publication,
|
|
985
|
+
// community and RPC client it serves. The wrapper turns the throw into the end of this one publication.
|
|
986
|
+
_guardDetachedHandler(entryPoint, handler) {
|
|
987
|
+
return async (...args) => {
|
|
988
|
+
try {
|
|
989
|
+
await handler(...args);
|
|
990
|
+
}
|
|
991
|
+
catch (e) {
|
|
992
|
+
await this._endPublicationAfterDetachedFailure(entryPoint, e);
|
|
993
|
+
}
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
// Never throws: it runs where a throw would be fatal. Before an end nothing can recover the exchange, so the
|
|
997
|
+
// publication fails (first end wins, see _claimPublishEnd). After a verdict its outcome stands and the error is
|
|
998
|
+
// only reported. After stop() the caller has left, so it is only logged.
|
|
999
|
+
async _endPublicationAfterDetachedFailure(entryPoint, cause) {
|
|
1000
|
+
const log = Logger("pkc-js:publication:_endPublicationAfterDetachedFailure");
|
|
1001
|
+
log.error(`Handler ${entryPoint} of a publication threw`, cause);
|
|
1002
|
+
const error = new PKCError("ERR_PUBLICATION_INTERNAL_ERROR", { entryPoint, cause });
|
|
1003
|
+
const endedBefore = this._publishEndedBy;
|
|
1004
|
+
const failsThePublication = this._claimPublishEnd("failure");
|
|
1005
|
+
try {
|
|
1006
|
+
if (failsThePublication) {
|
|
1007
|
+
try {
|
|
1008
|
+
await this._postSucessOrFailurePublishing();
|
|
1009
|
+
}
|
|
1010
|
+
catch (teardownError) {
|
|
1011
|
+
log.error(`Teardown after the failure of ${entryPoint} threw as well`, teardownError);
|
|
1012
|
+
}
|
|
1013
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1014
|
+
newPublishingState: "failed",
|
|
1015
|
+
event: { name: "error", args: [error] }
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
else if (endedBefore !== "stop")
|
|
1019
|
+
this.emit("error", error);
|
|
1020
|
+
}
|
|
1021
|
+
catch (emitError) {
|
|
1022
|
+
// an "error" emit throws when nothing listens to it; the process must outlive that too
|
|
1023
|
+
log.error(`Could not report the failure of ${entryPoint}`, emitError);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
// For the places that end a publish after its verdict: a teardown that rejects must not replace the error the caller is
|
|
1027
|
+
// already propagating (a listener of the application that threw), and must not stop the failure from being written
|
|
1028
|
+
async _tearDownWithoutThrowing() {
|
|
1029
|
+
try {
|
|
1030
|
+
await this._postSucessOrFailurePublishing();
|
|
1031
|
+
}
|
|
1032
|
+
catch (teardownError) {
|
|
1033
|
+
Logger("pkc-js:publication:_tearDownWithoutThrowing").error("The teardown that ends the publish threw", teardownError);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
816
1036
|
async _postSucessOrFailurePublishing() {
|
|
817
1037
|
const log = Logger("pkc-js:publication:_postSucessOrFailurePublishing");
|
|
818
1038
|
this._publishRunAbortController?.abort();
|
|
819
1039
|
this._unregisterFromPkcOncePublishWorkSettles();
|
|
820
|
-
|
|
1040
|
+
// Only a publication that is still publishing. After a verdict the state is "stopped" already, and a listener of
|
|
1041
|
+
// that verdict may have started the comment's update loop since ("updating"), which this must not undo
|
|
1042
|
+
if (this.state === "publishing")
|
|
1043
|
+
this._setStateWithEmission("stopped");
|
|
821
1044
|
if (this._rpcPublishSubscriptionId) {
|
|
822
1045
|
// Cleared synchronously before the awaited unsubscribe so the deferred
|
|
823
1046
|
// attach-and-replay timer from _publishWithRpc (#314) sees the teardown immediately
|
|
@@ -875,6 +1098,10 @@ class Publication extends TypedEmitter {
|
|
|
875
1098
|
async _handleIncomingChallengeVerificationFromRpc(args) {
|
|
876
1099
|
const { challengeVerification: encoded, runtimeFields } = args.params.result;
|
|
877
1100
|
const decoded = decodeRpcChallengeVerificationPubsubMsg(encoded);
|
|
1101
|
+
// The verdict is the end of this publish, unless a failure the server reported (or stop()) already ended it and is
|
|
1102
|
+
// still unsubscribing: this subscription delivers until the server answers that call
|
|
1103
|
+
if (!this._claimPublishEnd("verification"))
|
|
1104
|
+
return;
|
|
878
1105
|
this._challengeExchanges[decoded.challengeRequestId.toString()] = {
|
|
879
1106
|
...this._challengeExchanges[decoded.challengeRequestId.toString()],
|
|
880
1107
|
challengeVerification: decoded
|
|
@@ -895,12 +1122,30 @@ class Publication extends TypedEmitter {
|
|
|
895
1122
|
async _handleIncomingErrorFromRpc(args) {
|
|
896
1123
|
const log = Logger("pkc-js:publication:publish:_publishWithRpc:_handleIncomingErrorFromRpc");
|
|
897
1124
|
const error = args.params.result;
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
1125
|
+
// The server's publish() threw, or its publication stopped with this error: either way the publish ended there, so
|
|
1126
|
+
// end it here too, or this instance stays publishing, registered and subscribed until stop(). An error that left
|
|
1127
|
+
// the server's publication publishing (a challenge answer that could not be published) is one the caller can
|
|
1128
|
+
// still act on
|
|
1129
|
+
const endedOnServer = error.details?.publishThrowError || error.details?.newState === "stopped";
|
|
1130
|
+
if (endedOnServer) {
|
|
1131
|
+
if (!this._claimPublishEnd("failure")) {
|
|
1132
|
+
// A verdict or stop() already ended it. An error the server only emitted is still the caller's to see
|
|
1133
|
+
if (!error.details?.publishThrowError)
|
|
1134
|
+
this.emit("error", error);
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
log.error("The publication failed on the RPC server, will stop publication", error);
|
|
902
1138
|
await this._postSucessOrFailurePublishing();
|
|
1139
|
+
// The error first, then the state change, the order a publication emits them in. The server's own state
|
|
1140
|
+
// change follows its error and is ignored from here on (see _publishWithRpc)
|
|
1141
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1142
|
+
newPublishingState: error.details?.newPublishingState ?? "failed",
|
|
1143
|
+
event: { name: "error", args: [error] }
|
|
1144
|
+
});
|
|
1145
|
+
return;
|
|
903
1146
|
}
|
|
1147
|
+
if (error.details?.newPublishingState)
|
|
1148
|
+
this._updatePublishingStateNoEmission(error.details.newPublishingState);
|
|
904
1149
|
this.emit("error", error);
|
|
905
1150
|
}
|
|
906
1151
|
async _publishWithRpc() {
|
|
@@ -919,7 +1164,28 @@ class Publication extends TypedEmitter {
|
|
|
919
1164
|
// Each publish method expects its specific type, but toJSONPubsubRequestToEncrypt() returns the correct shape at runtime
|
|
920
1165
|
const publishFn = pubNameToPublishFunction[this.getType()];
|
|
921
1166
|
const { subscriptionId } = await publishFn.bind(rpcClient)(this.toJSONPubsubRequestToEncrypt());
|
|
1167
|
+
if (this._hasPublishEnded()) {
|
|
1168
|
+
// stop() ran while the server was starting this publish and found no subscription id to unsubscribe. The
|
|
1169
|
+
// server answers only after its publish() started, so drop the subscription here or its events reach a
|
|
1170
|
+
// stopped instance that nothing tracks any more
|
|
1171
|
+
try {
|
|
1172
|
+
await rpcClient.unsubscribe(subscriptionId);
|
|
1173
|
+
}
|
|
1174
|
+
catch (e) {
|
|
1175
|
+
Logger("pkc-js:publication:publish:_publishWithRpc").error("Failed to unsubscribe from a publish stopped while starting", e);
|
|
1176
|
+
}
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
922
1179
|
this._rpcPublishSubscriptionId = subscriptionId;
|
|
1180
|
+
// The RPC client removes these handlers only once an unsubscribe call returns, so the subscription still delivers
|
|
1181
|
+
// events after stop(), while its unsubscribe is pending. Like the pubsub messages of a stopped publication, they
|
|
1182
|
+
// are ignored: a verdict used to land on the stopped publication
|
|
1183
|
+
// The same goes for a publish that failed: the server's remaining events, such as the state change that follows
|
|
1184
|
+
// its error, would land in the middle of the teardown or after it
|
|
1185
|
+
const unlessStopped = (handler) => (args) => {
|
|
1186
|
+
if (this._publishEndedBy !== "stop" && this._publishEndedBy !== "failure")
|
|
1187
|
+
return handler(args);
|
|
1188
|
+
};
|
|
923
1189
|
// Deferred so a listener attached synchronously after `await publish()` resolves still
|
|
924
1190
|
// receives events the server emitted before the publish response (#314); see
|
|
925
1191
|
// attachSubscriptionHandlersDeferred for the mechanism
|
|
@@ -927,13 +1193,13 @@ class Publication extends TypedEmitter {
|
|
|
927
1193
|
subscriptionId,
|
|
928
1194
|
isStale: () => this._rpcPublishSubscriptionId !== subscriptionId,
|
|
929
1195
|
attach: (subscription) => subscription
|
|
930
|
-
.on("challengerequest", this._handleIncomingChallengeRequestFromRpc.bind(this))
|
|
931
|
-
.on("challenge", this._handleIncomingChallengeFromRpc.bind(this))
|
|
932
|
-
.on("challengeanswer", this._handleIncomingChallengeAnswerFromRpc.bind(this))
|
|
933
|
-
.on("challengeverification", this._handleIncomingChallengeVerificationFromRpc.bind(this))
|
|
934
|
-
.on("publishingstatechange", this._handleIncomingPublishingStateFromRpc.bind(this))
|
|
935
|
-
.on("statechange", this._handleIncomingStateFromRpc.bind(this))
|
|
936
|
-
.on("error", this._handleIncomingErrorFromRpc.bind(this)),
|
|
1196
|
+
.on("challengerequest", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeRequestFromRpc", this._handleIncomingChallengeRequestFromRpc.bind(this))))
|
|
1197
|
+
.on("challenge", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeFromRpc", this._handleIncomingChallengeFromRpc.bind(this))))
|
|
1198
|
+
.on("challengeanswer", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeAnswerFromRpc", this._handleIncomingChallengeAnswerFromRpc.bind(this))))
|
|
1199
|
+
.on("challengeverification", unlessStopped(this._guardDetachedHandler("_handleIncomingChallengeVerificationFromRpc", this._handleIncomingChallengeVerificationFromRpc.bind(this))))
|
|
1200
|
+
.on("publishingstatechange", unlessStopped(this._guardDetachedHandler("_handleIncomingPublishingStateFromRpc", this._handleIncomingPublishingStateFromRpc.bind(this))))
|
|
1201
|
+
.on("statechange", unlessStopped(this._guardDetachedHandler("_handleIncomingStateFromRpc", this._handleIncomingStateFromRpc.bind(this))))
|
|
1202
|
+
.on("error", unlessStopped(this._guardDetachedHandler("_handleIncomingErrorFromRpc", this._handleIncomingErrorFromRpc.bind(this)))),
|
|
937
1203
|
// Pre-deferral a replay throw rejected publish(); the helper contains it (log,
|
|
938
1204
|
// surface as an "error" event, stop)
|
|
939
1205
|
replayErrorContainment: {
|
|
@@ -1002,8 +1268,11 @@ class Publication extends TypedEmitter {
|
|
|
1002
1268
|
this._validateCommunityFields();
|
|
1003
1269
|
}
|
|
1004
1270
|
catch (e) {
|
|
1005
|
-
|
|
1006
|
-
this.
|
|
1271
|
+
// A fetch aborted by stop() rejects after stop() settled the states, which must stay "stopped"
|
|
1272
|
+
if (!this._hasPublishEnded()) {
|
|
1273
|
+
this._setStateWithEmission("stopped");
|
|
1274
|
+
this._updatePublishingStateWithEmission("failed");
|
|
1275
|
+
}
|
|
1007
1276
|
throw e;
|
|
1008
1277
|
}
|
|
1009
1278
|
}
|
|
@@ -1043,14 +1312,14 @@ class Publication extends TypedEmitter {
|
|
|
1043
1312
|
return contexts;
|
|
1044
1313
|
}
|
|
1045
1314
|
async _handleNotReceivingResponseToChallengeRequest({ providers, currentPubsubProviderIndex, acceptedChallengeTypes }) {
|
|
1046
|
-
//
|
|
1315
|
+
// Aborted once the publish run is over, so the waits below end with it
|
|
1047
1316
|
const runSignal = this._getPublishRunWaitSignal();
|
|
1048
1317
|
await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1000, runSignal);
|
|
1049
1318
|
// pkc.destroy() and the end of the run (verification, failure, stop()) abort the sleep above, so
|
|
1050
1319
|
// neither teardown nor garbage collection waits it out. Bail before doing any re-publish work:
|
|
1051
1320
|
// otherwise we'd create a signer on a destroyed pkc (throwing ERR_PKC_IS_DESTROYED), re-publish a
|
|
1052
1321
|
// stopped publication, or re-subscribe/re-dial peers that nothing is left to tear down.
|
|
1053
|
-
if (this.
|
|
1322
|
+
if (this._hasPublishEnded())
|
|
1054
1323
|
return;
|
|
1055
1324
|
if (this._didWeReceiveChallengeOrChallengeVerification())
|
|
1056
1325
|
return;
|
|
@@ -1062,15 +1331,16 @@ class Publication extends TypedEmitter {
|
|
|
1062
1331
|
if (this._isAllAttemptsExhausted(providers.length)) {
|
|
1063
1332
|
// pkc-js tried all providers and still no response is received
|
|
1064
1333
|
log.error(`Failed to receive any response for publication`, this.getType());
|
|
1065
|
-
await this.
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1334
|
+
await this._endPublishWithFailure(() => {
|
|
1335
|
+
const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
|
|
1336
|
+
challengeExchanges: this._challengeExchangesFormattedForErrors(),
|
|
1337
|
+
publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
|
|
1338
|
+
providerHeliaContexts: this._libp2pJsClientHeliaContexts()
|
|
1339
|
+
});
|
|
1340
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1341
|
+
newPublishingState: "failed",
|
|
1342
|
+
event: { name: "error", args: [error] }
|
|
1343
|
+
});
|
|
1074
1344
|
});
|
|
1075
1345
|
}
|
|
1076
1346
|
else if (this.state === "stopped") {
|
|
@@ -1078,19 +1348,17 @@ class Publication extends TypedEmitter {
|
|
|
1078
1348
|
await this._postSucessOrFailurePublishing();
|
|
1079
1349
|
}
|
|
1080
1350
|
else {
|
|
1081
|
-
if (currentPubsubProviderIndex + 1
|
|
1082
|
-
log.error(`Failed to receive any response for publication`, this.getType(), "after publishing to all providers", providers);
|
|
1083
|
-
await this._postSucessOrFailurePublishing();
|
|
1084
|
-
}
|
|
1085
|
-
else {
|
|
1351
|
+
if (currentPubsubProviderIndex + 1 < providers.length) {
|
|
1086
1352
|
// let's publish to the next provider
|
|
1087
1353
|
log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
|
|
1088
1354
|
currentPubsubProviderIndex += 1;
|
|
1089
1355
|
while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
|
|
1090
1356
|
const providerUrl = providers[currentPubsubProviderIndex];
|
|
1091
|
-
if (this.
|
|
1357
|
+
if (this._hasPublishEnded())
|
|
1092
1358
|
return;
|
|
1093
1359
|
const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
|
|
1360
|
+
if (this._hasPublishEnded())
|
|
1361
|
+
return;
|
|
1094
1362
|
this._updatePublishingStateWithEmission("publishing-challenge-request");
|
|
1095
1363
|
this._updatePubsubState("subscribing-pubsub", providerUrl);
|
|
1096
1364
|
try {
|
|
@@ -1103,6 +1371,8 @@ class Publication extends TypedEmitter {
|
|
|
1103
1371
|
timestamp();
|
|
1104
1372
|
}
|
|
1105
1373
|
catch (e) {
|
|
1374
|
+
if (this._hasPublishEnded())
|
|
1375
|
+
return;
|
|
1106
1376
|
log.error("Failed to publish challenge request using provider ", providerUrl, e);
|
|
1107
1377
|
this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
|
|
1108
1378
|
continue;
|
|
@@ -1110,6 +1380,8 @@ class Publication extends TypedEmitter {
|
|
|
1110
1380
|
finally {
|
|
1111
1381
|
currentPubsubProviderIndex += 1;
|
|
1112
1382
|
}
|
|
1383
|
+
if (this._hasPublishEnded())
|
|
1384
|
+
return;
|
|
1113
1385
|
const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
|
|
1114
1386
|
// The first request's challenge can land while the retry's publish call is still
|
|
1115
1387
|
// in flight; the publication is then already waiting for answers (or verified) and
|
|
@@ -1122,34 +1394,41 @@ class Publication extends TypedEmitter {
|
|
|
1122
1394
|
this.emit("challengerequest", decryptedRequest);
|
|
1123
1395
|
if (currentPubsubProviderIndex !== providers.length)
|
|
1124
1396
|
await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1000, runSignal);
|
|
1125
|
-
if (this.
|
|
1397
|
+
if (this._hasPublishEnded())
|
|
1126
1398
|
return;
|
|
1127
1399
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
//
|
|
1132
|
-
// publication
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1400
|
+
}
|
|
1401
|
+
else {
|
|
1402
|
+
// The request is held by the last provider (the ones before it threw), so there is nobody left to
|
|
1403
|
+
// retry with. Give it the same failure wait as a retried request below. Stopping here instead left the
|
|
1404
|
+
// publication stopped with publishingState "waiting-challenge" and no error
|
|
1405
|
+
log(`No response from the last provider (${currentPubsubProvider}), will wait for it until the failure threshold`);
|
|
1406
|
+
}
|
|
1407
|
+
await sleepUntilTimeoutOrAbort(this._setProviderFailureThresholdSeconds * 1000, runSignal);
|
|
1408
|
+
if (this._hasPublishEnded())
|
|
1409
|
+
return;
|
|
1410
|
+
// Kept although stop() now ends the wait above through the run signal: a stopped
|
|
1411
|
+
// publication must not be treated as a failure and emit ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS.
|
|
1412
|
+
// The enclosing `else` narrowed `this.state` to exclude "stopped", but stop() during the
|
|
1413
|
+
// awaited wait above can have set it since, so widen back to the field's declared type.
|
|
1414
|
+
if (this.state === "stopped")
|
|
1415
|
+
return;
|
|
1416
|
+
// A challenge (or the verification itself) can arrive during the wait above. That
|
|
1417
|
+
// exchange is live and the no-response watchdog has nothing left to decide: the
|
|
1418
|
+
// publication stays subscribed for its verification, exactly like a publication whose
|
|
1419
|
+
// challenge arrived before any retry (issue #340).
|
|
1420
|
+
if (this._didWeReceiveChallengeOrChallengeVerification()) {
|
|
1421
|
+
log(`Received a challenge or challenge verification while waiting for retried providers, will keep the exchange alive`);
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
if (this._isAllAttemptsExhausted(providers.length)) {
|
|
1425
|
+
// Read before the cleanup below, and say what actually happened. A request that
|
|
1426
|
+
// reached pubsub and was met with silence may still be accepted by a community
|
|
1427
|
+
// that is slow or busy (issue #362), so that is "no response", never "all
|
|
1428
|
+
// providers threw". Only when no request could be published at all is the
|
|
1429
|
+
// publication known not to have reached the community.
|
|
1430
|
+
const aRequestWasPublished = this._wasAnyChallengeRequestPublished();
|
|
1431
|
+
await this._endPublishWithFailure(() => {
|
|
1153
1432
|
const allAttemptsFailedError = aRequestWasPublished
|
|
1154
1433
|
? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
|
|
1155
1434
|
challengeExchanges: this._challengeExchangesFormattedForErrors(),
|
|
@@ -1168,8 +1447,8 @@ class Publication extends TypedEmitter {
|
|
|
1168
1447
|
newPublishingState: "failed",
|
|
1169
1448
|
event: { name: "error", args: [allAttemptsFailedError] }
|
|
1170
1449
|
});
|
|
1171
|
-
|
|
1172
|
-
|
|
1450
|
+
});
|
|
1451
|
+
return;
|
|
1173
1452
|
}
|
|
1174
1453
|
}
|
|
1175
1454
|
}
|
|
@@ -1187,23 +1466,31 @@ class Publication extends TypedEmitter {
|
|
|
1187
1466
|
this._publishingToLocalCommunity = community;
|
|
1188
1467
|
const log = Logger("pkc-js:publication:publish:_publishWithLocalCommunity");
|
|
1189
1468
|
log("Community is local, will not publish over pubsub, and instead will publish directly to the community by accessing pkc._startedCommunities");
|
|
1190
|
-
const communityChallengeListener = async (challenge) => {
|
|
1469
|
+
const communityChallengeListener = this._guardDetachedHandler("communityChallengeListener", async (challenge) => {
|
|
1470
|
+
if (this._hasPublishEnded())
|
|
1471
|
+
return;
|
|
1191
1472
|
if (challenge.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
|
|
1192
1473
|
// need to remove encrypted fields from challenge otherwise _handleIncomingChallengePubsubMessage will throw
|
|
1193
1474
|
const encryptedFields = ["challenges"];
|
|
1194
1475
|
log("Received a challenge from the local community", challenge);
|
|
1195
1476
|
await this._handleIncomingChallengePubsubMessage(omit(challenge, encryptedFields));
|
|
1196
1477
|
}
|
|
1197
|
-
};
|
|
1478
|
+
});
|
|
1198
1479
|
community.on("challenge", communityChallengeListener);
|
|
1199
|
-
|
|
1480
|
+
// The handling of the community's verdict, which records it only after its signature is checked. Set synchronously
|
|
1481
|
+
// on the emission, so a rejection that follows the verdict can wait for it
|
|
1482
|
+
let verificationHandling;
|
|
1483
|
+
const communityChallengeVerificationListener = this._guardDetachedHandler("communityChallengeVerificationListener", async (decryptedChallengeVerification) => {
|
|
1484
|
+
if (this._hasPublishEnded())
|
|
1485
|
+
return;
|
|
1200
1486
|
if (decryptedChallengeVerification.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
|
|
1201
1487
|
log("Received a challenge verification from the local community", decryptedChallengeVerification);
|
|
1202
1488
|
// need to remove publicatioon fields from challenge verification otherwise verifyChallengeVerification will throw
|
|
1203
1489
|
const publicationFieldsToRemove = ["comment", "commentUpdate"];
|
|
1204
|
-
|
|
1490
|
+
verificationHandling = this._handleIncomingChallengeVerificationPubsubMessage(omit(decryptedChallengeVerification, publicationFieldsToRemove));
|
|
1491
|
+
await verificationHandling;
|
|
1205
1492
|
}
|
|
1206
|
-
};
|
|
1493
|
+
});
|
|
1207
1494
|
community.on("challengeverification", communityChallengeVerificationListener);
|
|
1208
1495
|
this.emit("challengerequest", challengeRequest);
|
|
1209
1496
|
community
|
|
@@ -1214,10 +1501,25 @@ class Publication extends TypedEmitter {
|
|
|
1214
1501
|
challengeRequestPublishTimestamp: timestamp()
|
|
1215
1502
|
};
|
|
1216
1503
|
})
|
|
1217
|
-
.catch((e) => {
|
|
1504
|
+
.catch(async (e) => {
|
|
1218
1505
|
log.error("Failed to handle challenge request with local community", e);
|
|
1219
|
-
|
|
1220
|
-
|
|
1506
|
+
const challengeRequestId = challengeRequest.challengeRequestId.toString();
|
|
1507
|
+
this._challengeExchanges[challengeRequestId].challengeRequestPublishError = e;
|
|
1508
|
+
// A request the community could not decrypt or parse gets a failed verdict right before this rejection. That
|
|
1509
|
+
// verdict ends the publish, so wait for its handling (a rejection of it still rejects the listener above)
|
|
1510
|
+
await verificationHandling?.catch(() => { });
|
|
1511
|
+
// Without a verdict, nothing else can end the publish: the listeners above are removed once this settles. It
|
|
1512
|
+
// used to stay "publishing" and registered until stop(), and the rejection was unhandled. After a verdict or
|
|
1513
|
+
// a stop() this writes nothing
|
|
1514
|
+
try {
|
|
1515
|
+
await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1516
|
+
newPublishingState: "failed",
|
|
1517
|
+
event: { name: "error", args: [e] }
|
|
1518
|
+
}));
|
|
1519
|
+
}
|
|
1520
|
+
catch (endError) {
|
|
1521
|
+
log.error("Failed to end the exchange the local community rejected", endError);
|
|
1522
|
+
}
|
|
1221
1523
|
})
|
|
1222
1524
|
.finally(() => {
|
|
1223
1525
|
community.removeListener("challenge", communityChallengeListener);
|
|
@@ -1225,9 +1527,21 @@ class Publication extends TypedEmitter {
|
|
|
1225
1527
|
});
|
|
1226
1528
|
}
|
|
1227
1529
|
async publish() {
|
|
1530
|
+
// One challenge exchange per instance, see _isPublishSpent
|
|
1531
|
+
if (this._isPublishSpent || this._isPublishCallRunning) {
|
|
1532
|
+
const exchanges = Object.values(this._challengeExchanges);
|
|
1533
|
+
throw new PKCError("ERR_PUBLICATION_PUBLISH_ALREADY_CALLED", {
|
|
1534
|
+
publicationType: this.getType(),
|
|
1535
|
+
state: this.state,
|
|
1536
|
+
publishingState: this.publishingState,
|
|
1537
|
+
receivedChallenge: exchanges.some((exchange) => exchange.challenge),
|
|
1538
|
+
receivedChallengeVerification: exchanges.some((exchange) => exchange.challengeVerification)
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1228
1541
|
this._validatePublicationFields();
|
|
1229
|
-
|
|
1230
|
-
// fetch before it
|
|
1542
|
+
this._isPublishCallRunning = true;
|
|
1543
|
+
// An earlier stop() left the signal aborted, which would cancel this publish's community fetch before it
|
|
1544
|
+
// started.
|
|
1231
1545
|
if (this._getCommunityFetchAbortSignal().aborted)
|
|
1232
1546
|
this._resetCommunityFetchAbortSignal();
|
|
1233
1547
|
this._beginPublishRun();
|
|
@@ -1252,6 +1566,9 @@ class Publication extends TypedEmitter {
|
|
|
1252
1566
|
this._publishRunAbortController?.abort();
|
|
1253
1567
|
throw e;
|
|
1254
1568
|
}
|
|
1569
|
+
finally {
|
|
1570
|
+
this._isPublishCallRunning = false;
|
|
1571
|
+
}
|
|
1255
1572
|
}
|
|
1256
1573
|
async _publishAfterRegistering() {
|
|
1257
1574
|
const log = Logger("pkc-js:publication:publish");
|
|
@@ -1269,29 +1586,43 @@ class Publication extends TypedEmitter {
|
|
|
1269
1586
|
await this._signPublicationWithCommunityFields();
|
|
1270
1587
|
}
|
|
1271
1588
|
await this._validateSignatureHook();
|
|
1589
|
+
// Before _isPublishSpent, so an invalid wallet entry fails with nothing sent and the instance stays usable
|
|
1590
|
+
this._validateAuthorWalletProofs();
|
|
1591
|
+
// Stopped during the steps above: stop() settled the states, so do not start an exchange behind it
|
|
1592
|
+
if (this._hasPublishEnded())
|
|
1593
|
+
return;
|
|
1594
|
+
// Pre-flight is over. From here a request can leave this instance, so it cannot publish again
|
|
1595
|
+
this._isPublishSpent = true;
|
|
1272
1596
|
if (this._pkc._pkcRpcClient)
|
|
1273
1597
|
return this._publishWithRpc();
|
|
1274
1598
|
const options = { acceptedChallengeTypes: [] };
|
|
1275
1599
|
const startedCommunity = findStartedCommunity(this._pkc, { publicKey: this.communityPublicKey, name: this.communityName });
|
|
1276
1600
|
if (startedCommunity) {
|
|
1277
|
-
|
|
1601
|
+
const challengeRequest = await this._generateChallengeRequestToPublish(LOCAL_COMMUNITY_PROVIDER, options.acceptedChallengeTypes);
|
|
1602
|
+
if (this._hasPublishEnded())
|
|
1603
|
+
return;
|
|
1604
|
+
return this._publishWithLocalCommunity(startedCommunity, challengeRequest);
|
|
1278
1605
|
}
|
|
1279
1606
|
// Only the network path needs a challenge topic. Fail fast before touching pubsub so a client
|
|
1280
1607
|
// can disable its reply UI instead of timing out against a topic nobody runs (issue #229).
|
|
1281
1608
|
if (typeof this._community?.pubsubTopic !== "string") {
|
|
1282
|
-
await this.
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1609
|
+
const disabledError = await this._endPublishWithFailure(() => {
|
|
1610
|
+
const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
|
|
1611
|
+
communityAddress: this._community?.address ?? this.communityAddress,
|
|
1612
|
+
communityName: this._community?.name ?? this.communityName,
|
|
1613
|
+
communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
|
|
1614
|
+
publicationType: this.getType()
|
|
1615
|
+
});
|
|
1616
|
+
log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
|
|
1617
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1618
|
+
newPublishingState: "failed",
|
|
1619
|
+
event: { name: "error", args: [error] }
|
|
1620
|
+
});
|
|
1621
|
+
return error;
|
|
1293
1622
|
});
|
|
1294
|
-
|
|
1623
|
+
if (disabledError)
|
|
1624
|
+
throw disabledError;
|
|
1625
|
+
return; // stop() ended the publish first
|
|
1295
1626
|
}
|
|
1296
1627
|
// Discovered only once the network path is certain: neither the local shortcut above nor the
|
|
1297
1628
|
// disabled-exchange fast-fail publishes over pubsub, so neither should demand a provider.
|
|
@@ -1300,6 +1631,8 @@ class Publication extends TypedEmitter {
|
|
|
1300
1631
|
while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
|
|
1301
1632
|
const providerUrl = providers[currentPubsubProviderIndex];
|
|
1302
1633
|
const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, options.acceptedChallengeTypes);
|
|
1634
|
+
if (this._hasPublishEnded())
|
|
1635
|
+
return;
|
|
1303
1636
|
this._updatePublishingStateWithEmission("publishing-challenge-request");
|
|
1304
1637
|
this._updatePubsubState("subscribing-pubsub", providerUrl);
|
|
1305
1638
|
try {
|
|
@@ -1312,27 +1645,37 @@ class Publication extends TypedEmitter {
|
|
|
1312
1645
|
this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
|
|
1313
1646
|
}
|
|
1314
1647
|
catch (e) {
|
|
1648
|
+
if (this._hasPublishEnded())
|
|
1649
|
+
return; // stopped meanwhile: a clean exit, not a failure
|
|
1315
1650
|
this._updatePubsubState("stopped", providerUrl);
|
|
1316
1651
|
log.error("Failed to publish challenge request using provider ", providerUrl, e);
|
|
1317
1652
|
currentPubsubProviderIndex += 1;
|
|
1318
1653
|
this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
|
|
1319
1654
|
if (this._isAllAttemptsExhausted(providers.length)) {
|
|
1320
|
-
await this.
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1655
|
+
const failure = await this._endPublishWithFailure(() => {
|
|
1656
|
+
const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
|
|
1657
|
+
challengeExchanges: this._challengeExchangesFormattedForErrors(),
|
|
1658
|
+
pubsubTopic: this._community?.pubsubTopic,
|
|
1659
|
+
providerHeliaContexts: this._libp2pJsClientHeliaContexts()
|
|
1660
|
+
});
|
|
1661
|
+
log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
|
|
1662
|
+
this._changePublicationStateEmitEventEmitStateChangeEvent({
|
|
1663
|
+
newPublishingState: "failed",
|
|
1664
|
+
event: { name: "error", args: [allAttemptsFailedError] }
|
|
1665
|
+
});
|
|
1666
|
+
return allAttemptsFailedError;
|
|
1330
1667
|
});
|
|
1331
|
-
|
|
1668
|
+
if (failure)
|
|
1669
|
+
throw failure;
|
|
1670
|
+
return; // stop() ended the publish first
|
|
1332
1671
|
}
|
|
1333
1672
|
else
|
|
1334
1673
|
continue;
|
|
1335
1674
|
}
|
|
1675
|
+
// stop() landed while the request was being published and already settled the states and unsubscribed, or
|
|
1676
|
+
// the community's verdict did: waiting for a challenge, or starting the no-response watchdog, would undo that
|
|
1677
|
+
if (this._hasPublishEnded())
|
|
1678
|
+
return;
|
|
1336
1679
|
const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
|
|
1337
1680
|
this._updatePubsubState("waiting-challenge", providerUrl);
|
|
1338
1681
|
this._updatePublishingStateWithEmission("waiting-challenge");
|
|
@@ -1348,6 +1691,7 @@ class Publication extends TypedEmitter {
|
|
|
1348
1691
|
acceptedChallengeTypes: options.acceptedChallengeTypes
|
|
1349
1692
|
}).catch((err) => {
|
|
1350
1693
|
log.error("Failed to handle not receiving response to challenge request", err);
|
|
1694
|
+
void this._endPublicationAfterDetachedFailure("_handleNotReceivingResponseToChallengeRequest", err);
|
|
1351
1695
|
});
|
|
1352
1696
|
}
|
|
1353
1697
|
}
|