on 5f71b99 help sign in
bridge/src/views/SetKeys.js
436 lines 11 kB history raw
1import React from 'react'
2import Maybe from 'folktale/maybe'
3import * as azimuth from 'azimuth-js'
4import * as ob from 'urbit-ob'
5import { Row, Col, H1, P, Warning, H3 } from '../components/Base'
6import { RequiredInput, InnerLabel } from '../components/Base'
8import StatelessTransaction from '../components/StatelessTransaction'
9import { BRIDGE_ERROR } from '../lib/error'
10import { ROUTE_NAMES } from '../lib/router'
11import { attemptSeedDerivation, genKey } from '../lib/keys'
13import saveAs from 'file-saver'
15import { WALLET_NAMES } from '../lib/wallet'
17import * as kg from '../../node_modules/urbit-key-generation/dist/index'
19import {
20 sendSignedTransaction,
21 fromWei,
22 } from '../lib/txn'
24import {
25 addressFromSecp256k1Public,
26 addHexPrefix
27} from '../lib/wallet'
29class SetKeys extends React.Component {
30 constructor(props) {
31 super(props)
33 const point = props.pointCursor.matchWith({
34 Just: (shp) => shp.value,
35 Nothing: () => {
36 throw BRIDGE_ERROR.MISSING_POINT
37 }
38 })
40 this.state = {
41 auth: '',
42 encr: '',
43 networkSeed: '',
44 point: point,
45 cryptoSuiteVersion: 1,
46 continuity: false,
47 txn: Maybe.Nothing(),
48 txError: Maybe.Nothing(),
49 isManagementSeed: false,
50 userApproval: false,
51 nonce: '',
52 gasPrice: '5',
53 showGasDetails: false,
54 chainId: '',
55 gasLimit: '600000',
56 stx: Maybe.Nothing(),
57 }
59 this.handleNetworkSeedInput = this.handleNetworkSeedInput.bind(this)
60 // Transaction
61 this.handleCreateUnsignedTxn = this.handleCreateUnsignedTxn.bind(this)
62 this.handleSubmit = this.handleSubmit.bind(this)
63 this.handleSetUserApproval = this.handleSetUserApproval.bind(this)
64 this.handleSetTxn = this.handleSetTxn.bind(this)
65 this.handleSetStx = this.handleSetStx.bind(this)
66 this.handleSetNonce = this.handleSetNonce.bind(this)
67 this.handleSetChainId = this.handleSetChainId.bind(this)
68 this.handleSetGasPrice = this.handleSetGasPrice.bind(this)
69 this.handleSetGasLimit = this.handleSetGasLimit.bind(this)
70 this.toggleGasDetails = this.toggleGasDetails.bind(this)
71 }
73 toggleGasDetails() {
74 this.setState({
75 showGasDetails: !this.state.showGasDetails
76 })
77 }
79 componentDidMount() {
80 const { props } = this
82 this.deriveSeed()
84 const addr = props.wallet.matchWith({
85 Just: wal => addressFromSecp256k1Public(wal.value.publicKey),
86 Nothing: () => {
87 throw BRIDGE_ERROR.MISSING_WALLET
88 }
89 })
91 this.determineManagementSeed(props.contracts.value, addr)
93 props.web3.matchWith({
94 Nothing: () => {},
95 Just: (w3) => {
96 const validWeb3 = w3.value
98 const getTxMetadata = [
99 validWeb3.eth.getTransactionCount(addr),
100 validWeb3.eth.net.getId(),
101 validWeb3.eth.getGasPrice()
102 ];
104 Promise.all(getTxMetadata).then(r => {
105 const txMetadata = {
106 nonce: r[0],
107 chainId: r[1],
108 gasPrice: fromWei(r[2], 'gwei'),
109 };
111 this.setState({...txMetadata})
113 })
114 }
115 });
116 }
118 async determineManagementSeed(ctrcs, addr) {
119 const managing =
120 await azimuth.azimuth.getManagerFor(ctrcs, addr)
122 this.setState({
123 isManagementSeed: managing.length !== 0
124 })
125 }
127 randomHex(len) {
128 let hex = "";
130 for (var i = 0; i < len; i++) {
131 hex = hex + ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
132 'C', 'D', 'E', 'F'][Math.floor(Math.random() * 16)]
133 }
135 return hex;
136 }
138 async deriveSeed() {
139 const next = true
140 let seed = await attemptSeedDerivation(next, this.props)
142 if (seed.getOrElse('') === '') {
143 seed = Maybe.Just(this.randomHex(64));
144 }
146 this.setState({
147 networkSeed: seed.getOrElse('')
148 })
149 }
151 handleNetworkSeedInput(networkSeed) {
152 this.setState({ networkSeed })
153 }
155 handleCreateUnsignedTxn() {
156 const txn = this.createUnsignedTxn()
157 this.setState({ txn })
158 }
161 handleSetUserApproval(){
162 const {state} = this
163 this.setState({ userApproval: !state.userApproval })
164 }
168 handleSetTxn(txn){
169 this.setState({ txn })
170 }
174 handleSetStx(stx){
175 this.setState({
176 stx,
177 userApproval: false,
178 })
179 }
183 handleSetNonce(nonce){
184 this.setState({ nonce })
185 this.handleClearStx()
186 }
190 handleSetChainId(chainId){
191 this.setState({ chainId })
192 this.handleClearStx()
193 }
197 handleSetGasPrice(gasPrice){
198 this.setState({ gasPrice })
199 this.handleClearStx()
200 }
204 handleSetGasLimit(gasLimit){
205 this.setState({ gasLimit })
206 this.handleClearStx()
207 }
211 handleClearStx() {
212 this.setState({
213 userApproval: false,
214 stx: Maybe.Nothing(),
215 })
216 }
221 handleClearTxn() {
222 this.setState({
223 userApproval: false,
224 txn: Maybe.Nothing(),
225 stx: Maybe.Nothing(),
226 })
227 }
231 handleClearTransaction() {
232 this.setState({
233 userApproval: false,
234 txn: Maybe.Nothing(),
235 stx: Maybe.Nothing(),
236 })
237 }
239 downloadKeyfile(networkSeed) {
240 const { pointCache } = this.props
241 const { pointCursor } = this.props
243 const point = pointCursor.matchWith({
244 Just: (pt) => pt.value,
245 Nothing: () => {
246 throw BRIDGE_ERROR.MISSING_POINT
247 }
248 })
250 const pointDetails =
251 point in pointCache
252 ? pointCache[point]
253 : (() => { throw BRIDGE_ERROR.MISSING_POINT })()
255 const revision = parseInt(pointDetails.keyRevisionNumber)
256 const keyfile = genKey(networkSeed, point, revision)
257 let blob = new Blob([keyfile], {type:"text/plain;charset=utf-8"});
258 saveAs(blob, `${ob.patp(point).slice(1)}-${revision}.key`)
259 }
261 handleSubmit(){
262 const { props, state } = this
263 sendSignedTransaction(props.web3.value, state.stx)
264 .then(sent => {
265 props.setNetworkSeedCache(this.state.networkSeed)
266 this.downloadKeyfile(this.state.networkSeed)
267 props.setTxnHashCursor(sent)
268 props.popRoute()
269 props.pushRoute(ROUTE_NAMES.SENT_TRANSACTION)
270 })
271 .catch(err => {
272 this.setState({ txError: err.map(val => val.merge()) })
273 })
274 }
278 createUnsignedTxn() {
279 const { state, props } = this
281 const validContracts = props.contracts.matchWith({
282 Just: (cs) => cs.value,
283 Nothing: () => {
284 throw BRIDGE_ERROR.MISSING_CONTRACTS
285 }
286 })
288 const validPoint = props.pointCursor.matchWith({
289 Just: (shp) => shp.value,
290 Nothing: () => {
291 throw BRIDGE_ERROR.MISSING_POINT
292 }
293 })
295 const hexRegExp = /[0-9A-Fa-f]{64}/g
297 if (hexRegExp.test(state.networkSeed)) {
298 // derive network keys
299 const pair = kg.deriveNetworkKeys(state.networkSeed)
301 const pencr = addHexPrefix(pair.crypt.public)
302 const pauth = addHexPrefix(pair.auth.public)
304 const txn = azimuth.ecliptic.configureKeys(
305 validContracts,
306 validPoint,
307 pencr,
308 pauth,
309 1,
310 false
311 )
313 return Maybe.Just(txn)
314 }
316 return Maybe.Nothing()
317 }
319 render() {
320 const { props, state } = this
322 const canGenerate =
323 state.networkSeed.length === 64
324 && state.networkSeed.length === 64
326 const canSign = Maybe.Just.hasInstance(state.txn)
327 const canApprove = Maybe.Just.hasInstance(state.stx)
329 const canSend =
330 Maybe.Just.hasInstance(state.stx)
331 && state.userApproval === true
333 const pointDetails =
334 state.point in props.pointCache
335 ? props.pointCache[state.point]
336 : (() => { throw BRIDGE_ERROR.MISSING_POINT })()
338 const isManagementMnemonic =
339 this.state.isManagementSeed &&
340 props.walletType === WALLET_NAMES.MNEMONIC
342 const isMasterTicket =
343 props.walletType === WALLET_NAMES.TICKET ||
344 props.walletType === WALLET_NAMES.SHARD
346 const networkSeedDisabled = isManagementMnemonic || isMasterTicket;
348 return (
349 <Row>
350 <Col>
351 <H1>
352 { 'Set Network Keys For ' } <code>{ `${ob.patp(state.point)}` }</code>
353 </H1>
355 <P>
356 {
357 `Set new authentication and encryption keys for your Arvo ship. Once the transaction is sent, a keyfile will be downloaded, enabling you to instantiate your ship on the network.`
358 }
359 </P>
361 { pointDetails.keyRevisionNumber === '0'
362 ? <Warning>
363 <h3 className={'mb-2'}>{'Warning'}</h3>
364 {
365 'Once these keys have been set, your point is considered ' +
366 "'linked'. This operation cannot be undone."
367 }
368 </Warning>
369 : <div /> }
371 <RequiredInput
372 className='mono'
373 prop-size='lg'
374 prop-format='innerLabel'
375 autoFocus
376 disabled= { networkSeedDisabled }
377 value={ state.networkSeed }
378 onChange={ this.handleNetworkSeedInput }>
379 <InnerLabel>{ 'Network seed' }</InnerLabel>
380 </RequiredInput>
382 <StatelessTransaction
383 // Upper scope
384 web3={props.web3}
385 contracts={props.contracts}
386 wallet={props.wallet}
387 walletType={props.walletType}
388 walletHdPath={props.walletHdPath}
389 networkType={props.networkType}
390 // Tx
391 txn={state.txn}
392 stx={state.stx}
393 // Tx details
394 nonce={state.nonce}
395 gasPrice={state.gasPrice}
396 chainId={state.chainId}
397 gasLimit={state.gasLimit}
398 showGasDetails={state.showGasDetails}
399 toggleGasDetails={this.toggleGasDetails}
400 // Checks
401 userApproval={state.userApproval}
402 canGenerate={ canGenerate }
403 canSign={ canSign }
404 canApprove={ canApprove }
405 canSend={ canSend }
406 // Methods
407 createUnsignedTxn={this.handleCreateUnsignedTxn}
408 setUserApproval={this.handleSetUserApproval}
409 setTxn={this.handleSetTxn}
410 setStx={this.handleSetStx}
411 setNonce={this.handleSetNonce}
412 setChainId={this.handleSetChainId}
413 setGasPrice={this.handleSetGasPrice}
414 setGasLimit={this.handleSetGasLimit}
415 handleSubmit={this.handleSubmit} />
417 {
418 Maybe.Nothing.hasInstance(state.txError)
419 ? ''
420 : <Warning className={'mt-8'}>
421 <H3 style={{marginTop: 0, paddingTop: 0}}>
422 {
423 'There was an error sending your transaction.'
424 }
425 </H3>
426 { state.txError.value }
427 </Warning>
428 }
430 </Col>
431 </Row>
432 )
433 }
436export default SetKeys