on e7c1371 help sign in
bridge/src/lib/useKeyfileGenerator.js
103 lines 2.8 kB history raw
1import { useCallback, useEffect, useState } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import saveAs from 'file-saver';
4import * as ob from 'urbit-ob';
6import { usePointCache } from 'store/pointCache';
7import { useWallet } from 'store/wallet';
9import * as need from 'lib/need';
11import {
12 attemptNetworkSeedDerivation,
13 keysMatchChain,
14 deriveNetworkKeys,
15 compileNetworkingKey,
16} from './keys';
17import usePermissionsForPoint from './usePermissionsForPoint';
19export default function useKeyfileGenerator(point, manualNetworkSeed) {
20 const { getDetails } = usePointCache();
21 const { urbitWallet, wallet, authMnemonic } = useWallet();
23 const [downloaded, setDownloaded] = useState(false);
24 const [generating, setGenerating] = useState(true);
25 const [keyfile, setKeyfile] = useState(false);
27 const _address = need.wallet(wallet).address;
28 const _details = need.details(getDetails(point));
30 const networkRevision = parseInt(_details.keyRevisionNumber, 10);
31 const { isOwner, isManagementProxy } = usePermissionsForPoint(
32 _address,
33 point
34 );
36 const hasNetworkingKeys = networkRevision > 0;
37 const available =
38 (isOwner || isManagementProxy) && hasNetworkingKeys && keyfile;
40 const generate = useCallback(async () => {
41 console.log('generating for network revision', networkRevision);
43 const networkSeed = manualNetworkSeed
44 ? Just(manualNetworkSeed)
45 : await attemptNetworkSeedDerivation({
46 urbitWallet,
47 wallet,
48 authMnemonic,
49 details: _details,
50 revision: networkRevision,
51 });
53 if (Nothing.hasInstance(networkSeed)) {
54 setGenerating(false);
55 console.log('nondeterministic seed!');
56 // TODO: tell user their seed is nondeterministic
57 return;
58 }
60 const _networkSeed = networkSeed.value;
62 const pair = deriveNetworkKeys(_networkSeed);
64 if (!keysMatchChain(pair, _details)) {
65 setGenerating(false);
66 console.log('Derived networking keys do not match public keys on chain.');
67 // TODO: tell usrs their seed is nondeterministic
68 }
70 setKeyfile(compileNetworkingKey(pair, point, networkRevision));
71 setGenerating(false);
72 }, [
73 manualNetworkSeed,
74 urbitWallet,
75 wallet,
76 authMnemonic,
77 _details,
78 networkRevision,
79 point,
80 ]);
82 const download = useCallback(() => {
83 saveAs(
84 new Blob([keyfile], {
85 type: 'text/plain;charset=utf-8',
86 }),
87 `${ob.patp(point).slice(1)}-${networkRevision}.key`
88 // TODO: ^ unifiy "remove tilde" calls
89 );
90 setDownloaded(true);
91 }, [keyfile, point, networkRevision]);
93 useEffect(() => {
94 generate();
95 }, [generate]);
97 return {
98 generating,
99 available,
100 downloaded,
101 download,
102 };