-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathindex.ts
More file actions
98 lines (84 loc) · 2.92 KB
/
Copy pathindex.ts
File metadata and controls
98 lines (84 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { randomUUIDv7 } from "bun";
import type { OutgoingMessage, SignupOutgoingMessage, ValidateOutgoingMessage } from "common/types";
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";
import nacl_util from "tweetnacl-util";
import bs58 from 'bs58'
const CALLBACKS: {[callbackId: string]: (data: SignupOutgoingMessage) => void} = {}
let validatorId: string | null = null;
async function main() {
const keypair = Keypair.fromSecretKey(
bs58.decode(process.env.PRIVATE_KEY!)
);
const ws = new WebSocket("ws://localhost:8081");
ws.onmessage = async (event) => {
const data: OutgoingMessage = JSON.parse(event.data);
if (data.type === 'signup') {
CALLBACKS[data.data.callbackId]?.(data.data)
delete CALLBACKS[data.data.callbackId];
} else if (data.type === 'validate') {
await validateHandler(ws, data.data, keypair);
}
}
ws.onopen = async () => {
const callbackId = randomUUIDv7();
CALLBACKS[callbackId] = (data: SignupOutgoingMessage) => {
validatorId = data.validatorId;
}
const signedMessage = await signMessage(`Signed message for ${callbackId}, ${keypair.publicKey}`, keypair);
ws.send(JSON.stringify({
type: 'signup',
data: {
callbackId,
ip: '127.0.0.1',
publicKey: keypair.publicKey,
signedMessage,
},
}));
}
}
async function validateHandler(ws: WebSocket, { url, callbackId, websiteId }: ValidateOutgoingMessage, keypair: Keypair) {
console.log(`Validating ${url}`);
const startTime = Date.now();
const signature = await signMessage(`Replying to ${callbackId}`, keypair);
try {
const response = await fetch(url);
const endTime = Date.now();
const latency = endTime - startTime;
const status = response.status;
console.log(url);
console.log(status);
ws.send(JSON.stringify({
type: 'validate',
data: {
callbackId,
status: status === 200 ? 'Good' : 'Bad',
latency,
websiteId,
validatorId,
signedMessage: signature,
},
}));
} catch (error) {
ws.send(JSON.stringify({
type: 'validate',
data: {
callbackId,
status:'Bad',
latency: 1000,
websiteId,
validatorId,
signedMessage: signature,
},
}));
console.error(error);
}
}
async function signMessage(message: string, keypair: Keypair) {
const messageBytes = nacl_util.decodeUTF8(message);
const signature = nacl.sign.detached(messageBytes, keypair.secretKey);
return JSON.stringify(Array.from(signature));
}
main();
setInterval(async () => {
}, 10000);