dao-governance-framework/forum-network/public/classes/message.js

66 lines
1.4 KiB
JavaScript
Raw Normal View History

import { CryptoUtil } from './crypto.js';
2023-01-01 21:09:02 -06:00
import { PostContent } from './post.js';
export class Message {
constructor(content) {
this.content = content;
}
async sign({ publicKey, privateKey }) {
this.publicKey = await CryptoUtil.exportKey(publicKey);
// Call toJSON before signing, to match what we'll later send
2023-01-01 21:09:02 -06:00
this.signature = await CryptoUtil.sign(this.contentToJSON(), privateKey);
return this;
}
static async verify({ content, publicKey, signature }) {
2022-12-31 16:08:42 -06:00
return CryptoUtil.verify(content, publicKey, signature);
}
2023-01-01 21:09:02 -06:00
contentToJSON() {
return this.content;
}
toJSON() {
return {
type: this.type,
2023-01-01 21:09:02 -06:00
content: this.contentToJSON(),
publicKey: this.publicKey,
signature: this.signature,
};
}
}
export class PostMessage extends Message {
type = 'post';
2023-01-01 21:09:02 -06:00
constructor({ post, stake }) {
super({
post: PostContent.fromJSON(post),
stake,
2023-01-01 21:09:02 -06:00
});
}
2023-01-01 21:09:02 -06:00
contentToJSON() {
return {
2023-01-01 21:09:02 -06:00
post: this.content.post.toJSON(),
stake: this.content.stake,
};
}
}
export class PeerMessage extends Message {
type = 'peer';
}
const messageTypes = new Map([
['post', PostMessage],
['peer', PeerMessage],
]);
2022-12-31 16:08:42 -06:00
export const messageFromJSON = ({ type, content }) => {
const MessageType = messageTypes.get(type) || Message;
2023-01-01 21:09:02 -06:00
// const messageContent = MessageType.contentFromJSON(content);
return new MessageType(content);
2022-12-31 16:08:42 -06:00
};