on ade464d help sign in
bridge/src/views/UrbitOS/NetworkingKeys.js
358 lines 11 kB history raw
1import React, { useCallback, useMemo, useRef, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { Grid, ToggleInput, CheckboxInput, Button } from 'indigo-react';
4import * as azimuth from 'azimuth-js';
5import { randomHex } from 'web3-utils';
7import { usePointCursor } from 'store/pointCursor';
8import { usePointCache } from 'store/pointCache';
9import { useNetwork } from 'store/network';
10import { useWallet } from 'store/wallet';
11import { useRollerStore } from 'store/rollerStore';
13import useRoller from 'lib/useRoller';
14import { useLocalRouter } from 'lib/LocalRouter';
15import * as need from 'lib/need';
16import {
17 attemptNetworkSeedDerivation,
18 deriveNetworkKeys,
19 CRYPTO_SUITE_VERSION,
20} from 'lib/keys';
21import useEthereumTransaction from 'lib/useEthereumTransaction';
22import { GAS_LIMITS } from 'lib/constants';
23import { addHexPrefix } from 'lib/utils/address';
24import useKeyfileGenerator from 'lib/useKeyfileGenerator';
26import DownloadKeyfileButton from 'components/DownloadKeyfileButton';
27import InlineEthereumTransaction from 'components/InlineEthereumTransaction';
28import NoticeBox from 'components/NoticeBox';
29import AlertBox from 'components/AlertBox';
31import { HexInput } from 'form/Inputs';
32import {
33 composeValidator,
34 buildCheckboxValidator,
35 buildHexValidator,
36} from 'form/validators';
37import BridgeForm from 'form/BridgeForm';
38import Condition from 'form/Condition';
39import FormError from 'form/FormError';
40import { convertToInt } from 'lib/convertToInt';
41import Window from 'components/L2/Window/Window';
42import HeaderPane from 'components/L2/Window/HeaderPane';
43import BodyPane from 'components/L2/Window/BodyPane';
44import { Box, Row } from '@tlon/indigo-react';
46function useSetKeys(manualNetworkSeed, setManualNetworkSeed) {
47 const { urbitWallet, wallet, authMnemonic, authToken } = useWallet();
48 const { pointCursor } = usePointCursor();
49 const { syncDetails, syncRekeyDate, getDetails } = usePointCache();
50 const { contracts } = useNetwork();
52 const _point = need.point(pointCursor);
53 const _contracts = need.contracts(contracts);
54 const _details = need.details(getDetails(_point));
56 const networkRevision = convertToInt(_details.keyRevisionNumber, 10);
57 const randomSeed = useRef();
59 const {
60 available: keyfileAvailable,
61 generating: keyfileGenerating,
62 filename,
63 bind: keyfileBind,
64 } = useKeyfileGenerator(manualNetworkSeed);
66 const buildNetworkSeed = useCallback(
67 async manualSeed => {
68 if (manualSeed !== undefined) {
69 setManualNetworkSeed(manualSeed);
70 return manualSeed;
71 } else {
72 const newNetworkRevision = networkRevision + 1;
73 console.log(`deriving seed with revision ${newNetworkRevision}`);
75 const networkSeed = await attemptNetworkSeedDerivation({
76 urbitWallet,
77 wallet,
78 authMnemonic,
79 details: _details,
80 point: _point,
81 authToken,
82 revision: newNetworkRevision,
83 });
85 if (Just.hasInstance(networkSeed)) {
86 return networkSeed.value;
87 }
89 randomSeed.current = randomSeed.current || randomHex(32); // 32 bytes
90 setManualNetworkSeed(randomSeed.current);
92 return randomSeed.current;
93 }
94 },
95 [
96 _details,
97 authMnemonic,
98 setManualNetworkSeed,
99 networkRevision,
100 urbitWallet,
101 wallet,
102 _point,
103 authToken,
104 ]
105 );
107 const { completed: _completed, ...rest } = useEthereumTransaction(
108 useCallback(
109 async (manualSeed, isDiscontinuity) => {
110 const seed = await buildNetworkSeed(manualSeed);
111 const pair = deriveNetworkKeys(seed);
113 return azimuth.ecliptic.configureKeys(
114 _contracts,
115 _point,
116 addHexPrefix(pair.crypt.public),
117 addHexPrefix(pair.auth.public),
118 CRYPTO_SUITE_VERSION,
119 isDiscontinuity
120 );
121 },
122 [_contracts, _point, buildNetworkSeed]
123 ),
124 useCallback(
125 () => Promise.all([syncDetails(_point), syncRekeyDate(_point)]),
126 [_point, syncDetails, syncRekeyDate]
127 ),
128 GAS_LIMITS.CONFIGURE_KEYS
129 );
131 // only treat the transaction as completed once we also have keys to download
132 const completed = _completed && keyfileAvailable && !keyfileGenerating;
134 return {
135 completed,
136 filename,
137 keyfileBind,
138 ...rest,
139 };
142export default function UrbitOSNetworkingKeys({
143 manualNetworkSeed,
144 setManualNetworkSeed,
145}) {
146 const { pop } = useLocalRouter();
147 const { pointCursor } = usePointCursor();
148 const { getDetails } = usePointCache();
149 const {
150 point: { isL2 },
151 } = useRollerStore();
152 const { configureNetworkingKeys, getPendingTransactions } = useRoller();
153 const [breach, setBreach] = useState(false);
155 const point = need.point(pointCursor);
156 const details = getDetails(point);
158 const hasKeys = details.matchWith({
159 Nothing: () => false,
160 Just: ({ value: details }) => parseInt(details.keyRevisionNumber, 10) > 0,
161 // we actually don't mind the default NaN behavior of parseInt here,
162 // since NaN > 0 === false and that's a reasonable result
163 });
165 const {
166 construct,
167 unconstruct,
168 completed,
169 inputsLocked,
170 bind,
171 keyfileBind,
172 } = useSetKeys(manualNetworkSeed, setManualNetworkSeed);
174 const validateForm = useCallback((values, errors) => {
175 if (values.useNetworkSeed && errors.networkSeed) {
176 return errors;
177 }
178 }, []);
180 const validate = useMemo(
181 () =>
182 composeValidator(
183 {
184 useNetworkSeed: buildCheckboxValidator(),
185 networkSeed: buildHexValidator(64), // 64 chars
186 useDiscontinuity: buildCheckboxValidator(),
187 },
188 validateForm
189 ),
190 [validateForm]
191 );
193 const onValues = useCallback(
194 ({ valid, values, form }) => {
195 if (valid) {
196 construct(
197 values.useNetworkSeed ? values.networkSeed : undefined,
198 values.useDiscontinuity
199 );
200 setBreach(values.useDiscontinuity);
201 setManualNetworkSeed(values.useNetworkSeed);
202 } else {
203 unconstruct();
204 }
206 if (!values.useNetworkSeed && values.networkSeed) {
207 form.change('networkSeed', '');
208 setBreach(false);
209 setManualNetworkSeed('');
210 }
211 },
212 [construct, unconstruct, setManualNetworkSeed, setBreach]
213 );
215 const setNetworkingKeys = useCallback(async () => {
216 // setLoading(true);
217 try {
218 await configureNetworkingKeys({
219 breach,
220 manualNetworkSeed,
221 });
222 // TODO: just use the tx hash instead?
223 getPendingTransactions(point);
224 // TODO: this is just so we get visual feedback that the tx has gone through
225 // but this should be addressed with the new UI flow (-> download keyfile)
226 //
227 // A question here is how to deal with the modals/messages about the keys not being
228 // set since they are in pending in the Roller...
229 // we could inspect if there's a changeKeys in the local list of pending txs,...
230 //
231 pop();
232 } catch (error) {
233 // setError(error);
234 } finally {
235 // setLoading(false);
236 }
237 }, [
238 breach,
239 manualNetworkSeed,
240 getPendingTransactions,
241 point,
242 pop,
243 configureNetworkingKeys,
244 ]);
246 const initialValues = useMemo(
247 () => ({
248 useNetworkSeed: false,
249 useDiscontinuity: false,
250 }),
251 []
252 );
254 const viewTitle = completed
255 ? 'Network Keys are now set'
256 : 'Set Networking Keys';
258 const usageMessage =
259 'You need this keyfile to authenticate with your OS. Please Download.';
261 return (
262 <Window>
263 <HeaderPane>
264 <Row className="header-row">
265 <h5>{viewTitle}</h5>
266 </Row>
267 </HeaderPane>
268 <BodyPane>
269 {!completed && (
270 <Grid.Item className="gray4 f5 mv2 align-self-start" full>
271 Network Keys authenticate Urbit ID with Urbit OS.
272 </Grid.Item>
273 )}
274 {completed && (
275 <>
276 <Grid.Item
277 full
278 className="mb3"
279 as={DownloadKeyfileButton}
280 solid
281 left
282 {...keyfileBind}
283 />
284 <Grid.Item full as={AlertBox} className="mb8">
285 {usageMessage}
286 </Grid.Item>
287 </>
288 )}
289 <BridgeForm
290 validate={validate}
291 onValues={onValues}
292 initialValues={initialValues}>
293 {() => (
294 <Box width="100%">
295 {!completed && (
296 <>
297 <Grid.Item
298 full
299 as={ToggleInput}
300 name="useNetworkSeed"
301 label="Use Custom Network Seed"
302 inverseLabel="Back to Derived Network Seed"
303 disabled={inputsLocked}
304 />
305 <Condition when="useNetworkSeed" is={true}>
306 <Grid.Item full as={NoticeBox} className="mb2">
307 When using a custom network seed, you'll need to download
308 your Arvo keyfile immediately after this transaction as
309 Bridge does not store your seed.
310 </Grid.Item>
311 <Grid.Item
312 full
313 as={HexInput}
314 name="networkSeed"
315 label="Network Seed (32 bytes)"
316 disabled={inputsLocked}
317 className="mb6"
318 />
319 </Condition>
320 <Grid.Item
321 full
322 as={CheckboxInput}
323 name="useDiscontinuity"
324 label="Breach Continuity"
325 disabled={inputsLocked}
326 className="mb6"
327 />
329 <Grid.Item full as={FormError} />
330 </>
331 )}
333 {isL2 ? (
334 <Grid.Item
335 as={Button}
336 full
337 className=""
338 center
339 solid
340 onClick={setNetworkingKeys}>
341 {'Reset Networking Keys'}
342 </Grid.Item>
343 ) : (
344 <Grid.Item
345 full
346 as={InlineEthereumTransaction}
347 {...bind}
348 label={`${hasKeys ? 'Reset' : 'Set'} Networking Keys`}
349 onReturn={() => pop()}
350 />
351 )}
352 </Box>
353 )}
354 </BridgeForm>
355 </BodyPane>
356 </Window>
357 );