Browse Source

feature(unlockWallet): ability to unlock wallet with helpful error messages

renovate/lint-staged-8.x
Jack Mallers 7 years ago
parent
commit
24ae067ad9
  1. 35
      app/components/Onboarding/InitWallet.js
  2. 60
      app/components/Onboarding/InitWallet.scss
  3. 43
      app/components/Onboarding/Login.js
  4. 124
      app/components/Onboarding/Login.scss
  5. 58
      app/components/Onboarding/NewWalletPassword.js
  6. 24
      app/components/Onboarding/NewWalletPassword.scss
  7. 20
      app/components/Onboarding/NewWalletSeed.js
  8. 11
      app/components/Onboarding/NewWalletSeed.scss
  9. 59
      app/components/Onboarding/Onboarding.js
  10. 19
      app/components/Onboarding/Signup.js
  11. 0
      app/components/Onboarding/Signup.scss
  12. 52
      app/containers/Root.js
  13. 1
      app/icons/eye.svg
  14. 153
      app/lnd/config/rpc.proto
  15. 18
      app/lnd/index.js
  16. 13
      app/lnd/init/index.js
  17. 24
      app/lnd/lib/grpcInit.js
  18. 2
      app/lnd/lib/lightning.js
  19. 148
      app/lnd/lib/rpc.proto
  20. 16
      app/lnd/lib/walletUnlocker.js
  21. 46
      app/lnd/methods/walletController.js
  22. 30
      app/lnd/walletUnlockerMethods/index.js
  23. 36
      app/main.dev.js
  24. 18
      app/reducers/ipc.js
  25. 124
      app/reducers/onboarding.js
  26. 148
      app/rpc.proto

35
app/components/Onboarding/InitWallet.js

@ -0,0 +1,35 @@
import React from 'react'
import PropTypes from 'prop-types'
import Login from './Login'
import Signup from './Signup'
import styles from './InitWallet.scss'
const InitWallet = ({
password,
passwordIsValid,
hasSeed,
updatePassword,
createWallet,
unlockWallet,
unlockingWallet,
unlockWalletError
}) => (
<div className={styles.container}>
{
hasSeed ?
<Login
password={password}
updatePassword={updatePassword}
unlockingWallet={unlockingWallet}
unlockWallet={unlockWallet}
unlockWalletError={unlockWalletError}
/>
:
<Signup />
}
</div>
)
InitWallet.propTypes = {}
export default InitWallet

60
app/components/Onboarding/InitWallet.scss

@ -0,0 +1,60 @@
@import '../../variables.scss';
.container {
position: relative;
}
.password {
background: transparent;
outline: none;
border: 0;
color: $gold;
-webkit-text-fill-color: $white;
font-size: 22px;
}
.password::-webkit-input-placeholder {
text-shadow: none;
-webkit-text-fill-color: initial;
}
.buttons {
margin-top: 15%;
text-align: center;
div {
color: $white;
&:nth-child(1) {
text-align: center;
margin-bottom: 40px;
span {
padding: 15px 35px;
background: $darkspaceblue;
font-size: 14px;
opacity: 0.5;
transition: all 0.25s;
&.active {
opacity: 1.0;
cursor: pointer;
&:hover {
background: lighten($darkspaceblue, 10%);
}
}
}
}
&:nth-child(2), &:nth-child(3) {
font-size: 12px;
cursor: pointer;
margin: 10px 0;
&:hover {
text-decoration: underline;
}
}
}
}

43
app/components/Onboarding/Login.js

@ -0,0 +1,43 @@
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Login.scss'
const Login = ({
password,
updatePassword,
unlockingWallet,
unlockWallet,
unlockWalletError
}) => (
<div className={styles.container}>
<input
type='password'
placeholder='Password'
className={`${styles.password} ${unlockWalletError.isError && styles.inputError}`}
ref={input => input && input.focus()}
value={password}
onChange={event => updatePassword(event.target.value)}
/>
<p className={`${unlockWalletError.isError && styles.active} ${styles.error}`}>
{unlockWalletError.message}
</p>
<section className={styles.buttons}>
<div>
<span className={`${!unlockingWallet && styles.active} ${styles.button}`} onClick={() => unlockWallet(password)}>
{
unlockingWallet ?
<i className={styles.spinner} />
:
'Log In'
}
</span>
</div>
<div>Recover existing wallet</div>
</section>
</div>
)
Login.propTypes = {}
export default Login

124
app/components/Onboarding/Login.scss

@ -0,0 +1,124 @@
@import '../../variables.scss';
.container {
position: relative;
}
.password {
background: transparent;
outline: none;
border: 0;
color: $gold;
-webkit-text-fill-color: $white;
font-size: 22px;
border-bottom: 1px solid transparent;
transition: all 0.25s;
&.inputError {
border-bottom: 1px solid $red;
}
}
.password::-webkit-input-placeholder {
text-shadow: none;
-webkit-text-fill-color: initial;
}
.error {
margin-top: 20px;
color: $red;
visibility: hidden;
font-size: 12px;
transition: all 0.25s;
&.active {
visibility: visible;
}
}
.buttons {
margin-top: 15%;
text-align: center;
div {
color: $white;
&:nth-child(1) {
text-align: center;
margin-bottom: 40px;
span {
padding: 15px 35px;
background: $darkspaceblue;
font-size: 14px;
opacity: 0.5;
transition: all 0.25s;
&.button {
position: relative;
}
&.active {
opacity: 1.0;
cursor: pointer;
&:hover {
background: lighten($darkspaceblue, 10%);
}
}
}
}
&:nth-child(2), &:nth-child(3) {
font-size: 12px;
cursor: pointer;
margin: 10px 0;
&:hover {
text-decoration: underline;
}
}
}
}
.spinner {
height: 20px;
width: 20px;
border: 1px solid rgba(235, 184, 100, 0.1);
border-left-color: rgba(235, 184, 100, 0.4);
-webkit-border-radius: 999px;
-moz-border-radius: 999px;
border-radius: 999px;
-webkit-animation: animation-rotate 1000ms linear infinite;
-moz-animation: animation-rotate 1000ms linear infinite;
-o-animation: animation-rotate 1000ms linear infinite;
animation: animation-rotate 1000ms linear infinite;
display: inline-block;
position: absolute;
top: calc(50% - 10px);
left: calc(50% - 10px);
}
@-webkit-keyframes animation-rotate {
100% {
-webkit-transform: rotate(360deg);
}
}
@-moz-keyframes animation-rotate {
100% {
-moz-transform: rotate(360deg);
}
}
@-o-keyframes animation-rotate {
100% {
-o-transform: rotate(360deg);
}
}
@keyframes animation-rotate {
100% {
transform: rotate(360deg);
}
}

58
app/components/Onboarding/NewWalletPassword.js

@ -0,0 +1,58 @@
import React from 'react'
import PropTypes from 'prop-types'
import Isvg from 'react-inlinesvg'
import eye from 'icons/eye.svg'
import styles from './NewWalletPassword.scss'
class NewWalletPassword extends React.Component {
constructor(props) {
super(props)
this.state = {
inputType: 'password',
confirmPassword: ''
}
}
render() {
const { createWalletPassword, updateCreateWalletPassword } = this.props
const { inputType, confirmPassword } = this.state
const toggleInputType = () => {
const newInputType = inputType === 'password' ? 'text' : 'password'
this.setState({ inputType: newInputType })
}
return (
<div className={styles.container}>
<section className={styles.input}>
<input
type={inputType}
placeholder='Password'
className={styles.password}
value={createWalletPassword}
onChange={event => updateCreateWalletPassword(event.target.value)}
/>
</section>
<section className={styles.input}>
<input
type={inputType}
placeholder='Confirm Password'
className={styles.password}
value={confirmPassword}
onChange={event => this.setState({ confirmPassword: event.target.value })}
/>
</section>
</div>
)
}
}
NewWalletPassword.propTypes = {
createWalletPassword: PropTypes.string.isRequired,
updateCreateWalletPassword: PropTypes.func.isRequired
}
export default NewWalletPassword

24
app/components/Onboarding/NewWalletPassword.scss

@ -0,0 +1,24 @@
@import '../../variables.scss';
.input:nth-child(2) {
margin-top: 40px;
}
.password {
background: transparent;
outline: none;
border: 0;
color: $gold;
-webkit-text-fill-color: $white;
font-size: 22px;
transition: all 0.25s;
&.error {
border-bottom: 1px solid $red;
}
}
.password::-webkit-input-placeholder {
text-shadow: none;
-webkit-text-fill-color: initial;
}

20
app/components/Onboarding/NewWalletSeed.js

@ -0,0 +1,20 @@
import React from 'react'
import PropTypes from 'prop-types'
import styles from './NewWalletSeed.scss'
const NewWalletSeed = ({ seed }) => (
<div className={styles.container}>
{
seed.length > 0 ?
seed.join(', ')
:
'loading'
}
</div>
)
NewWalletSeed.propTypes = {
seed: PropTypes.array.isRequired
}
export default NewWalletSeed

11
app/components/Onboarding/NewWalletSeed.scss

@ -0,0 +1,11 @@
@import '../../variables.scss';
.container {
background: darken(#242833, 10%);
padding: 20px 40px;
font-size: 14px;
line-height: 50px;
color: $white;
font-family: 'Roboto';
letter-spacing: 1.5px;
}

59
app/components/Onboarding/Onboarding.js

@ -6,25 +6,35 @@ import LoadingBolt from 'components/LoadingBolt'
import FormContainer from './FormContainer' import FormContainer from './FormContainer'
import Alias from './Alias' import Alias from './Alias'
import Autopilot from './Autopilot' import Autopilot from './Autopilot'
import InitWallet from './InitWallet'
import NewWalletSeed from './NewWalletSeed'
import NewWalletPassword from './NewWalletPassword'
import styles from './Onboarding.scss' import styles from './Onboarding.scss'
const Onboarding = ({ const Onboarding = ({
onboarding: { onboarding: {
step, step,
alias, alias,
autopilot autopilot,
startingLnd,
createWalletPassword,
seed
}, },
changeStep, changeStep,
submit, startLnd,
submitNewWallet,
aliasProps, aliasProps,
autopilotProps initWalletProps,
autopilotProps,
newWalletSeedProps,
newWalletPasswordProps
}) => { }) => {
const renderStep = () => { const renderStep = () => {
switch (step) { switch (step) {
case 1: case 1:
return ( return (
<FormContainer <FormContainer
title='1. What should we call you?' title='What should we call you?'
description='Set your nickname to help others connect with you on the Lightning Network' description='Set your nickname to help others connect with you on the Lightning Network'
back={null} back={null}
next={() => changeStep(2)} next={() => changeStep(2)}
@ -35,19 +45,54 @@ const Onboarding = ({
case 2: case 2:
return ( return (
<FormContainer <FormContainer
title='2. Autopilot' title='Autopilot'
description='Autopilot is an automatic network manager. Instead of manually adding people to build your network to make payments, enable autopilot to automatically connect you to the Lightning Network using 60% of your balance.' // eslint-disable-line description='Autopilot is an automatic network manager. Instead of manually adding people to build your network to make payments, enable autopilot to automatically connect you to the Lightning Network using 60% of your balance.' // eslint-disable-line
back={() => changeStep(1)} back={() => changeStep(1)}
next={() => submit(alias, autopilot)} next={() => startLnd(alias, autopilot)}
> >
<Autopilot {...autopilotProps} /> <Autopilot {...autopilotProps} />
</FormContainer> </FormContainer>
) )
case 3:
return (
<FormContainer
title='Welcome!'
description='Enter your wallet password or create a new wallet' // eslint-disable-line
back={() => changeStep(2)}
next={null}
>
<InitWallet {...initWalletProps} />
</FormContainer>
)
case 4:
return (
<FormContainer
title='Save your wallet seed'
description='Please save these 24 words securely! This will allow you to recover your wallet in the future' // eslint-disable-line
back={() => changeStep(3)}
next={() => changeStep(5)}
>
<NewWalletSeed {...newWalletSeedProps} />
</FormContainer>
)
case 5:
return (
<FormContainer
title='Set your password'
description='Choose a password to encrypt your wallet' // eslint-disable-line
back={() => changeStep(4)}
next={() => submitNewWallet(createWalletPassword, seed)}
>
<NewWalletPassword {...newWalletPasswordProps} />
</FormContainer>
)
default: default:
return <LoadingBolt /> return <LoadingBolt />
} }
} }
if (startingLnd) { return <LoadingBolt /> }
return ( return (
<div className={styles.container}> <div className={styles.container}>
{renderStep()} {renderStep()}
@ -60,7 +105,7 @@ Onboarding.propTypes = {
aliasProps: PropTypes.object.isRequired, aliasProps: PropTypes.object.isRequired,
autopilotProps: PropTypes.object.isRequired, autopilotProps: PropTypes.object.isRequired,
changeStep: PropTypes.func.isRequired, changeStep: PropTypes.func.isRequired,
submit: PropTypes.func.isRequired startLnd: PropTypes.func.isRequired
} }
export default Onboarding export default Onboarding

19
app/components/Onboarding/Signup.js

@ -0,0 +1,19 @@
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Signup.scss'
const Signup = ({
password,
passwordIsValid,
hasSeed,
updatePassword,
createWallet
}) => (
<div className={styles.container}>
signup yo
</div>
)
Signup.propTypes = {}
export default Signup

0
app/components/Onboarding/Signup.scss

52
app/containers/Root.js

@ -7,15 +7,31 @@ import PropTypes from 'prop-types'
import LoadingBolt from '../components/LoadingBolt' import LoadingBolt from '../components/LoadingBolt'
import Onboarding from '../components/Onboarding' import Onboarding from '../components/Onboarding'
import Syncing from '../components/Onboarding/Syncing' import Syncing from '../components/Onboarding/Syncing'
import { updateAlias, setAutopilot, changeStep, submit } from '../reducers/onboarding' import {
updateAlias,
updatePassword,
setAutopilot,
changeStep,
startLnd,
createWallet,
updateCreateWalletPassword,
submitNewWallet,
onboardingSelectors,
unlockWallet
} from '../reducers/onboarding'
import { fetchBlockHeight, lndSelectors } from '../reducers/lnd' import { fetchBlockHeight, lndSelectors } from '../reducers/lnd'
import Routes from '../routes' import Routes from '../routes'
const mapDispatchToProps = { const mapDispatchToProps = {
updateAlias, updateAlias,
updatePassword,
updateCreateWalletPassword,
setAutopilot, setAutopilot,
changeStep, changeStep,
submit, startLnd,
createWallet,
submitNewWallet,
unlockWallet,
fetchBlockHeight fetchBlockHeight
} }
@ -24,7 +40,8 @@ const mapStateToProps = state => ({
lnd: state.lnd, lnd: state.lnd,
onboarding: state.onboarding, onboarding: state.onboarding,
syncPercentage: lndSelectors.syncPercentage(state) syncPercentage: lndSelectors.syncPercentage(state),
passwordIsValid: onboardingSelectors.passwordIsValid(state)
}) })
const mergeProps = (stateProps, dispatchProps, ownProps) => { const mergeProps = (stateProps, dispatchProps, ownProps) => {
@ -43,12 +60,37 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => {
setAutopilot: dispatchProps.setAutopilot setAutopilot: dispatchProps.setAutopilot
} }
const initWalletProps = {
password: stateProps.onboarding.password,
passwordIsValid: stateProps.passwordIsValid,
hasSeed: stateProps.onboarding.hasSeed,
unlockingWallet: stateProps.onboarding.unlockingWallet,
unlockWalletError: stateProps.onboarding.unlockWalletError,
updatePassword: dispatchProps.updatePassword,
createWallet: dispatchProps.createWallet,
unlockWallet: dispatchProps.unlockWallet
}
const newWalletSeedProps = {
seed: stateProps.onboarding.seed
}
const newWalletPasswordProps = {
createWalletPassword: stateProps.onboarding.createWalletPassword,
updateCreateWalletPassword: dispatchProps.updateCreateWalletPassword
}
const onboardingProps = { const onboardingProps = {
onboarding: stateProps.onboarding, onboarding: stateProps.onboarding,
changeStep: dispatchProps.changeStep, changeStep: dispatchProps.changeStep,
submit: dispatchProps.submit, startLnd: dispatchProps.startLnd,
submitNewWallet: dispatchProps.submitNewWallet,
aliasProps, aliasProps,
autopilotProps autopilotProps,
initWalletProps,
newWalletSeedProps,
newWalletPasswordProps
} }
return { return {

1
app/icons/eye.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>

After

Width:  |  Height:  |  Size: 316 B

153
app/lnd/config/rpc.proto

@ -1,6 +1,6 @@
syntax = "proto3"; syntax = "proto3";
import "google/api/annotations.proto"; // import "google/api/annotations.proto";
package lnrpc; package lnrpc;
/** /**
@ -28,13 +28,39 @@ package lnrpc;
// The WalletUnlocker service is used to set up a wallet password for // The WalletUnlocker service is used to set up a wallet password for
// lnd at first startup, and unlock a previously set up wallet. // lnd at first startup, and unlock a previously set up wallet.
service WalletUnlocker { service WalletUnlocker {
/** lncli: `create` /**
CreateWallet is used at lnd startup to set the encryption password for GenSeed is the first method that should be used to instantiate a new lnd
the wallet database. instance. This method allows a caller to generate a new aezeed cipher seed
given an optional passphrase. If provided, the passphrase will be necessary
to decrypt the cipherseed to expose the internal wallet seed.
Once the cipherseed is obtained and verified by the user, the InitWallet
method should be used to commit the newly generated seed, and create the
wallet.
*/ */
rpc CreateWallet(CreateWalletRequest) returns (CreateWalletResponse) { rpc GenSeed(GenSeedRequest) returns (GenSeedResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/createwallet" get: "/v1/genseed"
};
}
/** lncli: `init`
InitWallet is used when lnd is starting up for the first time to fully
initialize the daemon and its internal wallet. At the very least a wallet
password must be provided. This will be used to encrypt sensitive material
on disk.
In the case of a recovery scenario, the user can also specify their aezeed
mnemonic and passphrase. If set, then the daemon will use this prior state
to initialize its internal wallet.
Alternatively, this can be used along with the GenSeed RPC to obtain a
seed, then present it to the user. Once it has been verified by the user,
the seed can be fed into this RPC in order to commit the new wallet.
*/
rpc InitWallet(InitWalletRequest) returns (InitWalletResponse) {
option (google.api.http) = {
post: "/v1/initwallet"
body: "*" body: "*"
}; };
} }
@ -51,20 +77,74 @@ service WalletUnlocker {
} }
} }
message CreateWalletRequest { message GenSeedRequest {
bytes password = 1; /**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 1;
/**
seed_entropy is an optional 16-bytes generated via CSPRNG. If not
specified, then a fresh set of randomness will be used to create the seed.
*/
bytes seed_entropy = 2;
} }
message CreateWalletResponse {} message GenSeedResponse {
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This field is optional, as if not
provided, then the daemon will generate a new cipher seed for the user.
Otherwise, then the daemon will attempt to recover the wallet state linked
to this cipher seed.
*/
repeated string cipher_seed_mnemonic = 1;
/**
enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
cipher text before run through our mnemonic encoding scheme.
*/
bytes enciphered_seed = 2;
}
message InitWalletRequest {
/**
wallet_password is the passphrase that should be used to encrypt the
wallet. This MUST be at least 8 chars in length. After creation, this
password is required to unlock the daemon.
*/
bytes wallet_password = 1;
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This may have been generated by the
GenSeed method, or be an existing seed.
*/
repeated string cipher_seed_mnemonic = 2;
/**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 3;
}
message InitWalletResponse {
}
message UnlockWalletRequest { message UnlockWalletRequest {
bytes password = 1; /**
wallet_password should be the current valid passphrase for the daemon. This
will be required to decrypt on-disk material that the daemon requires to
function properly.
*/
bytes wallet_password = 1;
} }
message UnlockWalletResponse {} message UnlockWalletResponse {}
service Lightning { service Lightning {
/** lncli: `walletbalance` /** lncli: `walletbalance`
WalletBalance returns total unspent outputs(confirmed and unconfirmed), all confirmed unspent outputs and all unconfirmed unspent outputs under control WalletBalance returns total unspent outputs(confirmed and unconfirmed), all
confirmed unspent outputs and all unconfirmed unspent outputs under control
by the wallet. This method can be modified by having the request specify by the wallet. This method can be modified by having the request specify
only witness outputs should be factored into the final output sum. only witness outputs should be factored into the final output sum.
*/ */
@ -251,7 +331,7 @@ service Lightning {
*/ */
rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) { rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) {
option (google.api.http) = { option (google.api.http) = {
delete: "/v1/channels/{channel_point.funding_txid}/{channel_point.output_index}" delete: "/v1/channels/{channel_point.funding_txid_str}/{channel_point.output_index}"
}; };
} }
@ -294,18 +374,18 @@ service Lightning {
*/ */
rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) { rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{pending_only}" get: "/v1/invoices"
}; };
} }
/** lncli: `lookupinvoice` /** lncli: `lookupinvoice`
LookupInvoice attemps to look up an invoice according to its payment hash. LookupInvoice attempts to look up an invoice according to its payment hash.
The passed payment hash *must* be exactly 32 bytes, if not, an error is The passed payment hash *must* be exactly 32 bytes, if not, an error is
returned. returned.
*/ */
rpc LookupInvoice (PaymentHash) returns (Invoice) { rpc LookupInvoice (PaymentHash) returns (Invoice) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{r_hash_str}" get: "/v1/invoice/{r_hash_str}"
}; };
} }
@ -389,7 +469,7 @@ service Lightning {
route to a target destination capable of carrying a specific amount of route to a target destination capable of carrying a specific amount of
satoshis. The retuned route contains the full details required to craft and satoshis. The retuned route contains the full details required to craft and
send an HTLC, also including the necessary information that should be send an HTLC, also including the necessary information that should be
present within the Sphinx packet encapsualted within the HTLC. present within the Sphinx packet encapsulated within the HTLC.
*/ */
rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) { rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) {
option (google.api.http) = { option (google.api.http) = {
@ -447,7 +527,7 @@ service Lightning {
*/ */
rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) { rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/fees" post: "/v1/chanpolicy"
body: "*" body: "*"
}; };
} }
@ -518,16 +598,16 @@ message SendResponse {
} }
message ChannelPoint { message ChannelPoint {
// TODO(roasbeef): make str vs bytes into a oneof oneof funding_txid {
/// Txid of the funding transaction
bytes funding_txid_bytes = 1 [json_name = "funding_txid_bytes"];
/// Txid of the funding transaction /// Hex-encoded string representing the funding transaction
bytes funding_txid = 1 [ json_name = "funding_txid" ]; string funding_txid_str = 2 [json_name = "funding_txid_str"];
}
/// Hex-encoded string representing the funding transaction
string funding_txid_str = 2 [ json_name = "funding_txid_str" ];
/// The index of the output of the funding transaction /// The index of the output of the funding transaction
uint32 output_index = 3 [ json_name = "output_index" ]; uint32 output_index = 3 [json_name = "output_index"];
} }
message LightningAddress { message LightningAddress {
@ -610,7 +690,7 @@ message VerifyMessageRequest {
/// The message over which the signature is to be verified /// The message over which the signature is to be verified
bytes msg = 1 [ json_name = "msg" ]; bytes msg = 1 [ json_name = "msg" ];
/// The signature to be verifed over the given message /// The signature to be verified over the given message
string signature = 2 [ json_name = "signature" ]; string signature = 2 [ json_name = "signature" ];
} }
message VerifyMessageResponse { message VerifyMessageResponse {
@ -630,8 +710,6 @@ message ConnectPeerRequest {
bool perm = 2; bool perm = 2;
} }
message ConnectPeerResponse { message ConnectPeerResponse {
/// The id of the newly connected peer
int32 peer_id = 1 [json_name = "peer_id"];
} }
message DisconnectPeerRequest { message DisconnectPeerRequest {
@ -738,9 +816,6 @@ message Peer {
/// The identity pubkey of the peer /// The identity pubkey of the peer
string pub_key = 1 [json_name = "pub_key"]; string pub_key = 1 [json_name = "pub_key"];
/// The peer's id from the local point of view
int32 peer_id = 2 [json_name = "peer_id"];
/// Network address of the peer; eg `127.0.0.1:10011` /// Network address of the peer; eg `127.0.0.1:10011`
string address = 3 [json_name = "address"]; string address = 3 [json_name = "address"];
@ -806,6 +881,9 @@ message GetInfoResponse {
/// The URIs of the current node. /// The URIs of the current node.
repeated string uris = 12 [json_name = "uris"]; repeated string uris = 12 [json_name = "uris"];
/// Timestamp of the block best known to the wallet
int64 best_header_timestamp = 13 [ json_name = "best_header_timestamp" ];
} }
message ConfirmationUpdate { message ConfirmationUpdate {
@ -840,8 +918,9 @@ message CloseChannelRequest {
int32 target_conf = 3; int32 target_conf = 3;
/// A manual fee rate set in sat/byte that should be used when crafting the closure transaction. /// A manual fee rate set in sat/byte that should be used when crafting the closure transaction.
int64 sat_per_byte = 5; int64 sat_per_byte = 4;
} }
message CloseStatusUpdate { message CloseStatusUpdate {
oneof update { oneof update {
PendingUpdate close_pending = 1 [json_name = "close_pending"]; PendingUpdate close_pending = 1 [json_name = "close_pending"];
@ -857,13 +936,10 @@ message PendingUpdate {
message OpenChannelRequest { message OpenChannelRequest {
/// The peer_id of the node to open a channel with
int32 target_peer_id = 1 [json_name = "target_peer_id"];
/// The pubkey of the node to open a channel with /// The pubkey of the node to open a channel with
bytes node_pubkey = 2 [json_name = "node_pubkey"]; bytes node_pubkey = 2 [json_name = "node_pubkey"];
/// The hex encorded pubkey of the node to open a channel with /// The hex encoded pubkey of the node to open a channel with
string node_pubkey_string = 3 [json_name = "node_pubkey_string"]; string node_pubkey_string = 3 [json_name = "node_pubkey_string"];
/// The number of satoshis the wallet should commit to the channel /// The number of satoshis the wallet should commit to the channel
@ -1031,6 +1107,9 @@ message QueryRoutesRequest {
/// The amount to send expressed in satoshis /// The amount to send expressed in satoshis
int64 amt = 2; int64 amt = 2;
/// The max number of routes to return.
int32 num_routes = 3;
} }
message QueryRoutesResponse { message QueryRoutesResponse {
repeated Route routes = 1 [ json_name = "routes"]; repeated Route routes = 1 [ json_name = "routes"];
@ -1337,6 +1416,7 @@ message InvoiceSubscription {
message Payment { message Payment {
/// The payment hash /// The payment hash
string payment_hash = 1 [json_name = "payment_hash"]; string payment_hash = 1 [json_name = "payment_hash"];
/// The value of the payment in satoshis /// The value of the payment in satoshis
int64 value = 2 [json_name = "value"]; int64 value = 2 [json_name = "value"];
@ -1348,6 +1428,9 @@ message Payment {
/// The fee paid for this payment in satoshis /// The fee paid for this payment in satoshis
int64 fee = 5 [json_name = "fee"]; int64 fee = 5 [json_name = "fee"];
/// The payment preimage
string payment_preimage = 6 [json_name = "payment_preimage"];
} }
message ListPaymentsRequest { message ListPaymentsRequest {

18
app/lnd/index.js

@ -2,10 +2,12 @@ import grpc from 'grpc'
import fs from 'fs' import fs from 'fs'
import config from './config' import config from './config'
import lightning from './lib/lightning' import lightning from './lib/lightning'
import walletUnlocker from './lib/walletUnlocker'
import subscribe from './subscribe' import subscribe from './subscribe'
import methods from './methods' import methods from './methods'
import walletUnlockerMethods from './walletUnlockerMethods'
export default (callback) => { const initLnd = (callback) => {
const macaroonFile = fs.readFileSync(config.macaroon) const macaroonFile = fs.readFileSync(config.macaroon)
const meta = new grpc.Metadata() const meta = new grpc.Metadata()
meta.add('macaroon', macaroonFile.toString('hex')) meta.add('macaroon', macaroonFile.toString('hex'))
@ -14,5 +16,19 @@ export default (callback) => {
const lndSubscribe = mainWindow => subscribe(mainWindow, lnd, meta) const lndSubscribe = mainWindow => subscribe(mainWindow, lnd, meta)
const lndMethods = (event, msg, data) => methods(lnd, meta, event, msg, data) const lndMethods = (event, msg, data) => methods(lnd, meta, event, msg, data)
callback(lndSubscribe, lndMethods) callback(lndSubscribe, lndMethods)
} }
const initWalletUnlocker = (callback) => {
const walletUnlockerObj = walletUnlocker(config.lightningRpc, config.lightningHost)
const walletUnlockerMethodsCallback = (event, msg, data) => walletUnlockerMethods(walletUnlockerObj, event, msg, data)
callback(walletUnlockerMethodsCallback)
}
export default {
initLnd,
initWalletUnlocker
}

13
app/lnd/init/index.js

@ -0,0 +1,13 @@
/* eslint no-console: 0 */ // --> OFF
import * as walletController from '../methods/walletController'
export default function (walletUnlocker, meta, event, msg, data) {
console.log('msg yo wtf: ', msg)
switch (msg) {
case 'genSeed':
walletController.genSeed(walletUnlocker, meta)
.then(data => { console.log('data: ', data) })
.catch(error => { console.log('error: ', error) })
default:
}
}

24
app/lnd/lib/grpcInit.js

@ -0,0 +1,24 @@
import fs from 'fs'
import path from 'path'
import grpc from 'grpc'
import config from '../config'
const grpcInit = (rpcpath, host) => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
process.env.GRPC_SSL_CIPHER_SUITES = 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384'
const lndCert = fs.readFileSync(config.cert)
const credentials = grpc.credentials.createSsl(lndCert)
const rpc = grpc.load(path.join(__dirname, 'rpc.proto'))
const lightning = new rpc.lnrpc.Lightning(host, credentials)
const walletUnlocker = new rpc.lnrpc.WalletUnlocker(host, credentials)
return {
lightning,
walletUnlocker
}
}
export default grpcInit

2
app/lnd/lib/lightning.js

@ -4,6 +4,8 @@ import grpc from 'grpc'
import config from '../config' import config from '../config'
const lightning = (rpcpath, host) => { const lightning = (rpcpath, host) => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
process.env.GRPC_SSL_CIPHER_SUITES = 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384'
const lndCert = fs.readFileSync(config.cert) const lndCert = fs.readFileSync(config.cert)
const credentials = grpc.credentials.createSsl(lndCert) const credentials = grpc.credentials.createSsl(lndCert)
const rpc = grpc.load(path.join(__dirname, 'rpc.proto')) const rpc = grpc.load(path.join(__dirname, 'rpc.proto'))

148
app/lnd/lib/rpc.proto

@ -28,13 +28,39 @@ package lnrpc;
// The WalletUnlocker service is used to set up a wallet password for // The WalletUnlocker service is used to set up a wallet password for
// lnd at first startup, and unlock a previously set up wallet. // lnd at first startup, and unlock a previously set up wallet.
service WalletUnlocker { service WalletUnlocker {
/** lncli: `create` /**
CreateWallet is used at lnd startup to set the encryption password for GenSeed is the first method that should be used to instantiate a new lnd
the wallet database. instance. This method allows a caller to generate a new aezeed cipher seed
given an optional passphrase. If provided, the passphrase will be necessary
to decrypt the cipherseed to expose the internal wallet seed.
Once the cipherseed is obtained and verified by the user, the InitWallet
method should be used to commit the newly generated seed, and create the
wallet.
*/ */
rpc CreateWallet(CreateWalletRequest) returns (CreateWalletResponse) { rpc GenSeed(GenSeedRequest) returns (GenSeedResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/createwallet" get: "/v1/genseed"
};
}
/** lncli: `init`
InitWallet is used when lnd is starting up for the first time to fully
initialize the daemon and its internal wallet. At the very least a wallet
password must be provided. This will be used to encrypt sensitive material
on disk.
In the case of a recovery scenario, the user can also specify their aezeed
mnemonic and passphrase. If set, then the daemon will use this prior state
to initialize its internal wallet.
Alternatively, this can be used along with the GenSeed RPC to obtain a
seed, then present it to the user. Once it has been verified by the user,
the seed can be fed into this RPC in order to commit the new wallet.
*/
rpc InitWallet(InitWalletRequest) returns (InitWalletResponse) {
option (google.api.http) = {
post: "/v1/initwallet"
body: "*" body: "*"
}; };
} }
@ -51,20 +77,74 @@ service WalletUnlocker {
} }
} }
message CreateWalletRequest { message GenSeedRequest {
bytes password = 1; /**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 1;
/**
seed_entropy is an optional 16-bytes generated via CSPRNG. If not
specified, then a fresh set of randomness will be used to create the seed.
*/
bytes seed_entropy = 2;
}
message GenSeedResponse {
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This field is optional, as if not
provided, then the daemon will generate a new cipher seed for the user.
Otherwise, then the daemon will attempt to recover the wallet state linked
to this cipher seed.
*/
repeated string cipher_seed_mnemonic = 1;
/**
enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
cipher text before run through our mnemonic encoding scheme.
*/
bytes enciphered_seed = 2;
} }
message CreateWalletResponse {}
message InitWalletRequest {
/**
wallet_password is the passphrase that should be used to encrypt the
wallet. This MUST be at least 8 chars in length. After creation, this
password is required to unlock the daemon.
*/
bytes wallet_password = 1;
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This may have been generated by the
GenSeed method, or be an existing seed.
*/
repeated string cipher_seed_mnemonic = 2;
/**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 3;
}
message InitWalletResponse {
}
message UnlockWalletRequest { message UnlockWalletRequest {
bytes password = 1; /**
wallet_password should be the current valid passphrase for the daemon. This
will be required to decrypt on-disk material that the daemon requires to
function properly.
*/
bytes wallet_password = 1;
} }
message UnlockWalletResponse {} message UnlockWalletResponse {}
service Lightning { service Lightning {
/** lncli: `walletbalance` /** lncli: `walletbalance`
WalletBalance returns total unspent outputs(confirmed and unconfirmed), all confirmed unspent outputs and all unconfirmed unspent outputs under control WalletBalance returns total unspent outputs(confirmed and unconfirmed), all
confirmed unspent outputs and all unconfirmed unspent outputs under control
by the wallet. This method can be modified by having the request specify by the wallet. This method can be modified by having the request specify
only witness outputs should be factored into the final output sum. only witness outputs should be factored into the final output sum.
*/ */
@ -251,7 +331,7 @@ service Lightning {
*/ */
rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) { rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) {
option (google.api.http) = { option (google.api.http) = {
delete: "/v1/channels/{channel_point.funding_txid}/{channel_point.output_index}" delete: "/v1/channels/{channel_point.funding_txid_str}/{channel_point.output_index}"
}; };
} }
@ -294,18 +374,18 @@ service Lightning {
*/ */
rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) { rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{pending_only}" get: "/v1/invoices"
}; };
} }
/** lncli: `lookupinvoice` /** lncli: `lookupinvoice`
LookupInvoice attemps to look up an invoice according to its payment hash. LookupInvoice attempts to look up an invoice according to its payment hash.
The passed payment hash *must* be exactly 32 bytes, if not, an error is The passed payment hash *must* be exactly 32 bytes, if not, an error is
returned. returned.
*/ */
rpc LookupInvoice (PaymentHash) returns (Invoice) { rpc LookupInvoice (PaymentHash) returns (Invoice) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{r_hash_str}" get: "/v1/invoice/{r_hash_str}"
}; };
} }
@ -389,7 +469,7 @@ service Lightning {
route to a target destination capable of carrying a specific amount of route to a target destination capable of carrying a specific amount of
satoshis. The retuned route contains the full details required to craft and satoshis. The retuned route contains the full details required to craft and
send an HTLC, also including the necessary information that should be send an HTLC, also including the necessary information that should be
present within the Sphinx packet encapsualted within the HTLC. present within the Sphinx packet encapsulated within the HTLC.
*/ */
rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) { rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) {
option (google.api.http) = { option (google.api.http) = {
@ -447,7 +527,7 @@ service Lightning {
*/ */
rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) { rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/fees" post: "/v1/chanpolicy"
body: "*" body: "*"
}; };
} }
@ -518,16 +598,16 @@ message SendResponse {
} }
message ChannelPoint { message ChannelPoint {
// TODO(roasbeef): make str vs bytes into a oneof oneof funding_txid {
/// Txid of the funding transaction
/// Txid of the funding transaction bytes funding_txid_bytes = 1 [json_name = "funding_txid_bytes"];
bytes funding_txid = 1 [ json_name = "funding_txid" ];
/// Hex-encoded string representing the funding transaction /// Hex-encoded string representing the funding transaction
string funding_txid_str = 2 [ json_name = "funding_txid_str" ]; string funding_txid_str = 2 [json_name = "funding_txid_str"];
}
/// The index of the output of the funding transaction /// The index of the output of the funding transaction
uint32 output_index = 3 [ json_name = "output_index" ]; uint32 output_index = 3 [json_name = "output_index"];
} }
message LightningAddress { message LightningAddress {
@ -610,7 +690,7 @@ message VerifyMessageRequest {
/// The message over which the signature is to be verified /// The message over which the signature is to be verified
bytes msg = 1 [ json_name = "msg" ]; bytes msg = 1 [ json_name = "msg" ];
/// The signature to be verifed over the given message /// The signature to be verified over the given message
string signature = 2 [ json_name = "signature" ]; string signature = 2 [ json_name = "signature" ];
} }
message VerifyMessageResponse { message VerifyMessageResponse {
@ -630,8 +710,6 @@ message ConnectPeerRequest {
bool perm = 2; bool perm = 2;
} }
message ConnectPeerResponse { message ConnectPeerResponse {
/// The id of the newly connected peer
int32 peer_id = 1 [json_name = "peer_id"];
} }
message DisconnectPeerRequest { message DisconnectPeerRequest {
@ -738,9 +816,6 @@ message Peer {
/// The identity pubkey of the peer /// The identity pubkey of the peer
string pub_key = 1 [json_name = "pub_key"]; string pub_key = 1 [json_name = "pub_key"];
/// The peer's id from the local point of view
int32 peer_id = 2 [json_name = "peer_id"];
/// Network address of the peer; eg `127.0.0.1:10011` /// Network address of the peer; eg `127.0.0.1:10011`
string address = 3 [json_name = "address"]; string address = 3 [json_name = "address"];
@ -806,6 +881,9 @@ message GetInfoResponse {
/// The URIs of the current node. /// The URIs of the current node.
repeated string uris = 12 [json_name = "uris"]; repeated string uris = 12 [json_name = "uris"];
/// Timestamp of the block best known to the wallet
int64 best_header_timestamp = 13 [ json_name = "best_header_timestamp" ];
} }
message ConfirmationUpdate { message ConfirmationUpdate {
@ -840,8 +918,9 @@ message CloseChannelRequest {
int32 target_conf = 3; int32 target_conf = 3;
/// A manual fee rate set in sat/byte that should be used when crafting the closure transaction. /// A manual fee rate set in sat/byte that should be used when crafting the closure transaction.
int64 sat_per_byte = 5; int64 sat_per_byte = 4;
} }
message CloseStatusUpdate { message CloseStatusUpdate {
oneof update { oneof update {
PendingUpdate close_pending = 1 [json_name = "close_pending"]; PendingUpdate close_pending = 1 [json_name = "close_pending"];
@ -857,13 +936,10 @@ message PendingUpdate {
message OpenChannelRequest { message OpenChannelRequest {
/// The peer_id of the node to open a channel with
int32 target_peer_id = 1 [json_name = "target_peer_id"];
/// The pubkey of the node to open a channel with /// The pubkey of the node to open a channel with
bytes node_pubkey = 2 [json_name = "node_pubkey"]; bytes node_pubkey = 2 [json_name = "node_pubkey"];
/// The hex encorded pubkey of the node to open a channel with /// The hex encoded pubkey of the node to open a channel with
string node_pubkey_string = 3 [json_name = "node_pubkey_string"]; string node_pubkey_string = 3 [json_name = "node_pubkey_string"];
/// The number of satoshis the wallet should commit to the channel /// The number of satoshis the wallet should commit to the channel
@ -1031,6 +1107,9 @@ message QueryRoutesRequest {
/// The amount to send expressed in satoshis /// The amount to send expressed in satoshis
int64 amt = 2; int64 amt = 2;
/// The max number of routes to return.
int32 num_routes = 3;
} }
message QueryRoutesResponse { message QueryRoutesResponse {
repeated Route routes = 1 [ json_name = "routes"]; repeated Route routes = 1 [ json_name = "routes"];
@ -1337,6 +1416,7 @@ message InvoiceSubscription {
message Payment { message Payment {
/// The payment hash /// The payment hash
string payment_hash = 1 [json_name = "payment_hash"]; string payment_hash = 1 [json_name = "payment_hash"];
/// The value of the payment in satoshis /// The value of the payment in satoshis
int64 value = 2 [json_name = "value"]; int64 value = 2 [json_name = "value"];

16
app/lnd/lib/walletUnlocker.js

@ -0,0 +1,16 @@
import fs from 'fs'
import path from 'path'
import grpc from 'grpc'
import config from '../config'
const walletUnlocker = (rpcpath, host) => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
process.env.GRPC_SSL_CIPHER_SUITES = 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384'
const lndCert = fs.readFileSync(config.cert)
const credentials = grpc.credentials.createSsl(lndCert)
const rpc = grpc.load(path.join(__dirname, 'rpc.proto'))
return new rpc.lnrpc.WalletUnlocker(host, credentials)
}
export default walletUnlocker

46
app/lnd/methods/walletController.js

@ -1,3 +1,6 @@
import bitcore from 'bitcore-lib'
const BufferUtil = bitcore.util.buffer
/** /**
* Returns the sum of all confirmed unspent outputs under control by the wallet * Returns the sum of all confirmed unspent outputs under control by the wallet
* @param {[type]} lnd [description] * @param {[type]} lnd [description]
@ -92,3 +95,46 @@ export function setAlias(lnd, meta, { new_alias }) {
}) })
}) })
} }
/**
* Generates a seed for the wallet
*/
export function genSeed(walletUnlocker) {
console.log('walletUnlocker: ', walletUnlocker)
return new Promise((resolve, reject) => {
walletUnlocker.genSeed({}, (err, data) => {
if (err) { reject(err) }
resolve(data)
})
})
}
/**
* Unlocks a wallet with a password
* @param {[type]} password [description]
*/
export function unlockWallet(walletUnlocker, { wallet_password }) {
return new Promise((resolve, reject) => {
walletUnlocker.unlockWallet({ wallet_password }, (err, data) => {
if (err) { reject(err) }
resolve(data)
})
})
}
/**
* Unlocks a wallet with a password
* @param {[type]} password [description]
* @param {[type]} cipher_seed_mnemonic [description]
*/
export function initWallet(walletUnlocker, { wallet_password, cipher_seed_mnemonic }) {
return new Promise((resolve, reject) => {
walletUnlocker.initWallet({ wallet_password, cipher_seed_mnemonic }, (err, data) => {
if (err) { reject(err) }
resolve(data)
})
})
}

30
app/lnd/walletUnlockerMethods/index.js

@ -0,0 +1,30 @@
/* eslint no-console: 0 */ // --> OFF
import * as walletController from '../methods/walletController'
export default function (walletUnlocker, event, msg, data) {
switch (msg) {
case 'genSeed':
walletController.genSeed(walletUnlocker)
.then(data => {
console.log('data yo: ', data)
event.sender.send('receiveSeed', data)
})
.catch(error => {
console.log('genSeed error: ', error)
event.sender.send('receiveSeedError', error)
})
break
case 'unlockWallet':
walletController.unlockWallet(walletUnlocker, data)
.then(data => event.sender.send('walletUnlocked'))
.catch(error => event.sender.send('unlockWalletError'))
break
case 'initWallet':
walletController.initWallet(walletUnlocker, data)
.then(data => event.sender.send('successfullyCreatedWallet'))
.catch(error => console.log('initWallet error: ', error))
break
default:
}
}

36
app/main.dev.js

@ -17,7 +17,7 @@ import { spawn } from 'child_process'
import { lookup } from 'ps-node' import { lookup } from 'ps-node'
import os from 'os' import os from 'os'
import MenuBuilder from './menu' import MenuBuilder from './menu'
import lnd from './lnd' import { initLnd, initWalletUnlocker } from './lnd'
const plat = os.platform() const plat = os.platform()
const homedir = os.homedir() const homedir = os.homedir()
@ -111,7 +111,7 @@ const sendGrpcConnected = () => {
// Create and subscribe the grpc object // Create and subscribe the grpc object
const startGrpc = () => { const startGrpc = () => {
lnd((lndSubscribe, lndMethods) => { initLnd((lndSubscribe, lndMethods) => {
// Subscribe to bi-directional streams // Subscribe to bi-directional streams
lndSubscribe(mainWindow) lndSubscribe(mainWindow)
@ -124,6 +124,18 @@ const startGrpc = () => {
}) })
} }
// Create and subscribe the grpc object
const startWalletUnlocker = () => {
initWalletUnlocker((walletUnlockerMethods) => {
// Listen for all gRPC restful methods
ipcMain.on('walletUnlocker', (event, { msg, data }) => {
walletUnlockerMethods(event, msg, data)
})
})
mainWindow.webContents.send('walletUnlockerStarted')
}
// Send the front end event letting them know LND is synced to the blockchain // Send the front end event letting them know LND is synced to the blockchain
const sendLndSynced = () => { const sendLndSynced = () => {
const sendLndSyncedInterval = setInterval(() => { const sendLndSyncedInterval = setInterval(() => {
@ -157,7 +169,6 @@ const startLnd = (alias, autopilot) => {
'--neutrino.addpeer=159.65.48.139:18333', '--neutrino.addpeer=159.65.48.139:18333',
'--neutrino.connect=127.0.0.1:18333', '--neutrino.connect=127.0.0.1:18333',
'--debuglevel=debug', '--debuglevel=debug',
'--noencryptwallet',
`${autopilot ? '--autopilot.active' : ''}`, `${autopilot ? '--autopilot.active' : ''}`,
`${alias ? `--alias=${alias}` : ''}` `${alias ? `--alias=${alias}` : ''}`
] ]
@ -179,12 +190,23 @@ const startLnd = (alias, autopilot) => {
if (fs.existsSync(certPath)) { if (fs.existsSync(certPath)) {
clearInterval(certInterval) clearInterval(certInterval)
console.log('CERT EXISTS, STARTING GRPC') console.log('CERT EXISTS, STARTING WALLET UNLOCKER')
startGrpc() startWalletUnlocker()
if (mainWindow) {
mainWindow.webContents.send('walletUnlockerStarted')
}
} }
}, 1000) }, 1000)
} }
if (line.includes('The wallet has been unlocked')) {
console.log('WALLET OPENED, STARTING LIGHTNING GRPC CONNECTION')
sendLndSyncing()
startGrpc()
}
// Pass current clock height progress to front end for loading state UX // Pass current clock height progress to front end for loading state UX
if (mainWindow && (line.includes('Caught up to height') || line.includes('Catching up block hashes to height'))) { if (mainWindow && (line.includes('Caught up to height') || line.includes('Catching up block hashes to height'))) {
// const blockHeight = line.slice(line.indexOf('Caught up to height') + 'Caught up to height'.length).trim() // const blockHeight = line.slice(line.indexOf('Caught up to height') + 'Caught up to height'.length).trim()
@ -282,10 +304,8 @@ app.on('ready', async () => {
} }
// Start LND // Start LND
// startLnd()
// once the onboarding has finished we wanna let the application we have started syncing and start LND // once the onboarding has finished we wanna let the application we have started syncing and start LND
ipcMain.on('onboardingFinished', (event, { alias, autopilot }) => { ipcMain.on('startLnd', (event, { alias, autopilot }) => {
sendLndSyncing()
startLnd(alias, autopilot) startLnd(alias, autopilot)
}) })
} else { } else {

18
app/reducers/ipc.js

@ -35,7 +35,15 @@ import {
import { receiveDescribeNetwork, receiveQueryRoutes, receiveInvoiceAndQueryRoutes } from './network' import { receiveDescribeNetwork, receiveQueryRoutes, receiveInvoiceAndQueryRoutes } from './network'
import { startOnboarding } from './onboarding' import {
startOnboarding,
walletUnlockerStarted,
receiveSeed,
receiveSeedError,
successfullyCreatedWallet,
walletUnlocked,
unlockWalletError
} from './onboarding'
// Import all receiving IPC event handlers and pass them into createIpc // Import all receiving IPC event handlers and pass them into createIpc
const ipc = createIpc({ const ipc = createIpc({
@ -95,7 +103,13 @@ const ipc = createIpc({
receiveQueryRoutes, receiveQueryRoutes,
receiveInvoiceAndQueryRoutes, receiveInvoiceAndQueryRoutes,
startOnboarding startOnboarding,
walletUnlockerStarted,
receiveSeed,
receiveSeedError,
successfullyCreatedWallet,
walletUnlocked,
unlockWalletError
}) })
export default ipc export default ipc

124
app/reducers/onboarding.js

@ -1,17 +1,32 @@
import { createSelector } from 'reselect'
import { ipcRenderer } from 'electron' import { ipcRenderer } from 'electron'
// ------------------------------------ // ------------------------------------
// Constants // Constants
// ------------------------------------ // ------------------------------------
export const UPDATE_ALIAS = 'UPDATE_ALIAS' export const UPDATE_ALIAS = 'UPDATE_ALIAS'
export const UPDATE_PASSWORD = 'UPDATE_PASSWORD'
export const UPDATE_CREATE_WALLET_PASSWORD = 'UPDATE_CREATE_WALLET_PASSWORD'
export const CHANGE_STEP = 'CHANGE_STEP' export const CHANGE_STEP = 'CHANGE_STEP'
export const SET_AUTOPILOT = 'SET_AUTOPILOT' export const SET_AUTOPILOT = 'SET_AUTOPILOT'
export const FETCH_SEED = 'FETCH_SEED'
export const SET_SEED = 'SET_SEED'
export const SET_HAS_SEED = 'SET_HAS_SEED'
export const ONBOARDING_STARTED = 'ONBOARDING_STARTED' export const ONBOARDING_STARTED = 'ONBOARDING_STARTED'
export const ONBOARDING_FINISHED = 'ONBOARDING_FINISHED' export const ONBOARDING_FINISHED = 'ONBOARDING_FINISHED'
export const STARTING_LND = 'STARTING_LND'
export const LND_STARTED = 'LND_STARTED'
export const CREATING_NEW_WALLET = 'CREATING_NEW_WALLET'
export const UNLOCKING_WALLET = 'UNLOCKING_WALLET'
export const WALLET_UNLOCKED = 'WALLET_UNLOCKED'
export const SET_UNLOCK_WALLET_ERROR = 'SET_UNLOCK_WALLET_ERROR'
// ------------------------------------ // ------------------------------------
// Actions // Actions
// ------------------------------------ // ------------------------------------
@ -22,6 +37,20 @@ export function updateAlias(alias) {
} }
} }
export function updatePassword(password) {
return {
type: UPDATE_PASSWORD,
password
}
}
export function updateCreateWalletPassword(createWalletPassword) {
return {
type: UPDATE_CREATE_WALLET_PASSWORD,
createWalletPassword
}
}
export function setAutopilot(autopilot) { export function setAutopilot(autopilot) {
return { return {
type: SET_AUTOPILOT, type: SET_AUTOPILOT,
@ -36,31 +65,98 @@ export function changeStep(step) {
} }
} }
export function submit(alias, autopilot) { export function startLnd(alias, autopilot) {
// alert the app we're done onboarding and it's cool to start LND // once the user submits the data needed to start LND we will alert the app that it should start LND
// send the alias they set along with whether they want autopilot on or not ipcRenderer.send('startLnd', { alias, autopilot })
ipcRenderer.send('onboardingFinished', { alias, autopilot })
return { return {
type: ONBOARDING_FINISHED type: STARTING_LND
} }
} }
export function submitNewWallet(wallet_password, cipher_seed_mnemonic) {
// once the user submits the data needed to start LND we will alert the app that it should start LND
ipcRenderer.send('walletUnlocker', { msg: 'initWallet', data: { wallet_password, cipher_seed_mnemonic } })
dispatch({ type: CREATING_NEW_WALLET })
}
export const startOnboarding = () => (dispatch) => { export const startOnboarding = () => (dispatch) => {
dispatch({ type: ONBOARDING_STARTED }) dispatch({ type: ONBOARDING_STARTED })
} }
// Listener from after the LND walletUnlocker has started
export const walletUnlockerStarted = () => (dispatch) => {
dispatch({ type: LND_STARTED })
dispatch({ type: CHANGE_STEP, step: 3 })
ipcRenderer.send('walletUnlocker', { msg: 'genSeed' })
}
export const createWallet = () => (dispatch) => {
ipcRenderer.send('walletUnlocker', { msg: 'genSeed' })
dispatch({ type: CHANGE_STEP, step: 4 })
}
export const successfullyCreatedWallet = (event) => (dispatch) => dispatch({ type: ONBOARDING_FINISHED })
// Listener for when LND creates and sends us a generated seed
export const receiveSeed = (event, { cipher_seed_mnemonic }) => (dispatch) => dispatch({ type: SET_SEED, seed: cipher_seed_mnemonic })
// Listener for when LND throws an error on seed creation
export const receiveSeedError = (event, error) => (dispatch) => dispatch({ type: SET_HAS_SEED, hasSeed: true })
// Unlock an existing wallet with a wallet password
export const unlockWallet = (wallet_password) => (dispatch) => {
ipcRenderer.send('walletUnlocker', { msg: 'unlockWallet', data: { wallet_password } })
dispatch({ type: UNLOCKING_WALLET })
}
export const walletUnlocked = () => (dispatch) => {
dispatch({ type: WALLET_UNLOCKED })
dispatch({ type: ONBOARDING_FINISHED })
}
export const unlockWalletError = () => (dispatch) => {
dispatch({ type: SET_UNLOCK_WALLET_ERROR })
}
// ------------------------------------ // ------------------------------------
// Action Handlers // Action Handlers
// ------------------------------------ // ------------------------------------
const ACTION_HANDLERS = { const ACTION_HANDLERS = {
[UPDATE_ALIAS]: (state, { alias }) => ({ ...state, alias }), [UPDATE_ALIAS]: (state, { alias }) => ({ ...state, alias }),
[UPDATE_PASSWORD]: (state, { password }) => ({ ...state, password }),
[UPDATE_CREATE_WALLET_PASSWORD]: (state, { createWalletPassword }) => ({ ...state, createWalletPassword }),
[SET_AUTOPILOT]: (state, { autopilot }) => ({ ...state, autopilot }), [SET_AUTOPILOT]: (state, { autopilot }) => ({ ...state, autopilot }),
[SET_HAS_SEED]: (state, { hasSeed }) => ({ ...state, hasSeed }),
[SET_SEED]: (state, { seed }) => ({ ...state, seed, fetchingSeed: false }),
[CHANGE_STEP]: (state, { step }) => ({ ...state, step }), [CHANGE_STEP]: (state, { step }) => ({ ...state, step }),
[ONBOARDING_STARTED]: state => ({ ...state, onboarded: false }), [ONBOARDING_STARTED]: state => ({ ...state, onboarded: false }),
[ONBOARDING_FINISHED]: state => ({ ...state, onboarded: true }) [ONBOARDING_FINISHED]: state => ({ ...state, onboarded: true }),
[STARTING_LND]: state => ({ ...state, startingLnd: true }),
[LND_STARTED]: state => ({ ...state, startingLnd: false }),
[CREATING_NEW_WALLET]: state => ({ ...state, creatingNewWallet: true }),
[UNLOCKING_WALLET]: state => ({ ...state, unlockingWallet: true }),
[WALLET_UNLOCKED]: state => ({ ...state, unlockingWallet: false, unlockWalletError: { isError: false, message: '' } }),
[SET_UNLOCK_WALLET_ERROR]: state => ({ ...state, unlockingWallet: false, unlockWalletError: { isError: true, message: 'Incorrect password' } })
} }
const onboardingSelectors = {}
const passwordSelector = state => state.onboarding.password
onboardingSelectors.passwordIsValid = createSelector(
passwordSelector,
password => password.length >= 8
)
export { onboardingSelectors }
// ------------------------------------ // ------------------------------------
// Reducer // Reducer
// ------------------------------------ // ------------------------------------
@ -68,6 +164,22 @@ const initialState = {
onboarded: true, onboarded: true,
step: 1, step: 1,
alias: '', alias: '',
password: '',
startingLnd: false,
fetchingSeed: false,
hasSeed: false,
seed: [],
createWalletPassword: '',
creatingNewWallet: false,
unlockingWallet: false,
unlockWalletError: {
isError: false,
message: ''
},
autopilot: null autopilot: null
} }

148
app/rpc.proto

@ -28,13 +28,39 @@ package lnrpc;
// The WalletUnlocker service is used to set up a wallet password for // The WalletUnlocker service is used to set up a wallet password for
// lnd at first startup, and unlock a previously set up wallet. // lnd at first startup, and unlock a previously set up wallet.
service WalletUnlocker { service WalletUnlocker {
/** lncli: `create` /**
CreateWallet is used at lnd startup to set the encryption password for GenSeed is the first method that should be used to instantiate a new lnd
the wallet database. instance. This method allows a caller to generate a new aezeed cipher seed
given an optional passphrase. If provided, the passphrase will be necessary
to decrypt the cipherseed to expose the internal wallet seed.
Once the cipherseed is obtained and verified by the user, the InitWallet
method should be used to commit the newly generated seed, and create the
wallet.
*/ */
rpc CreateWallet(CreateWalletRequest) returns (CreateWalletResponse) { rpc GenSeed(GenSeedRequest) returns (GenSeedResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/createwallet" get: "/v1/genseed"
};
}
/** lncli: `init`
InitWallet is used when lnd is starting up for the first time to fully
initialize the daemon and its internal wallet. At the very least a wallet
password must be provided. This will be used to encrypt sensitive material
on disk.
In the case of a recovery scenario, the user can also specify their aezeed
mnemonic and passphrase. If set, then the daemon will use this prior state
to initialize its internal wallet.
Alternatively, this can be used along with the GenSeed RPC to obtain a
seed, then present it to the user. Once it has been verified by the user,
the seed can be fed into this RPC in order to commit the new wallet.
*/
rpc InitWallet(InitWalletRequest) returns (InitWalletResponse) {
option (google.api.http) = {
post: "/v1/initwallet"
body: "*" body: "*"
}; };
} }
@ -51,20 +77,74 @@ service WalletUnlocker {
} }
} }
message CreateWalletRequest { message GenSeedRequest {
bytes password = 1; /**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 1;
/**
seed_entropy is an optional 16-bytes generated via CSPRNG. If not
specified, then a fresh set of randomness will be used to create the seed.
*/
bytes seed_entropy = 2;
}
message GenSeedResponse {
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This field is optional, as if not
provided, then the daemon will generate a new cipher seed for the user.
Otherwise, then the daemon will attempt to recover the wallet state linked
to this cipher seed.
*/
repeated string cipher_seed_mnemonic = 1;
/**
enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
cipher text before run through our mnemonic encoding scheme.
*/
bytes enciphered_seed = 2;
} }
message CreateWalletResponse {}
message InitWalletRequest {
/**
wallet_password is the passphrase that should be used to encrypt the
wallet. This MUST be at least 8 chars in length. After creation, this
password is required to unlock the daemon.
*/
bytes wallet_password = 1;
/**
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This may have been generated by the
GenSeed method, or be an existing seed.
*/
repeated string cipher_seed_mnemonic = 2;
/**
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed.
*/
bytes aezeed_passphrase = 3;
}
message InitWalletResponse {
}
message UnlockWalletRequest { message UnlockWalletRequest {
bytes password = 1; /**
wallet_password should be the current valid passphrase for the daemon. This
will be required to decrypt on-disk material that the daemon requires to
function properly.
*/
bytes wallet_password = 1;
} }
message UnlockWalletResponse {} message UnlockWalletResponse {}
service Lightning { service Lightning {
/** lncli: `walletbalance` /** lncli: `walletbalance`
WalletBalance returns total unspent outputs(confirmed and unconfirmed), all confirmed unspent outputs and all unconfirmed unspent outputs under control WalletBalance returns total unspent outputs(confirmed and unconfirmed), all
confirmed unspent outputs and all unconfirmed unspent outputs under control
by the wallet. This method can be modified by having the request specify by the wallet. This method can be modified by having the request specify
only witness outputs should be factored into the final output sum. only witness outputs should be factored into the final output sum.
*/ */
@ -251,7 +331,7 @@ service Lightning {
*/ */
rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) { rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) {
option (google.api.http) = { option (google.api.http) = {
delete: "/v1/channels/{channel_point.funding_txid}/{channel_point.output_index}" delete: "/v1/channels/{channel_point.funding_txid_str}/{channel_point.output_index}"
}; };
} }
@ -294,18 +374,18 @@ service Lightning {
*/ */
rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) { rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{pending_only}" get: "/v1/invoices"
}; };
} }
/** lncli: `lookupinvoice` /** lncli: `lookupinvoice`
LookupInvoice attemps to look up an invoice according to its payment hash. LookupInvoice attempts to look up an invoice according to its payment hash.
The passed payment hash *must* be exactly 32 bytes, if not, an error is The passed payment hash *must* be exactly 32 bytes, if not, an error is
returned. returned.
*/ */
rpc LookupInvoice (PaymentHash) returns (Invoice) { rpc LookupInvoice (PaymentHash) returns (Invoice) {
option (google.api.http) = { option (google.api.http) = {
get: "/v1/invoices/{r_hash_str}" get: "/v1/invoice/{r_hash_str}"
}; };
} }
@ -389,7 +469,7 @@ service Lightning {
route to a target destination capable of carrying a specific amount of route to a target destination capable of carrying a specific amount of
satoshis. The retuned route contains the full details required to craft and satoshis. The retuned route contains the full details required to craft and
send an HTLC, also including the necessary information that should be send an HTLC, also including the necessary information that should be
present within the Sphinx packet encapsualted within the HTLC. present within the Sphinx packet encapsulated within the HTLC.
*/ */
rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) { rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) {
option (google.api.http) = { option (google.api.http) = {
@ -447,7 +527,7 @@ service Lightning {
*/ */
rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) { rpc UpdateChannelPolicy(PolicyUpdateRequest) returns (PolicyUpdateResponse) {
option (google.api.http) = { option (google.api.http) = {
post: "/v1/fees" post: "/v1/chanpolicy"
body: "*" body: "*"
}; };
} }
@ -518,16 +598,16 @@ message SendResponse {
} }
message ChannelPoint { message ChannelPoint {
// TODO(roasbeef): make str vs bytes into a oneof oneof funding_txid {
/// Txid of the funding transaction
/// Txid of the funding transaction bytes funding_txid_bytes = 1 [json_name = "funding_txid_bytes"];
bytes funding_txid = 1 [ json_name = "funding_txid" ];
/// Hex-encoded string representing the funding transaction /// Hex-encoded string representing the funding transaction
string funding_txid_str = 2 [ json_name = "funding_txid_str" ]; string funding_txid_str = 2 [json_name = "funding_txid_str"];
}
/// The index of the output of the funding transaction /// The index of the output of the funding transaction
uint32 output_index = 3 [ json_name = "output_index" ]; uint32 output_index = 3 [json_name = "output_index"];
} }
message LightningAddress { message LightningAddress {
@ -610,7 +690,7 @@ message VerifyMessageRequest {
/// The message over which the signature is to be verified /// The message over which the signature is to be verified
bytes msg = 1 [ json_name = "msg" ]; bytes msg = 1 [ json_name = "msg" ];
/// The signature to be verifed over the given message /// The signature to be verified over the given message
string signature = 2 [ json_name = "signature" ]; string signature = 2 [ json_name = "signature" ];
} }
message VerifyMessageResponse { message VerifyMessageResponse {
@ -630,8 +710,6 @@ message ConnectPeerRequest {
bool perm = 2; bool perm = 2;
} }
message ConnectPeerResponse { message ConnectPeerResponse {
/// The id of the newly connected peer
int32 peer_id = 1 [json_name = "peer_id"];
} }
message DisconnectPeerRequest { message DisconnectPeerRequest {
@ -738,9 +816,6 @@ message Peer {
/// The identity pubkey of the peer /// The identity pubkey of the peer
string pub_key = 1 [json_name = "pub_key"]; string pub_key = 1 [json_name = "pub_key"];
/// The peer's id from the local point of view
int32 peer_id = 2 [json_name = "peer_id"];
/// Network address of the peer; eg `127.0.0.1:10011` /// Network address of the peer; eg `127.0.0.1:10011`
string address = 3 [json_name = "address"]; string address = 3 [json_name = "address"];
@ -806,6 +881,9 @@ message GetInfoResponse {
/// The URIs of the current node. /// The URIs of the current node.
repeated string uris = 12 [json_name = "uris"]; repeated string uris = 12 [json_name = "uris"];
/// Timestamp of the block best known to the wallet
int64 best_header_timestamp = 13 [ json_name = "best_header_timestamp" ];
} }
message ConfirmationUpdate { message ConfirmationUpdate {
@ -840,8 +918,9 @@ message CloseChannelRequest {
int32 target_conf = 3; int32 target_conf = 3;
/// A manual fee rate set in sat/byte that should be used when crafting the closure transaction. /// A manual fee rate set in sat/byte that should be used when crafting the closure transaction.
int64 sat_per_byte = 5; int64 sat_per_byte = 4;
} }
message CloseStatusUpdate { message CloseStatusUpdate {
oneof update { oneof update {
PendingUpdate close_pending = 1 [json_name = "close_pending"]; PendingUpdate close_pending = 1 [json_name = "close_pending"];
@ -857,13 +936,10 @@ message PendingUpdate {
message OpenChannelRequest { message OpenChannelRequest {
/// The peer_id of the node to open a channel with
int32 target_peer_id = 1 [json_name = "target_peer_id"];
/// The pubkey of the node to open a channel with /// The pubkey of the node to open a channel with
bytes node_pubkey = 2 [json_name = "node_pubkey"]; bytes node_pubkey = 2 [json_name = "node_pubkey"];
/// The hex encorded pubkey of the node to open a channel with /// The hex encoded pubkey of the node to open a channel with
string node_pubkey_string = 3 [json_name = "node_pubkey_string"]; string node_pubkey_string = 3 [json_name = "node_pubkey_string"];
/// The number of satoshis the wallet should commit to the channel /// The number of satoshis the wallet should commit to the channel
@ -1031,6 +1107,9 @@ message QueryRoutesRequest {
/// The amount to send expressed in satoshis /// The amount to send expressed in satoshis
int64 amt = 2; int64 amt = 2;
/// The max number of routes to return.
int32 num_routes = 3;
} }
message QueryRoutesResponse { message QueryRoutesResponse {
repeated Route routes = 1 [ json_name = "routes"]; repeated Route routes = 1 [ json_name = "routes"];
@ -1337,6 +1416,7 @@ message InvoiceSubscription {
message Payment { message Payment {
/// The payment hash /// The payment hash
string payment_hash = 1 [json_name = "payment_hash"]; string payment_hash = 1 [json_name = "payment_hash"];
/// The value of the payment in satoshis /// The value of the payment in satoshis
int64 value = 2 [json_name = "value"]; int64 value = 2 [json_name = "value"];

Loading…
Cancel
Save