on 8d566ea help sign in
bridge/src/views/UrbitOS/NetworkingKeys.js
278 lines 8.1 kB history raw
1import React, { useCallback, useMemo, useRef, useState } from 'react';
2import { Just } from 'folktale/maybe';
3import { Grid, 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 attemptNetworkSeedDerivation,
16 deriveNetworkKeys,
17 CRYPTO_SUITE_VERSION,
18} from 'lib/keys';
19import useEthereumTransaction from 'lib/useEthereumTransaction';
20import { GAS_LIMITS } from 'lib/constants';
21import { addHexPrefix } from 'lib/wallet';
22import useKeyfileGenerator from 'lib/useKeyfileGenerator';
24import ViewHeader from 'components/ViewHeader';
25import DownloadKeyfileButton from 'components/DownloadKeyfileButton';
26import InlineEthereumTransaction from 'components/InlineEthereumTransaction';
27import NoticeBox from 'components/NoticeBox';
29import { HexInput } from 'form/Inputs';
30import {
31 composeValidator,
32 buildCheckboxValidator,
33 buildHexValidator,
34} from 'form/validators';
35import BridgeForm from 'form/BridgeForm';
36import Condition from 'form/Condition';
37import FormError from 'form/FormError';
38import convertToInt from 'lib/convertToInt';
40function useSetKeys() {
41 const { urbitWallet, wallet, authMnemonic } = useWallet();
42 const { pointCursor } = usePointCursor();
43 const { syncDetails, syncRekeyDate, getDetails } = usePointCache();
44 const { contracts } = useNetwork();
46 const _point = need.point(pointCursor);
47 const _contracts = need.contracts(contracts);
48 const _details = need.details(getDetails(_point));
50 const networkRevision = convertToInt(_details.keyRevisionNumber, 10);
51 const randomSeed = useRef();
53 // NOTE: nd = 'nondeterministic' (can also be a 'manual' seed)
54 const [ndNetworkSeed, setNdNetworkSeed] = useState();
56 const {
57 available: keyfileAvailable,
58 filename,
59 bind: keyfileBind,
60 } = useKeyfileGenerator(ndNetworkSeed);
62 const buildNetworkSeed = useCallback(
63 async manualSeed => {
64 if (manualSeed !== undefined) {
65 setNdNetworkSeed(manualSeed);
66 return manualSeed;
67 } else {
68 const newNetworkRevision = networkRevision + 1;
69 console.log(`deriving seed with revision ${newNetworkRevision}`);
71 const networkSeed = await attemptNetworkSeedDerivation({
72 urbitWallet,
73 wallet,
74 authMnemonic,
75 details: _details,
76 revision: newNetworkRevision,
77 });
79 if (Just.hasInstance(networkSeed)) {
80 return networkSeed.value;
81 }
83 randomSeed.current = randomSeed.current || randomHex(32); // 32 bytes
84 setNdNetworkSeed(randomSeed.current);
86 return randomSeed.current;
87 }
88 },
89 [_details, authMnemonic, networkRevision, urbitWallet, wallet]
90 );
92 const { completed: _completed, ...rest } = useEthereumTransaction(
93 useCallback(
94 async (manualSeed, isDiscontinuity) => {
95 const seed = await buildNetworkSeed(manualSeed);
96 const pair = deriveNetworkKeys(seed);
98 return azimuth.ecliptic.configureKeys(
99 _contracts,
100 _point,
101 addHexPrefix(pair.crypt.public),
102 addHexPrefix(pair.auth.public),
103 CRYPTO_SUITE_VERSION,
104 isDiscontinuity
105 );
106 },
107 [_contracts, _point, buildNetworkSeed]
108 ),
109 useCallback(
110 () => Promise.all([syncDetails(_point), syncRekeyDate(_point)]),
111 [_point, syncDetails, syncRekeyDate]
112 ),
113 GAS_LIMITS.CONFIGURE_KEYS
114 );
116 // only treat the transaction as completed once we also have keys to download
117 const completed = _completed && keyfileAvailable;
119 return {
120 completed,
121 ndNetworkSeed,
122 filename,
123 keyfileBind,
124 ...rest,
125 };
128export default function UrbitOSNetworkingKeys() {
129 const { pop } = useLocalRouter();
130 const { pointCursor } = usePointCursor();
131 const { getDetails } = usePointCache();
133 const point = need.point(pointCursor);
134 const details = getDetails(point);
136 const hasKeys = details.matchWith({
137 Nothing: () => false,
138 Just: ({ value: details }) => parseInt(details.keyRevisionNumber, 10) > 0,
139 // we actually don't mind the default NaN behavior of parseInt here,
140 // since NaN > 0 === false and that's a reasonable result
141 });
143 const {
144 construct,
145 unconstruct,
146 broadcasting,
147 completed,
148 inputsLocked,
149 bind,
150 keyfileBind,
151 } = useSetKeys();
153 const validateForm = useCallback((values, errors) => {
154 if (values.useNetworkSeed && errors.networkSeed) {
155 return errors;
156 }
157 }, []);
159 const validate = useMemo(
160 () =>
161 composeValidator(
162 {
163 useNetworkSeed: buildCheckboxValidator(),
164 networkSeed: buildHexValidator(64), // 64 chars
165 useDiscontinuity: buildCheckboxValidator(),
166 },
167 validateForm
168 ),
169 [validateForm]
170 );
172 const onValues = useCallback(
173 ({ valid, values, form }) => {
174 if (valid) {
175 construct(
176 values.useNetworkSeed ? values.networkSeed : undefined,
177 values.useDiscontinuity
178 );
179 } else {
180 unconstruct();
181 }
183 if (!values.useNetworkSeed && values.networkSeed) {
184 form.change('networkSeed', '');
185 }
186 },
187 [construct, unconstruct]
188 );
190 const initialValues = useMemo(
191 () => ({
192 useNetworkSeed: false,
193 useDiscontinuity: false,
194 }),
195 []
196 );
198 const usageMessage = 'You need this to authenticate with arvo';
200 return (
201 <>
202 <Grid>
203 <Grid.Item full as={ViewHeader}>
204 Set Networking Keys
205 </Grid.Item>
206 <Grid.Item className="gray4 f6" full>
207 Network Keys solidify the handshake between ID and OS
208 </Grid.Item>
209 {completed && (
210 <>
211 <Grid.Item
212 full
213 className="mv3"
214 as={DownloadKeyfileButton}
215 solid
216 {...keyfileBind}
217 />
218 <Grid.Item full className="mb3 bg-red3 white t-center p3">
219 {usageMessage}
220 </Grid.Item>
221 </>
222 )}
223 <BridgeForm
224 validate={validate}
225 onValues={onValues}
226 initialValues={initialValues}>
227 {() => (
228 <>
229 {!completed && (
230 <>
231 <Grid.Item
232 full
233 as={ToggleInput}
234 name="useNetworkSeed"
235 label="Use Custom Network Seed"
236 inverseLabel="Back to Derived Network Seed"
237 disabled={inputsLocked}
238 />
239 <Condition when="useNetworkSeed" is={true}>
240 <Grid.Item full as={NoticeBox} className="mb2">
241 When using a custom network seed, you'll need to download
242 your Arvo keyfile immediately after this transaction is
243 Bridge does not store your seed.
244 </Grid.Item>
245 <Grid.Item
246 full
247 as={HexInput}
248 name="networkSeed"
249 label="Network Seed (32 bytes)"
250 disabled={inputsLocked}
251 />
252 </Condition>
253 <Grid.Item
254 full
255 as={CheckboxInput}
256 name="useDiscontinuity"
257 label="Breach Continuity"
258 disabled={inputsLocked}
259 />
261 <Grid.Item full as={FormError} />
262 </>
263 )}
265 <Grid.Item
266 full
267 as={InlineEthereumTransaction}
268 {...bind}
269 label={`${hasKeys ? 'Reset' : 'Set'} Networking Keys`}
270 onReturn={() => pop()}
271 />
272 </>
273 )}
274 </BridgeForm>
275 </Grid>
276 </>
277 );