-
Notifications
You must be signed in to change notification settings - Fork 0
/
deno-main.ts
293 lines (235 loc) · 8.47 KB
/
deno-main.ts
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
BigInt.prototype.toJSON = function () {
return Number(this.toString());
};
import { loadSync } from "https://deno.land/std@0.199.0/dotenv/mod.ts";
import { Command } from "https://deno.land/x/cliffy@v1.0.0-rc.3/command/mod.ts";
import {
applyParamsToScript,
Constr,
Data,
fromHex,
fromText,
generateSeedPhrase,
Kupmios,
Lucid,
Script,
sha256,
toHex,
} from "https://deno.land/x/lucid@0.10.1/mod.ts";
import {
calculateDifficultyNumber,
calculateInterlink,
getDifficulty,
getDifficultyAdjustement,
incrementU8Array,
readValidator,
} from "./utils.ts";
loadSync({ export: true, allowEmptyValues: true });
// Excludes datum field because it is not needed
// and it's annoying to type.
type Genesis = {
validator: string;
validatorHash: string;
validatorAddress: string;
boostrapHash: string;
outRef: { txHash: string; index: number };
};
const delay = (ms: number | undefined) =>
new Promise((res) => setTimeout(res, ms));
const mine = new Command()
.description("Start the miner")
.env("KUPO_URL=<value:string>", "Kupo URL", { required: true })
.env("OGMIOS_URL=<value:string>", "Ogmios URL", { required: true })
.option("-p, --preview", "Use testnet")
.action(async ({ preview, ogmiosUrl, kupoUrl }) => {
const genesisFile = Deno.readTextFileSync(
`genesis/${preview ? "preview" : "mainnet"}.json`,
);
const { validatorHash, validatorAddress }: Genesis = JSON
.parse(
genesisFile,
);
console.log(validatorAddress)
const provider = new Kupmios(kupoUrl, ogmiosUrl);
let mempool_datum = Deno.readTextFileSync(`tuna_datum.txt`,);
const lucid = await Lucid.new(provider, preview ? "Preview" : "Mainnet");
lucid.selectWalletFromSeed(Deno.readTextFileSync("seed.txt"));
let validatorUTXOs = await lucid.utxosAt(validatorAddress);
async function submit(answer: FoundAnswer, state: Constr<
string | bigint | string[]
>) {
const realTimeNow = Number((Date.now() / 1000).toFixed(0)) * 1000 - 60000;
console.log("answer diff: " + answer.difficulty, answer.zeroes)
console.log("real diff: " + JSON.stringify(getDifficulty(answer.answer)))
console.log("old state: " + JSON.stringify(state))
const interlink = calculateInterlink(toHex(answer.answer), { leadingZeros: answer.zeroes, difficulty_number: answer.difficulty}, {
leadingZeros: state.fields[2] as bigint,
difficulty_number: state.fields[3] as bigint,
}, state.fields[7] as string[]);
let epoch_time = (state.fields[4] as bigint) +
BigInt(90000 + realTimeNow) -
(state.fields[5] as bigint);
let difficulty_number = state.fields[3] as bigint;
let leading_zeros = state.fields[2] as bigint;
if (
state.fields[0] as bigint % 2016n === 0n &&
state.fields[0] as bigint > 0
) {
const adjustment = getDifficultyAdjustement(epoch_time, 1_209_600_000n);
epoch_time = 0n;
const new_difficulty = calculateDifficultyNumber(
{
leadingZeros: state.fields[2] as bigint,
difficulty_number: state.fields[3] as bigint,
},
adjustment.numerator,
adjustment.denominator,
);
difficulty_number = new_difficulty.difficulty_number;
leading_zeros = new_difficulty.leadingZeros;
}
// calculateDifficultyNumber();
const postDatum = new Constr(0, [
(state.fields[0] as bigint) + 1n,
toHex(answer.answer),
leading_zeros,
difficulty_number,
epoch_time,
BigInt(90000 + realTimeNow),
BigInt(0),
interlink,
]);
console.log(postDatum)
const outDat = Data.to(postDatum);
console.log(`Found next datum: ${outDat}`);
const mintTokens = { [validatorHash + fromText("TUNA")]: 5000000000n };
const masterToken = { [validatorHash + fromText("lord tuna")]: 1n };
try {
const readUtxo = await lucid.utxosByOutRef([{
txHash:
"01751095ea408a3ebe6083b4de4de8a24b635085183ab8a2ac76273ef8fff5dd",
outputIndex: 0,
}]);
let tuna_hash = Deno.readTextFileSync(`tuna_hash.txt`,);
let tuna_coins = Deno.readTextFileSync(`tuna_coins.txt`,);
let vRef = {
txHash: tuna_hash,
outputIndex: 0,
address: "addr1wynelppvx0hdjp2tnc78pnt28veznqjecf9h3wy4edqajxsg7hwsc",
assets: {
lovelace: BigInt(tuna_coins),
"279f842c33eed9054b9e3c70cd6a3b32298259c24b78b895cb41d91a6c6f72642074756e61": 1n},
datumHash: null,
datum: mempool_datum,
scriptRef: null
}
const txMine = await lucid
.newTx()
.collectFrom(
//[validatorOutRef],
[vRef],
Data.to(new Constr(1, [toHex(answer.nonce)])),
)
.payToAddressWithData(
validatorAddress,
{ inline: outDat },
masterToken,
)
.mintAssets(mintTokens, Data.to(new Constr(0, [])))
.readFrom(readUtxo)
.validTo(realTimeNow + 180000)
.validFrom(realTimeNow)
.complete();
const signed = await txMine.sign().complete();
await signed.submit();
console.log(`TX HASH: ${signed.toHash()}`);
console.log("Waiting for confirmation...");
// // await lucid.awaitTx(signed.toHash());
} catch (e) {
console.log(e);
}
}
// END SUBMIT FUNCTION
let validatorOutRef = validatorUTXOs.find(
(u) => u.assets[validatorHash + fromText("lord tuna")],
)!;
let validatorState = validatorOutRef.datum!;
let state = Data.from(validatorState) as Constr<
string | bigint | string[]
>;
let nonce = new Uint8Array(16);
crypto.getRandomValues(nonce);
console.log("Mining...");
const update = async () => {
// console.log("Trying to update!");
validatorUTXOs = await lucid.utxosAt(validatorAddress);
validatorOutRef = validatorUTXOs.find(
(u) => u.assets[validatorHash + fromText("lord tuna")],
)!;
//console.log(validatorOutRef);
let new_datum = Deno.readTextFileSync(`tuna_datum.txt`,);
if (new_datum != mempool_datum){
console.log('New Datum!');
mempool_datum = new_datum;
validatorState = mempool_datum;
state = Data.from(validatorState) as Constr<
string | bigint | string[]
>;
}
/*
if (validatorState !== validatorOutRef.datum!) {
console.log("NEW STATE!!!!")
validatorState = validatorOutRef.datum!;
state = Data.from(validatorState) as Constr<
string | bigint | string[]
>;
}
*/
await delay(500)
await update()
}
update()
Deno.serve({ port: 8008 }, serveHttp);
async function serveHttp(request: Request): Promise<Response> {
const body = `Your user-agent is:\n\n${
request.headers.get("user-agent") ?? "Unknown"
}`
if (request.url.match("submit")) {
let answer = (await request.json())
if (!answer.nonce || !answer.answer || !answer.difficulty || !answer.zeroes) {
throw ("NO")
}
answer = answer as FoundAnswer
submit(answer, state)
return new Response(body, { status: 200 });
} else {
const body = `Your user-agent is:\n\n${
request.headers.get("user-agent") ?? "Unknown"
}`
let fixed = {
fields: [
{bytes: toHex(nonce)},
{int: state.fields[0] as bigint},
{bytes: state.fields[1]},
{int: state.fields[2] as bigint},
{int: state.fields[3] as bigint},
{int: state.fields[4] as bigint},
],
constructor: state.index
}
return new Response(JSON.stringify(fixed), { status: 200 });
}
}
});
type FoundAnswer = {
nonce: Uint8Array,
answer: Uint8Array
difficulty: bigint,
zeroes: bigint,
}
await new Command()
.name("fortuna")
.description("Fortuna miner")
.version("0.0.1")
.command("mine", mine)
.parse(Deno.args);