summaryrefslogtreecommitdiff
path: root/lib/urbit/wallet.ts
blob: c29da48a6de6d81ce3dd9e35bf9b983434d6ad65 (plain)
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
import { generateWallet } from "urbit-key-generation";
import * as ob from "urbit-ob";

import {
  GALAXY_ENTROPY_BITS,
  MIN_PLANET,
  MIN_STAR,
  PLANET_ENTROPY_BITS,
  STAR_ENTROPY_BITS,
  SEED_ENTROPY_BITS,
} from "./constants";
import { shas } from "@/lib/utils/bit";

const SEED_LENGTH_BYTES = SEED_ENTROPY_BITS / 8;
const getTicketBitSize = (point: number) =>
  point < MIN_STAR
    ? GALAXY_ENTROPY_BITS
    : point < MIN_PLANET
      ? STAR_ENTROPY_BITS
      : PLANET_ENTROPY_BITS;

export const stripHexPrefix = (hex: string) => {
  return hex.startsWith("0x") ? hex.slice(2) : hex;
};
export const makeDeterministicTicket = (point: number, seed: string) => {
  const bits = getTicketBitSize(point);

  const bytes = bits / 8;

  const pointSalt = Buffer.concat([
    Buffer.from(point.toString()),
    Buffer.from("invites"),
  ]);
  const normalizedSeed = stripHexPrefix(seed);
  const entropy = shas(Buffer.from(normalizedSeed, "hex"), pointSalt);

  const buf = entropy.slice(0, bytes);
  const patq = ob.hex2patq(buf.toString("hex"));
  return patq;
};

// return a wallet object
export const makeWalletFromP = async (patp: string, ticket: string) => {
  const point = Number(ob.patp2dec(patp));
  return await makeWallet({ point, ticket });
};
export const makeWallet = async (data: {
  point: number;
  ticket: string;
  boot?: boolean;
  revision?: number;
}) => {
  const config = {
    ticket: data.ticket,
    seedSize: SEED_LENGTH_BYTES,
    point: data.point,
    password: "",
    revision: data.revision || 1,
    boot: data.boot || false,
  };

  // This is here to notify anyone who opens console because the thread
  // hangs, blocking UI updates so this cannot be done in the UI
  console.log("Generating Wallet for point address: ", data.point);

  const wallet = await generateWallet(config);
  console.log({ wallet });

  return wallet;
  // return new Promise(async (resolve, reject) => {
  //   // Use a web worker to process the data
  //   try {
  //     const processed = await walletgenWorker.generate(JSON.stringify(config));
  //     resolve(processed);
  //   } catch (error) {
  //     reject(error);
  //   }
  // });
};