@@ -0,0 +1,201 @@
1+import * as need from 'lib/need';
2+import saveAs from 'file-saver';
3+import ob from 'urbit-ob';
4+import { Just, Nothing } from 'folktale/maybe';
5+
6+import { useCallback, useEffect, useMemo, useState } from 'react';
7+import { usePointCache } from 'store/pointCache';
8+import { usePointCursor } from 'store/pointCursor';
9+import { useWallet } from 'store/wallet';
10+import { deriveNetworkKeys } from 'urbit-key-generation';
11+import { convertToInt } from './convertToInt';
12+import {
13+ attemptNetworkSeedDerivation,
14+ compileMultikey,
15+ keysMatchChain,
16+} from './keys';
17+import { generateCode } from './networkCode';
18+import { L1Point } from './types/L1Point';
19+import useCurrentPermissions from './useCurrentPermissions';
20+import { stripSigPrefix } from 'form/formatters';
21+
22+interface useMultikeyFileGeneratorArgs {
23+ seed?: string;
24+ point?: number;
25+ seedWallet?: any;
26+}
27+
28+/**
29+ * defaults:
30+ * - seed: derived from wallet, mnemonic, or token (if posisble)
31+ * - point: the current pointCursor
32+ */
33+export default function useMultikeyFileGenerator({
34+ seed,
35+ point,
36+ seedWallet,
37+}: useMultikeyFileGeneratorArgs) {
38+ const { urbitWallet, wallet, authMnemonic, authToken }: any = useWallet();
39+ const { pointCursor }: any = usePointCursor();
40+ const { syncDetails, getDetails }: any = usePointCache();
41+ const { isOwner, isManagementProxy } = useCurrentPermissions();
42+
43+ const [notice, setNotice] = useState('Deriving networking keys...');
44+ const [downloaded, setDownloaded] = useState(false);
45+ const [generating, setGenerating] = useState(true);
46+ const [keyfile, setKeyfile] = useState<boolean | string>(false);
47+ const [code, setCode] = useState(false);
48+
49+ const _point = useMemo(() => point || need.point(pointCursor), [
50+ point,
51+ pointCursor,
52+ ]);
53+ const details = getDetails(_point);
54+ const _details: L1Point | null = useMemo(
55+ () =>
56+ details.matchWith({
57+ Just: d => need.details(d),
58+ Nothing: () => null,
59+ }),
60+ [details]
61+ );
62+
63+ const currentRevision: number = useMemo(
64+ () =>
65+ details.matchWith({
66+ Just: ({ value }) => convertToInt(value.keyRevisionNumber, 10),
67+ Nothing: () => 0,
68+ }),
69+ [details]
70+ );
71+ const nextRevision = useMemo(() => currentRevision + 1, [currentRevision]);
72+
73+ const pairFromRevision = useCallback(
74+ async (revision: number) => {
75+ if (!_details) {
76+ return;
77+ }
78+
79+ const networkSeed = seed
80+ ? Just(seed)
81+ : await attemptNetworkSeedDerivation({
82+ urbitWallet: seedWallet || urbitWallet,
83+ wallet,
84+ authMnemonic,
85+ details: _details,
86+ authToken,
87+ point: _point,
88+ revision: revision,
89+ });
90+
91+ if (Nothing.hasInstance(networkSeed)) {
92+ setGenerating(false);
93+ setNotice(
94+ 'Custom or nondeterministic networking keys cannot be re-downloaded.'
95+ );
96+ console.log(`seed is nondeterminable for revision ${revision}`);
97+ return;
98+ }
99+
100+ const _networkSeed = networkSeed.value;
101+
102+ return deriveNetworkKeys(_networkSeed);
103+ },
104+ [
105+ _details,
106+ _point,
107+ authMnemonic,
108+ authToken,
109+ seed,
110+ urbitWallet,
111+ wallet,
112+ seedWallet,
113+ ]
114+ );
115+
116+ const hasNetworkKeys = currentRevision > 0;
117+ const available =
118+ (isOwner || isManagementProxy) && hasNetworkKeys && !!keyfile;
119+
120+ const generate = useCallback(async () => {
121+ if (!hasNetworkKeys) {
122+ setGenerating(false);
123+ setNotice('Network keys not yet set.');
124+ console.log(
125+ `no networking keys available for revision ${currentRevision}`
126+ );
127+ return;
128+ }
129+
130+ // TODO: Do we still need this? The legacy implementation in useKeyfileGenerator
131+ // performed this guard statement
132+
133+ // const currentPair = await pairFromRevision(currentRevision);
134+
135+ // if (!currentPair || !keysMatchChain(currentPair, _details)) {
136+ // setGenerating(false);
137+ // setNotice('Derived networking keys do not match on-chain details.');
138+ // console.log(`keys do not match details for revision ${currentRevision}`);
139+ // return;
140+ // }
141+
142+ // const nextPair = await pairFromRevision(nextRevision);
143+
144+ const [currentPair, nextPair] = await Promise.all([
145+ pairFromRevision(currentRevision),
146+ pairFromRevision(nextRevision),
147+ ]);
148+
149+ setNotice('');
150+ setCode(generateCode(currentPair));
151+ setKeyfile(
152+ compileMultikey(
153+ _point,
154+ currentPair,
155+ nextPair,
156+ currentRevision,
157+ nextRevision
158+ )
159+ );
160+ setGenerating(false);
161+ }, [_point, currentRevision, hasNetworkKeys, nextRevision, pairFromRevision]);
162+
163+ const filename = useMemo(() => {
164+ return `${stripSigPrefix(ob.patp(_point))}-${currentRevision}.key`;
165+ }, [_point, currentRevision]);
166+
167+ const download = useCallback(() => {
168+ if (typeof keyfile !== 'string') {
169+ return;
170+ }
171+
172+ saveAs(
173+ new Blob([keyfile], {
174+ type: 'text/plain;charset=utf-8',
175+ }),
176+ filename
177+ );
178+ setDownloaded(true);
179+ }, [filename, keyfile]);
180+
181+ useEffect(() => {
182+ syncDetails(_point);
183+ }, [_point, syncDetails]);
184+
185+ useEffect(() => {
186+ generate();
187+ }, [generate]);
188+
189+ const output = {
190+ generating,
191+ available,
192+ downloaded,
193+ download,
194+ filename,
195+ notice,
196+ keyfile,
197+ code,
198+ };
199+
200+ return { ...output, bind: output };
201+}