on cfae92f help sign in
bridge/src/views/Admin/AdminNetworkingKeys.js
398 lines 11 kB history raw
1import React, { useCallback, useMemo, useRef, useState } from 'react';
2import { Just, Nothing } from 'folktale/maybe';
3import { Grid, Text, H5, Flex, ToggleInput, CheckboxInput } 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';
12import { useLocalRouter } from 'lib/LocalRouter';
13import * as need from 'lib/need';
14import {
15 segmentNetworkKey,
16 attemptNetworkSeedDerivation,
17 deriveNetworkKeys,
18 CRYPTO_SUITE_VERSION,
19 CURVE_ZERO_ADDR,
20} from 'lib/keys';
21import { formatDotsWithTime } from 'lib/dateFormat';
22import useEthereumTransaction from 'lib/useEthereumTransaction';
23import { GAS_LIMITS } from 'lib/constants';
24import { addHexPrefix } from 'lib/wallet';
25import useKeyfileGenerator from 'lib/useKeyfileGenerator';
27import ViewHeader from 'components/ViewHeader';
28import { BootArvoButton } from 'components/Buttons';
29import FooterButton from 'components/FooterButton';
30import DownloadKeyfileButton from 'components/DownloadKeyfileButton';
31import InlineEthereumTransaction from 'components/InlineEthereumTransaction';
32import NoticeBox from 'components/NoticeBox';
34import { HexInput } from 'form/Inputs';
35import {
36 composeValidator,
37 buildCheckboxValidator,
38 buildHexValidator,
39} from 'form/validators';
40import BridgeForm from 'form/BridgeForm';
41import Condition from 'form/Condition';
42import FormError from 'form/FormError';
44const chainKeyProp = name => d =>
45 d[name] === CURVE_ZERO_ADDR ? Nothing() : Just(d[name]);
47const renderNetworkKey = key => {
48 const segments = segmentNetworkKey(key);
50 if (!segments) {
51 return 'Unset';
52 }
54 return segments.join('\n');
55};
57function useSetKeys() {
58 const { urbitWallet, wallet, authMnemonic } = useWallet();
59 const { pointCursor } = usePointCursor();
60 const { syncDetails, syncRekeyDate, getDetails } = usePointCache();
61 const { contracts } = useNetwork();
63 const _point = need.point(pointCursor);
64 const _contracts = need.contracts(contracts);
65 const _details = need.details(getDetails(_point));
67 const networkRevision = parseInt(_details.keyRevisionNumber, 10);
68 const randomSeed = useRef();
70 // NOTE: nd = 'nondeterministic' (can also be a 'manual' seed)
71 const [ndNetworkSeed, setNdNetworkSeed] = useState();
73 const {
74 available: keyfileAvailable,
75 bind: keyfileBind,
76 } = useKeyfileGenerator(ndNetworkSeed);
78 const buildNetworkSeed = useCallback(
79 async manualSeed => {
80 if (manualSeed !== undefined) {
81 setNdNetworkSeed(manualSeed);
82 return manualSeed;
83 } else {
84 const newNetworkRevision = networkRevision + 1;
85 console.log(`deriving seed with revision ${newNetworkRevision}`);
87 const networkSeed = await attemptNetworkSeedDerivation({
88 urbitWallet,
89 wallet,
90 authMnemonic,
91 details: _details,
92 revision: newNetworkRevision,
93 });
95 if (Just.hasInstance(networkSeed)) {
96 return networkSeed.value;
97 }
99 randomSeed.current = randomSeed.current || randomHex(64);
100 setNdNetworkSeed(randomSeed.current);
102 return randomSeed.current;
103 }
104 },
105 [_details, authMnemonic, networkRevision, urbitWallet, wallet]
106 );
108 const { completed: _completed, ...rest } = useEthereumTransaction(
109 useCallback(
110 async (manualSeed, isDiscontinuity) => {
111 const seed = await buildNetworkSeed(manualSeed);
112 const pair = deriveNetworkKeys(seed);
114 return azimuth.ecliptic.configureKeys(
115 _contracts,
116 _point,
117 addHexPrefix(pair.crypt.public),
118 addHexPrefix(pair.auth.public),
119 CRYPTO_SUITE_VERSION,
120 isDiscontinuity
121 );
122 },
123 [_contracts, _point, buildNetworkSeed]
124 ),
125 useCallback(
126 () => Promise.all([syncDetails(_point), syncRekeyDate(_point)]),
127 [_point, syncDetails, syncRekeyDate]
128 ),
129 GAS_LIMITS.CONFIGURE_KEYS
130 );
132 // only treat the transaction as completed once we also have keys to download
133 const completed = _completed && keyfileAvailable;
135 return {
136 completed,
137 ndNetworkSeed,
138 keyfileBind,
139 ...rest,
140 };
143export default function AdminNetworkingKeys() {
144 const { push, names, pop } = useLocalRouter();
145 const { pointCursor } = usePointCursor();
146 const { getDetails, getRekeyDate } = usePointCache();
148 const point = need.point(pointCursor);
149 const details = getDetails(point);
151 const hasKeys = details.matchWith({
152 Nothing: () => false,
153 Just: ({ value: details }) => parseInt(details.keyRevisionNumber, 10) > 0,
154 });
156 const {
157 isDefaultState,
158 construct,
159 unconstruct,
160 broadcasting,
161 completed,
162 inputsLocked,
163 bind,
164 keyfileBind,
165 } = useSetKeys();
167 const validateForm = useCallback((values, errors) => {
168 if (values.useNetworkSeed && errors.networkSeed) {
169 return errors;
170 }
171 }, []);
173 const validate = useMemo(
174 () =>
175 composeValidator(
176 {
177 useNetworkSeed: buildCheckboxValidator(),
178 networkSeed: buildHexValidator(32),
179 useDiscontinuity: buildCheckboxValidator(),
180 },
181 validateForm
182 ),
183 [validateForm]
184 );
186 const onValues = useCallback(
187 ({ valid, values, form }) => {
188 if (valid) {
189 construct(
190 values.useNetworkSeed ? values.networkSeed : undefined,
191 values.useDiscontinuity
192 );
193 } else {
194 unconstruct();
195 }
197 if (!values.useNetworkSeed && values.networkSeed) {
198 form.change('networkSeed', '');
199 }
200 },
201 [construct, unconstruct]
202 );
204 const initialValues = useMemo(
205 () => ({
206 useNetworkSeed: false,
207 useDiscontinuity: false,
208 }),
209 []
210 );
212 const goRelocate = useCallback(() => push(names.RELOCATE), [push, names]);
214 const renderTitle = () => {
215 if (completed) {
216 return 'Networking keys are now set. Download your Keyfile to authenticate Arvo.';
217 }
219 if (broadcasting) {
220 return 'Setting Network Keys...';
221 }
223 if (!hasKeys) {
224 return 'Networking keys have not yet been set.';
225 }
227 return 'Networking';
228 };
230 const renderNetworkKeySection = (title, key) => (
231 <>
232 <Grid.Item full as={H5} className="mt3 gray4">
233 {title}
234 </Grid.Item>
235 {key.matchWith({
236 Nothing: () => (
237 <Grid.Item full as="code" className="f5 mono gray4">
238 Unset
239 </Grid.Item>
240 ),
241 Just: ({ value: key }) => (
242 <>
243 <Grid.Item full as="code" className="f5 mono wrap">
244 0x
245 </Grid.Item>
246 <Grid.Item full as="code" className="f5 mono wrap">
247 {renderNetworkKey(key)}
248 </Grid.Item>
249 </>
250 ),
251 })}
252 </>
253 );
255 const renderDetail = (title, value) => (
256 <Flex.Item as={Flex} col>
257 <Flex.Item as={H5} className="gray4">
258 {title}
259 </Flex.Item>
260 {value.matchWith({
261 Nothing: () => (
262 <Flex.Item as={Text} className="f5 gray4">
263 Unset
264 </Flex.Item>
265 ),
266 Just: ({ value }) => <Flex.Item as={Text}>{value}</Flex.Item>,
267 })}
268 </Flex.Item>
269 );
271 const renderDetails = () => {
272 return (
273 <>
274 {renderNetworkKeySection(
275 'Authentication',
276 details.chain(chainKeyProp('authenticationKey'))
277 )}
278 {renderNetworkKeySection(
279 'Encryption',
280 details.chain(chainKeyProp('encryptionKey'))
281 )}
282 <Grid.Item full as={Flex} row justify="between" className="mt3">
283 {renderDetail('Revision', details.map(d => d.keyRevisionNumber))}
284 {renderDetail('Continuity Era', details.map(d => d.continuityNumber))}
285 {renderDetail(
286 'Crypto Suite Ver.',
287 details.map(d => d.cryptoSuiteVersion)
288 )}
289 </Grid.Item>
290 {hasKeys && (
291 <Grid.Item full as={Flex} row justify="between" className="mt3">
292 {renderDetail(
293 'Last Set',
294 getRekeyDate(point).map(date =>
295 date.matchWith({
296 Ok: r => formatDotsWithTime(r.value),
297 Error: () => Nothing(),
298 })
299 )
300 )}
301 </Grid.Item>
302 )}
303 </>
304 );
305 };
307 return (
308 <>
309 <Grid>
310 <Grid.Item full as={ViewHeader}>
311 {renderTitle()}
312 </Grid.Item>
314 <Grid.Item full as={Text} className="mb3">
315 {hasKeys
316 ? 'Here are your public keys that authenticate your Arvo.'
317 : 'Set your networking keys to authenticate with Arvo.'}
318 </Grid.Item>
320 {completed && (
321 <>
322 <Grid.Item full as={NoticeBox} className="mb3">
323 You need this keyfile to authenticate with Arvo. If you have
324 already booted Arvo, run <code>|rekey '0wkeyfile.contents'</code>
325 </Grid.Item>
326 <Grid.Item full as={DownloadKeyfileButton} solid {...keyfileBind} />
327 </>
328 )}
330 {!completed && (
331 <BridgeForm
332 validate={validate}
333 onValues={onValues}
334 initialValues={initialValues}>
335 {({ handleSubmit }) => (
336 <>
337 <Grid.Item
338 full
339 as={ToggleInput}
340 name="useNetworkSeed"
341 label="Use Custom Network Seed"
342 inverseLabel="Back to Derived Network Seed"
343 disabled={inputsLocked}
344 />
345 <Condition when="useNetworkSeed" is={true}>
346 <Grid.Item full as={NoticeBox} className="mb2">
347 When using a custom network seed, you'll need to download
348 your Arvo keyfile immediately after this transaction is
349 Bridge does not store your seed.
350 </Grid.Item>
351 <Grid.Item
352 full
353 as={HexInput}
354 name="networkSeed"
355 label="Network Seed (64 bytes)"
356 disabled={inputsLocked}
357 />
358 </Condition>
359 <Grid.Item
360 full
361 as={CheckboxInput}
362 name="useDiscontinuity"
363 label="Trigger New Continuity Era"
364 disabled={inputsLocked}
365 />
367 <Grid.Item full as={FormError} />
369 <Grid.Item
370 full
371 as={InlineEthereumTransaction}
372 {...bind}
373 label={`${hasKeys ? 'Reset' : 'Set'} Networking Keys`}
374 onReturn={() => pop()}
375 />
376 </>
377 )}
378 </BridgeForm>
379 )}
381 {isDefaultState && renderDetails()}
383 {completed && (
384 <>
385 <Grid.Item full as={BootArvoButton} disabled />
386 <Grid.Divider />
387 </>
388 )}
389 </Grid>
391 {isDefaultState && (
392 <FooterButton onClick={goRelocate} disabled>
393 Relocate
394 </FooterButton>
395 )}
396 </>
397 );