diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..ef8449ad1 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +node_modules +dist +release +main.js +main.js.map diff --git a/.eslintrc.js b/.eslintrc.js index a71db9e00..0455f8770 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,45 +1,6 @@ -var IGNORE = 0 -var WARN = 1 -var ERROR = 2 - -var ALWAYS = 'always' -var NEVER = 'never' -var OFF = 'off' - module.exports = { - extends: 'airbnb', - parser: 'babel-eslint', - env: { - browser: true, - node: true - }, + extends: '@case/eslint-config', rules: { - 'react/jsx-curly-spacing': [ERROR, ALWAYS, { spacing: { objectLiterals: NEVER }}], - "react/jsx-filename-extension": [IGNORE], - 'react/prop-types': [IGNORE], - 'template-curly-spacing': [ERROR, ALWAYS], - 'strict': [IGNORE], - 'no-unused-expressions': IGNORE, - 'no-unused-vars': [ERROR, { 'vars': 'local' }], - 'arrow-body-style': [IGNORE, ALWAYS], - 'camelcase': [ERROR], - 'constructor-super': ERROR, - 'quote-props': [ERROR, 'consistent'], - 'no-underscore-dangle': [WARN], - 'semi': [ERROR, NEVER], - 'import/no-unresolved': [ERROR], - 'new-cap': [IGNORE], - 'jsx-a11y/no-static-element-interactions': [IGNORE], - 'import/no-named-as-default': [IGNORE], - 'import/no-extraneous-dependencies': [IGNORE], - 'react/require-extension': OFF - }, - 'settings': { - 'import/core-modules': [ - 'electron', - 'redux-grpc-middlware', - 'lightning-notifications', - 'lightning-store', - ] + 'import/imports-first': 0, } } diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 000000000..e1c744754 --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1,9 @@ +### Description + +### Steps to reproduce the behavior + +### Expected behavior + +### Actual behavior + +### Screenshot and/or logs if applicable diff --git a/.gitignore b/.gitignore index 36f31abcb..90cb0bb7f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ node_modules # App packaged +*package-lock.json dist release main.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..9cecc1d46 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 000000000..f28be896f --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +## Lightning Desktop App + +This repo houses a cross-platform Lightning desktop app powered by +[`lnd`](https://github.com/lightningnetwork/lnd/). The application is under +active development and currently only operates on the Bitcoin testnet chain. + + + +### Developing Locally + + +First start by pulling down the git repo: +``` +git clone https://github.com/lightninglabs/lightning-app.git +``` + +Then go inside the project folder and run the following commands (grab a coffee, this might take a while): +``` +cd lightning-app +npm run setup +``` + +### Development Mode + +You can run the app in development mode in lieu of using the packaged app: +``` +npm start +``` + +You can pass extra arguments to be passed to lnd daemon (note the extra --): +``` +npm run start -- --peerport=10019 --rpcport=10017 --datadir=test_lnd --logdir=test_lnd +``` + +In development mode, the app will look for an lnd.conf in the default location for your platform. See [`lnd.conf` details](https://github.com/lightningnetwork/lnd/blob/master/docs/INSTALL.md#creating-an-lndconf-optional). A typical lnd.conf for running on simnet will look like the following: + +``` +debuglevel=debug +bitcoin.active=1 +bitcoin.simnet=1 +bitcoin.rpcuser=lnd +bitcoin.rpcpass=lnd +``` + +Running in development mode can allow you to run in full node mode instead of the default neutrino mode, and will also allow you to run in simnet node for testing. + +Note that in order to run in simnet node, you will have also had to separately install and configure the [roasbeef fork of `btcd`](https://github.com/roasbeef/btcd). Additional instructions for running simnet can be found [here](https://gist.github.com/davecgh/2992ed85d41307e794f6). + +Also note that if you have installed and built [`lnd`](https://github.com/lightningnetwork/lnd) separately, if an instance is running when the app starts, the app will connect to the already running instance rather than attempt to start a new one. + +If you want your lnd.conf to replicate the configuration used by the packaged app, you can use the following: + +``` +debuglevel=info +bitcoin.active=1 +bitcoin.testnet=1 +neutrino.active=1 +neutrino.connect=btcd0.lightning.computer:18333 +autopilot.active=1 +``` + +### Building the Packaged App + +To build the packaged version of the app for your current platform, run: +``` +npm run package-electron +``` + +The packaged app will then be available in the lightning-app/release directory. The packaged version of the app will run on Bitcoin testnet. To debug a packaged app, go to localhost:9997 in your browser. + +### Errors + +If the window doesn't load after running `npm start`: try clicking on dev tools window and hitting `cmd-r` to refresh the window. + +### Logs +Logs are written to the following locations: + +* **Linux:** `~/.config/Lightning/log.log` +* **OSX:** `~/Library/Logs/Lightning/log.log` +* **Windows:** `%USERPROFILE%\AppData\Roaming\Lightning\log.log` + diff --git a/apps/desktop/app.dev.html b/apps/desktop/app.dev.html new file mode 100644 index 000000000..473605121 --- /dev/null +++ b/apps/desktop/app.dev.html @@ -0,0 +1,75 @@ + + +Lightning + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + diff --git a/apps/desktop/app.html b/apps/desktop/app.html new file mode 100644 index 000000000..a33d66de6 --- /dev/null +++ b/apps/desktop/app.html @@ -0,0 +1,75 @@ + + +Lightning + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + diff --git a/apps/desktop/assets/ln-desktop.sketch b/apps/desktop/assets/ln-desktop.sketch new file mode 100644 index 000000000..622d4f4b3 Binary files /dev/null and b/apps/desktop/assets/ln-desktop.sketch differ diff --git a/apps/desktop/assets/ln-logo b/apps/desktop/assets/ln-logo new file mode 100644 index 000000000..5bc12e7ce --- /dev/null +++ b/apps/desktop/assets/ln-logo @@ -0,0 +1,22 @@ +How to use this icon: + +Step 1: Copy the icon to the clipboard +a) Click on this file from the Finder +b) Choose 'Get Info' from the 'File' menu. +c) In the info window that pops up, click on the icon +d) Choose 'Copy' from the 'Edit' menu. +e) Close the info window + +Step 2: Paste the icon to the desired item +a) Go to the item in the Finder that you want a custom icon +b) Click the item (file, folder, disk, etc) +b) Choose 'Get Info' from the 'File' menu. +c) In the info window that pops up, click on the icon +d) Choose 'Paste' from the 'Edit' menu. +e) Close the info window + +Step 3: +Enjoy your newly customized icon! + +For more thorough directions, see Apple's website at: +http://www.apple.com/support/mac101/customize/6/ diff --git a/apps/desktop/assets/ln-logo.icns b/apps/desktop/assets/ln-logo.icns new file mode 100644 index 000000000..dec953960 Binary files /dev/null and b/apps/desktop/assets/ln-logo.icns differ diff --git a/apps/desktop/assets/ln-logo.ico b/apps/desktop/assets/ln-logo.ico new file mode 100644 index 000000000..e95af6406 Binary files /dev/null and b/apps/desktop/assets/ln-logo.ico differ diff --git a/apps/desktop/assets/ln-logo.png b/apps/desktop/assets/ln-logo.png new file mode 100644 index 000000000..b3e786be7 Binary files /dev/null and b/apps/desktop/assets/ln-logo.png differ diff --git a/apps/desktop/assets/ln-logo.sketch b/apps/desktop/assets/ln-logo.sketch new file mode 100644 index 000000000..b89898526 Binary files /dev/null and b/apps/desktop/assets/ln-logo.sketch differ diff --git a/apps/desktop/bin/darwin/lncli b/apps/desktop/bin/darwin/lncli new file mode 100755 index 000000000..7834c6535 Binary files /dev/null and b/apps/desktop/bin/darwin/lncli differ diff --git a/apps/desktop/bin/darwin/lnd b/apps/desktop/bin/darwin/lnd new file mode 100755 index 000000000..3e088c179 Binary files /dev/null and b/apps/desktop/bin/darwin/lnd differ diff --git a/apps/desktop/bin/linux/lnd b/apps/desktop/bin/linux/lnd new file mode 100755 index 000000000..7934131c5 Binary files /dev/null and b/apps/desktop/bin/linux/lnd differ diff --git a/apps/desktop/bin/win32/lnd.exe b/apps/desktop/bin/win32/lnd.exe new file mode 100755 index 000000000..a871ed75c Binary files /dev/null and b/apps/desktop/bin/win32/lnd.exe differ diff --git a/apps/desktop/index.js b/apps/desktop/index.js new file mode 100644 index 000000000..093d7de89 --- /dev/null +++ b/apps/desktop/index.js @@ -0,0 +1,22 @@ +import React from 'react' +import { render } from 'react-dom' +import { Provider } from 'react-redux' +import { ConnectedRouter } from 'react-router-redux' +import 'normalize.css' +import { configureStore, history } from 'lightning-store' +import { App } from 'lightning-app' +import { remote } from 'electron' + +// Release the callbacks on app startup +remote.getCurrentWindow().removeAllListeners() + +const store = configureStore() + +render( + + + + + , + document.getElementById('root'), +) diff --git a/apps/desktop/main.dev.js b/apps/desktop/main.dev.js new file mode 100644 index 000000000..704aabd49 --- /dev/null +++ b/apps/desktop/main.dev.js @@ -0,0 +1,244 @@ +/* eslint-disable global-require, no-console */ + +import { app, BrowserWindow, Menu, ipcMain } from 'electron' +import path from 'path' +import windowStateKeeper from 'electron-window-state' +import _ from 'lodash' +import observe from 'observe' +import cp from 'child_process' +import ps from 'ps-node' +import fileLog from 'electron-log' +import os from 'os' +import fs from 'fs' +import grpc from 'grpc' + +app.commandLine.appendSwitch('remote-debugging-port', '9997') +app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') + +let mainWindow = null +const isDev = process.env.NODE_ENV === 'development' +const runningProcesses = [] + +const isProcessRunning = command => new Promise((resolve, reject) => { + ps.lookup({ command }, + (err, resultList) => { + if (err) { throw new Error(err) } + resultList[0] ? resolve(resultList[0]) : reject() + }, + ) +}) + +const runProcesses = (processes, logs) => { + _.map(processes, (proc) => { + isProcessRunning(proc.name) + .then(() => { + console.log(`${ proc.name } Already Running`) + logs.push(`${ proc.name } Already Running`) + fileLog.info(`${ proc.name } Already Running`) + }) + .catch(() => { + const plat = os.platform() + const filePath = path.join(__dirname, 'bin', plat, plat === 'win32' ? `${ proc.name }.exe` : proc.name) + + try { + const instance = cp.spawn(filePath, proc.args) + runningProcesses.push(instance) + instance.stdout.on('data', data => logs.push(`${ proc.name }: ${ data }`)) + instance.stderr.on('data', (data) => { + logs.push(`${ proc.name } Error: ${ data }`) + fileLog.error(`${ proc.name }: ${ data }`) + }) + } catch (error) { + console.log(`Caught Error When Starting ${ proc.name }: ${ error }`) + logs.push(`Caught Error When Starting ${ proc.name }: ${ error }`) + } + }) + }) +} + +const logBuffer = [] +const logs = observe(logBuffer) + +const processes = [ + { + name: 'lnd', + args: [ + isDev ? '' : '--bitcoin.active', + isDev ? '' : '--neutrino.active', + isDev ? '' : '--configfile=../lnd.conf', + isDev ? '' : '--bitcoin.testnet', + isDev ? '' : '--neutrino.connect=btcd0.lightning.computer:18333', + isDev ? '' : '--neutrino.connect=127.0.0.1:18333', + isDev ? '' : '--debuglevel=info', + isDev ? '' : '--autopilot.active', + '--noencryptwallet', + ], + }, +] + +const appendArgumentsLnd = () => { + processes[0].args = processes[0].args.concat(process.argv.slice(process.argv.indexOf('--') + 1)) +} + +appendArgumentsLnd() +runProcesses(processes, logs) + +let intervalId +let certPath +let macaroonPath +const homedir = os.homedir() + +switch (os.platform()) { + case 'darwin': + certPath = path.join(homedir, 'Library/Application\ Support/Lnd/tls.cert') + macaroonPath = path.join(homedir, 'Library/Application\ Support/Lnd/admin.macaroon') + break + case 'linux': + certPath = path.join(homedir, '.lnd/tls.cert') + macaroonPath = path.join(homedir, '.lnd/admin.macaroon') + break + case 'win32': + certPath = path.join(homedir, 'AppData', 'Local', 'Lnd', 'tls.cert') + macaroonPath = path.join(homedir, 'AppData', 'Local', 'Lnd', 'admin.macaroon') + break + default: + break +} + +const finishCreateWindow = () => { + const mainWindowState = windowStateKeeper({ + defaultWidth: 750, + defaultHeight: 500, + }) + + const plat = os.platform() + + const icon = 'assets/ln-logo' + ({ + 'darwin': '.icns', + 'win32': '.ico', + }[plat] || '.png') + + const { x, y, width, height } = mainWindowState + mainWindow = new BrowserWindow({ + x, + y, + width, + height, + icon: icon, + show: false, + frame: true, + title: 'Lightning', + nodeIntegration: false, + }) + + mainWindow.setMenu(null) + + mainWindowState.manage(mainWindow) + if (isDev) { + mainWindow.loadURL('http://localhost:4152') + } else { + mainWindow.loadURL(`file://${ __dirname }/app.html`) + } + + mainWindow.webContents.on('did-finish-load', () => { + mainWindow.show() + mainWindow.focus() + + mainWindow.webContents.send('logs', logBuffer) + }) + + let logQueue = [] + + logs.on('change', (change) => { + const log = logBuffer[change.index] + logQueue.push(log) + }) + + setInterval(() => { + try { + logQueue.length && mainWindow.webContents.send('logs', logQueue) + logQueue = [] + } catch (err) { + console.log('WARNING: App Was Closed While Writing Logs') + } + }, 2000) + + mainWindow.on('closed', () => { + mainWindow = null + }) + + const template = [ + { + label: 'Lightning', + submenu: [ + { label: 'Quit', accelerator: 'Command+Q', click() { app.quit() } }, + ], + }, { + label: 'Edit', + submenu: [ + { label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:' }, + { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:' }, + { type: 'separator' }, + { label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:' }, + { label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' }, + { label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' }, + { label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:' }, + ], + }, + ] + + !isDev && Menu.setApplicationMenu(Menu.buildFromTemplate(template)) +} + +const createWindow = () => { + intervalId = setInterval(() => { + if (fs.existsSync(certPath)) { + clearInterval(intervalId) + const lndCert = fs.readFileSync(certPath) + const credentials = grpc.credentials.createSsl(lndCert) + const { lnrpc } = grpc.load(path.join(__dirname, 'rpc.proto')) + const connection = new lnrpc.Lightning('localhost:10009', credentials) + let metadata = new grpc.Metadata() + const macaroonHex = fs.readFileSync(macaroonPath).toString("hex") + metadata.add('macaroon', macaroonHex) + const serverReady = cb => + grpc.waitForClientReady(connection, Infinity, cb) + global.connection = connection + global.metadata = metadata + global.serverReady = serverReady + finishCreateWindow() + } + }, 500) +} + +require('electron-debug')({ enabled: true }) + +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { + app.quit() + } +}) + +ipcMain.on('terminal-command', (event, args) => { + const plat = os.platform() + const filePath = path.join(__dirname, 'bin', plat, plat === 'win32' ? `lncli.exe` : 'lncli') + const instance = cp.spawn(filePath, args) + let dt = new Date().toISOString().replace('T', ' ').replace('Z', ' ') + logs.push(`${ dt } $ lncli ${ args.join(' ') }`) + instance.stdout.on('data', data => logs.push(`${ data }`)) + instance.stderr.on('data', (data) => { + logs.push(`Error: ${ data }`) + fileLog.error(` ${ data }`) + }) +}) + +app.on('ready', createWindow) + +app.on('quit', () => { + runningProcesses.forEach(proc => proc.kill()) +}) + +process.on('uncaughtException', (error) => { + console.log('Caught Main Process Error:', error) + fileLog.error(`Main Process: ${ error }`) +}) diff --git a/apps/desktop/package.json b/apps/desktop/package.json new file mode 100644 index 000000000..09476394e --- /dev/null +++ b/apps/desktop/package.json @@ -0,0 +1,68 @@ +{ + "name": "lightning-desktop", + "productName": "Lightning", + "version": "1.1.0", + "description": "main.js", + "main": "main.js", + "engines": { + "node": "^6.7.0" + }, + "scripts": { + "package": "cross-env NODE_ENV=production node -r babel-register -r babel-polyfill scripts/package.js", + "package-all": "npm run package -- --all", + "start": "f() { node scripts/startup-message.js && concurrently --kill-others \"npm run start-electron -- $*\" \"npm run start-webpack\" -n \"electron,webpack\" -p name; }; f", + "start-electron": "cross-env HOT=1 NODE_ENV=development electron -r babel-register ./main.dev --", + "start-webpack": "cross-env NODE_ENV=development node -r babel-register scripts/dev-server.js", + "install-grpc": "cd node_modules/grpc && git submodule update --init && npm run electron-build -- --target=1.4.6" + }, + "bin": { + "electron": "./node_modules/.bin/electron" + }, + "author": "case ", + "license": "MIT", + "dependencies": { + "babel-loader": "^6.2.10", + "babel-polyfill": "^6.20.0", + "babel-register": "^6.18.0", + "concurrently": "^3.1.0", + "css-loader": "^0.26.1", + "electron-debug": "^1.1.0", + "electron-log": "^2.2.6", + "electron-packager": "^8.4.0", + "electron-prebuilt": "^1.4.6", + "electron-window-state": "^4.0.1", + "express": "^4.14.0", + "extract-text-webpack-plugin": "^1.0.1", + "file-loader": "^0.9.0", + "grpc": "^1.1.1", + "json-loader": "^0.5.4", + "lightning-app": "^0.1.0", + "lightning-components": "^0.1.1", + "lightning-core": "^1.9.1", + "lightning-notifications": "^0.1.1", + "lightning-store": "^0.1.1", + "lodash": "^4.17.2", + "normalize.css": "^5.0.0", + "observe": "^1.3.7", + "protobufjs": "^6.4.6", + "ps-node": "^0.1.4", + "react": "^15.4.1", + "react-dom": "^15.4.1", + "react-redux": "^4.4.6", + "react-router-dom": "^4.0.0", + "react-router-redux": "^5.0.0-alpha.6", + "reactcss": "^1.1.1", + "redux": "^3.6.0", + "source-map-support": "^0.4.8", + "style-loader": "^0.13.1", + "webpack": "^1.14.0", + "webpack-dev-middleware": "^1.9.0", + "webpack-hot-middleware": "^2.13.2", + "webpack-merge": "^1.1.2", + "webpack-validator": "^2.3.0" + }, + "devDependencies": { + "babel-register": "^6.18.0", + "cross-env": "^3.1.3" + } +} diff --git a/apps/desktop/rpc.proto b/apps/desktop/rpc.proto new file mode 100644 index 000000000..be87075f3 --- /dev/null +++ b/apps/desktop/rpc.proto @@ -0,0 +1,605 @@ +syntax = "proto3"; + +package lnrpc; + +service Lightning { + rpc WalletBalance (WalletBalanceRequest) returns (WalletBalanceResponse) { + } + rpc ChannelBalance (ChannelBalanceRequest) returns (ChannelBalanceResponse) { + } + + rpc GetTransactions (GetTransactionsRequest) returns (TransactionDetails) { + } + rpc SendCoins (SendCoinsRequest) returns (SendCoinsResponse) { + } + rpc SubscribeTransactions (GetTransactionsRequest) returns (stream Transaction); + + rpc SendMany (SendManyRequest) returns (SendManyResponse); + + rpc NewAddress (NewAddressRequest) returns (NewAddressResponse); + rpc NewWitnessAddress (NewWitnessAddressRequest) returns (NewAddressResponse) { + } + + rpc SignMessage (SignMessageRequest) returns (SignMessageResponse); + rpc VerifyMessage (VerifyMessageRequest) returns (VerifyMessageResponse); + + rpc ConnectPeer (ConnectPeerRequest) returns (ConnectPeerResponse) { + } + + rpc DisconnectPeer (DisconnectPeerRequest) returns (DisconnectPeerResponse) { + } + + rpc ListPeers (ListPeersRequest) returns (ListPeersResponse) { + } + rpc GetInfo (GetInfoRequest) returns (GetInfoResponse) { + } + + // TODO(roasbeef): merge with below with bool? + rpc PendingChannels (PendingChannelRequest) returns (PendingChannelResponse) { + } + rpc ListChannels (ListChannelsRequest) returns (ListChannelsResponse) { + } + rpc OpenChannelSync (OpenChannelRequest) returns (ChannelPoint) { + } + + rpc OpenChannel (OpenChannelRequest) returns (stream OpenStatusUpdate); + + rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) { + } + + rpc SendPayment (stream SendRequest) returns (stream SendResponse); + + rpc SendPaymentSync (SendRequest) returns (SendResponse) { + } + + rpc AddInvoice (Invoice) returns (AddInvoiceResponse) { + } + rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) { + } + rpc LookupInvoice (PaymentHash) returns (Invoice) { + } + rpc SubscribeInvoices (InvoiceSubscription) returns (stream Invoice) { + } + rpc DecodePayReq (PayReqString) returns (PayReq) { + } + + rpc ListPayments (ListPaymentsRequest) returns (ListPaymentsResponse) { + }; + + rpc DeleteAllPayments (DeleteAllPaymentsRequest) returns (DeleteAllPaymentsResponse) { + }; + + rpc DescribeGraph (ChannelGraphRequest) returns (ChannelGraph) { + } + + rpc GetChanInfo (ChanInfoRequest) returns (ChannelEdge) { + } + + rpc GetNodeInfo (NodeInfoRequest) returns (NodeInfo) { + } + + rpc QueryRoutes(QueryRoutesRequest) returns (QueryRoutesResponse) { + } + + rpc GetNetworkInfo (NetworkInfoRequest) returns (NetworkInfo) { + } + + rpc StopDaemon(StopRequest) returns (StopResponse); + + rpc SubscribeChannelGraph(GraphTopologySubscription) returns (stream GraphTopologyUpdate); + + rpc SetAlias(SetAliasRequest) returns (SetAliasResponse); + + rpc DebugLevel (DebugLevelRequest) returns (DebugLevelResponse); +} + +message Transaction { + string tx_hash = 1 [ json_name = "tx_hash" ]; + int64 amount = 2 [ json_name = "amount" ]; + int32 num_confirmations = 3 [ json_name = "num_confirmations" ]; + string block_hash = 4 [ json_name = "block_hash" ]; + int32 block_height = 5 [ json_name = "block_height" ]; + int64 time_stamp = 6 [ json_name = "time_stamp" ]; + int64 total_fees = 7 [ json_name = "total_fees" ]; +} +message GetTransactionsRequest { +} +message TransactionDetails { + repeated Transaction transactions = 1 [json_name = "transactions"]; +} + +message SendRequest { + bytes dest = 1; + string dest_string = 2; + + int64 amt = 3; + + bytes payment_hash = 4; + string payment_hash_string = 5; + + string payment_request = 6; +} +message SendResponse { + string payment_error = 1 [json_name = "payment_error"]; + bytes payment_preimage = 2 [json_name = "payment_preimage"]; + Route payment_route = 3 [json_name = "payment_route"]; +} + +message ChannelPoint { + // TODO(roasbeef): make str vs bytes into a oneof + bytes funding_txid = 1 [ json_name = "funding_txid" ]; + string funding_txid_str = 2 [ json_name = "funding_txid_str" ]; + uint32 output_index = 3 [ json_name = "output_index" ]; +} + +message LightningAddress { + string pubkey = 1 [json_name = "pubkey"]; + string host = 2 [json_name = "host"]; +} + +message SendManyRequest { + map AddrToAmount = 1; +} +message SendManyResponse { + string txid = 1 [json_name = "txid"]; +} + +message SendCoinsRequest { + string addr = 1; + int64 amount = 2; +} +message SendCoinsResponse { + string txid = 1 [json_name = "txid"]; +} + +message NewAddressRequest { + enum AddressType { + WITNESS_PUBKEY_HASH = 0; + NESTED_PUBKEY_HASH = 1; + PUBKEY_HASH = 2; + } + AddressType type = 1; +} +message NewWitnessAddressRequest { +} +message NewAddressResponse { + string address = 1 [json_name = "address"]; +} + +message SignMessageRequest { + bytes msg = 1 [ json_name = "msg" ]; +} +message SignMessageResponse { + string signature = 1 [ json_name = "signature" ]; +} + +message VerifyMessageRequest { + bytes msg = 1 [ json_name = "msg" ]; + string signature = 2 [ json_name = "signature" ]; +} +message VerifyMessageResponse { + bool valid = 1 [ json_name = "valid" ]; + string pubkey = 2 [ json_name = "pubkey" ]; +} + +message ConnectPeerRequest { + LightningAddress addr = 1; + bool perm = 2; +} +message ConnectPeerResponse { + int32 peer_id = 1 [json_name = "peer_id"]; +} + +message DisconnectPeerRequest { + string pub_key = 1 [json_name = "pub_key"]; +} +message DisconnectPeerResponse { +} + +message HTLC { + bool incoming = 1 [json_name = "incoming"]; + int64 amount = 2 [json_name = "amount"]; + bytes hash_lock = 3 [json_name = "hash_lock"]; + uint32 expiration_height = 4 [json_name = "expiration_height"]; + uint32 revocation_delay = 5 [json_name = "revocation_delay"]; +} + +message ActiveChannel { + bool active = 1 [json_name = "active"]; + string remote_pubkey = 2 [json_name = "remote_pubkey"]; + string channel_point = 3 [json_name = "channel_point"]; + uint64 chan_id = 4 [json_name = "chan_id"]; + + int64 capacity = 5 [json_name = "capacity"]; + int64 local_balance = 6 [json_name = "local_balance"]; + int64 remote_balance = 7 [json_name = "remote_balance"]; + + int64 commit_fee = 8 [json_name = "commit_fee"]; + int64 commit_weight = 9 [ json_name = "commit_weight" ]; + int64 fee_per_kw = 10 [json_name = "fee_per_kw"]; + + int64 unsettled_balance = 11 [json_name = "unsettled_balance"]; + int64 total_satoshis_sent = 12 [json_name = "total_satoshis_sent"]; + int64 total_satoshis_received = 13 [json_name = "total_satoshis_received"]; + uint64 num_updates = 14 [json_name = "num_updates"]; + + repeated HTLC pending_htlcs = 15 [json_name = "pending_htlcs"]; +} + +message ListChannelsRequest { +} +message ListChannelsResponse { + repeated ActiveChannel channels = 11 [json_name = "channels"]; +} + +message Peer { + string pub_key = 1 [json_name = "pub_key"]; + int32 peer_id = 2 [json_name = "peer_id"]; + string address = 3 [json_name = "address"]; + + uint64 bytes_sent = 4 [json_name = "bytes_sent"]; + uint64 bytes_recv = 5 [json_name = "bytes_recv"]; + + int64 sat_sent = 6 [json_name = "sat_sent"]; + int64 sat_recv = 7 [json_name = "sat_recv"]; + + bool inbound = 8 [json_name = "inbound"]; + + int64 ping_time = 9 [json_name = "ping_time"]; +} + +message ListPeersRequest { +} +message ListPeersResponse { + repeated Peer peers = 1 [json_name = "peers"]; +} + +message GetInfoRequest { +} +message GetInfoResponse { + string identity_pubkey = 1 [json_name = "identity_pubkey"]; + string alias = 2 [json_name = "alias"]; + + uint32 num_pending_channels = 3 [json_name = "num_pending_channels"]; + uint32 num_active_channels = 4 [json_name = "num_active_channels"]; + + uint32 num_peers = 5 [json_name = "num_peers"]; + + uint32 block_height = 6 [json_name = "block_height"]; + string block_hash = 8 [json_name = "block_hash"]; + + bool synced_to_chain = 9 [ json_name = "synced_to_chain" ]; + bool testnet = 10 [ json_name = "testnet" ]; + + repeated string chains = 11 [ json_name = "chains" ]; +} + +message ConfirmationUpdate { + bytes block_sha = 1; + int32 block_height = 2; + + uint32 num_confs_left = 3; +} + +message ChannelOpenUpdate { + ChannelPoint channel_point = 1 [json_name = "channel_point"]; +} + +message ChannelCloseUpdate { + bytes closing_txid = 1 [json_name = "closing_txid"]; + + bool success = 2 [json_name = "success"]; +} + +message CloseChannelRequest { + ChannelPoint channel_point = 1; + int64 time_limit = 2; + bool force = 3; +} +message CloseStatusUpdate { + oneof update { + PendingUpdate close_pending = 1 [json_name = "close_pending"]; + ConfirmationUpdate confirmation = 2 [json_name = "confirmation"]; + ChannelCloseUpdate chan_close = 3 [json_name = "chan_close"]; + } +} + +message PendingUpdate { + bytes txid = 1 [json_name = "txid"]; + uint32 output_index = 2 [json_name = "output_index"]; +} + +message OpenChannelRequest { + int32 target_peer_id = 1 [json_name = "target_peer_id"]; + bytes node_pubkey = 2 [json_name = "node_pubkey"]; + string node_pubkey_string = 3 [json_name = "node_pubkey_string"]; + + int64 local_funding_amount = 4 [json_name = "local_funding_amount"]; + int64 push_sat = 5 [json_name = "push_sat"]; + + uint32 num_confs = 6 [json_name = "num_confs"]; +} +message OpenStatusUpdate { + oneof update { + PendingUpdate chan_pending = 1 [json_name = "chan_pending"]; + ConfirmationUpdate confirmation = 2 [json_name = "confirmation"]; + ChannelOpenUpdate chan_open = 3 [json_name = "chan_open"]; + } +} + +message PendingChannelRequest {} +message PendingChannelResponse { + message PendingChannel { + string remote_node_pub = 1 [ json_name = "remote_node_pub" ]; + string channel_point = 2 [ json_name = "channel_point" ]; + + int64 capacity = 3 [ json_name = "capacity" ]; + + int64 local_balance = 4 [ json_name = "local_balance" ]; + int64 remote_balance = 5 [ json_name = "remote_balance" ]; + } + + message PendingOpenChannel { + PendingChannel channel = 1 [ json_name = "channel" ]; + + uint32 confirmation_height = 2 [ json_name = "confirmation_height" ]; + uint32 blocks_till_open = 3 [ json_name = "blocks_till_open" ]; + + int64 commit_fee = 4 [json_name = "commit_fee" ]; + int64 commit_weight = 5 [ json_name = "commit_weight" ]; + int64 fee_per_kw = 6 [ json_name = "fee_per_kw" ]; + } + + message ClosedChannel { + PendingChannel channel = 1; + + string closing_txid = 2 [ json_name = "closing_txid" ]; + } + + message ForceClosedChannel { + PendingChannel channel = 1 [ json_name = "channel" ]; + + // TODO(roasbeef): HTLC's as well? + + string closing_txid = 2 [ json_name = "closing_txid" ]; + + int64 limbo_balance = 3 [ json_name = "limbo_balance" ]; + uint32 maturity_height = 4 [ json_name = "maturity_height" ]; + uint32 blocks_til_maturity = 5 [ json_name = "blocks_til_maturity" ]; + } + + int64 total_limbo_balance = 1 [ json_name = "total_limbo_balance" ]; + repeated PendingOpenChannel pending_open_channels = 2 [ json_name = "pending_open_channels" ]; + repeated ClosedChannel pending_closing_channels = 3 [ json_name = "pending_closing_channels" ]; + repeated ForceClosedChannel pending_force_closing_channels = 4 [ json_name = "pending_force_closing_channels" ]; +} + +message WalletBalanceRequest { + bool witness_only = 1; +} +message WalletBalanceResponse { + int64 balance = 1 [json_name = "balance"]; +} + +message ChannelBalanceRequest { +} +message ChannelBalanceResponse { + int64 balance = 1 [json_name = "balance"]; +} + +message QueryRoutesRequest { + string pub_key = 1; + int64 amt = 2; +} +message QueryRoutesResponse { + repeated Route routes = 1 [ json_name = "routes"]; +} + +message Hop { + uint64 chan_id = 1 [json_name = "chan_id"]; + int64 chan_capacity = 2 [json_name = "chan_capacity"]; + int64 amt_to_forward = 3 [json_name = "amt_to_forward"]; + int64 fee = 4 [json_name = "fee"]; +} + +message Route { + uint32 total_time_lock = 1 [json_name = "total_time_lock"]; + int64 total_fees = 2 [json_name = "total_fees"]; + int64 total_amt = 3 [json_name = "total_amt"]; + + repeated Hop hops = 4 [json_name = "hops"]; +} + +message NodeInfoRequest { + string pub_key = 1; +} + +message NodeInfo { + LightningNode node = 1 [json_name = "node"]; + + uint32 num_channels = 2 [json_name = "num_channels"]; + int64 total_capacity = 3 [json_name = "total_capacity"]; +} + +message LightningNode { + uint32 last_update = 1 [ json_name = "last_update" ]; + string pub_key = 2 [ json_name = "pub_key" ]; + string alias = 3 [ json_name = "alias" ]; + repeated NodeAddress addresses = 4 [ json_name = "addresses" ]; +} + +message NodeAddress { + string network = 1 [ json_name = "network" ]; + string addr = 2 [ json_name = "addr" ]; +} + +message RoutingPolicy { + uint32 time_lock_delta = 1 [json_name = "time_lock_delta"]; + int64 min_htlc = 2 [json_name = "min_htlc"]; + int64 fee_base_msat = 3 [json_name = "fee_base_msat"]; + int64 fee_rate_milli_msat = 4 [json_name = "fee_rate_milli_msat"]; +} + +message ChannelEdge { + uint64 channel_id = 1 [json_name = "channel_id"]; + string chan_point = 2 [json_name = "chan_point"]; + + uint32 last_update = 3 [json_name = "last_update"]; + + string node1_pub = 4 [json_name = "node1_pub"]; + string node2_pub = 5 [json_name = "node2_pub"]; + + int64 capacity = 6 [json_name = "capacity"]; + + RoutingPolicy node1_policy = 7 [json_name = "node1_policy"]; + RoutingPolicy node2_policy = 8 [json_name = "node2_policy"]; +} + +message ChannelGraphRequest { +} + +message ChannelGraph { + repeated LightningNode nodes = 1 [json_name = "nodes"]; + repeated ChannelEdge edges = 2 [json_name = "edges"]; +} + +message ChanInfoRequest { + uint64 chan_id = 1; +} + +message NetworkInfoRequest { +} +message NetworkInfo { + uint32 graph_diameter = 1 [json_name = "graph_diameter"]; + double avg_out_degree = 2 [json_name = "avg_out_degree"]; + uint32 max_out_degree = 3 [json_name = "max_out_degree"]; + + uint32 num_nodes = 4 [json_name = "num_nodes"]; + uint32 num_channels = 5 [json_name = "num_channels"]; + + int64 total_network_capacity = 6 [json_name = "total_network_capacity"]; + + double avg_channel_size = 7 [json_name = "avg_channel_size"]; + int64 min_channel_size = 8 [json_name = "min_channel_size"]; + int64 max_channel_size = 9 [json_name = "max_channel_size"]; + + // TODO(roasbeef): fee rate info, expiry + // * also additional RPC for tracking fee info once in +} + +message StopRequest{} +message StopResponse{} + +message GraphTopologySubscription {} +message GraphTopologyUpdate { + repeated NodeUpdate node_updates = 1; + repeated ChannelEdgeUpdate channel_updates = 2; + repeated ClosedChannelUpdate closed_chans = 3; +} +message NodeUpdate { + repeated string addresses = 1; + string identity_key = 2; + bytes global_features = 3; + string alias = 4; +} +message ChannelEdgeUpdate { + uint64 chan_id = 1; + + ChannelPoint chan_point = 2; + + int64 capacity = 3; + + RoutingPolicy routing_policy = 4; + + string advertising_node = 5; + string connecting_node = 6; +} +message ClosedChannelUpdate { + uint64 chan_id = 1; + int64 capacity = 2; + uint32 closed_height = 3; + ChannelPoint chan_point = 4; +} + +message SetAliasRequest { + string new_alias = 1; +} +message SetAliasResponse { +} + +message Invoice { + string memo = 1 [json_name = "memo"]; + bytes receipt = 2 [json_name = "receipt"]; + + bytes r_preimage = 3 [json_name = "r_preimage"]; + bytes r_hash = 4 [json_name = "r_hash"]; + + int64 value = 5 [json_name = "value"]; + + bool settled = 6 [json_name = "settled"]; + + int64 creation_date = 7 [json_name = "creation_date"]; + int64 settle_date = 8 [json_name = "settle_date"]; + + string payment_request = 9 [json_name = "payment_request"]; +} +message AddInvoiceResponse { + bytes r_hash = 1 [json_name = "r_hash"]; + + string payment_request = 2 [json_name = "payment_request"]; +} +message PaymentHash { + string r_hash_str = 1 [json_name = "r_hash_str"]; + bytes r_hash = 2 [json_name = "r_hash"]; +} +message ListInvoiceRequest { + bool pending_only = 1; +} +message ListInvoiceResponse { + repeated Invoice invoices = 1 [json_name = "invoices"]; +} + +message InvoiceSubscription { +} + + +message Payment { + string payment_hash = 1 [json_name = "payment_hash"]; + int64 value = 2 [json_name = "value"]; + + int64 creation_date = 3 [json_name = "creation_date"]; + + repeated string path = 4 [ json_name = "path" ]; + + int64 fee = 5 [json_name = "fee"]; +} + +message ListPaymentsRequest { +} + +message ListPaymentsResponse { + repeated Payment payments = 1 [json_name = "payments"]; +} + +message DeleteAllPaymentsRequest { +} + +message DeleteAllPaymentsResponse { +} + +message DebugLevelRequest { + bool show = 1; + string level_spec = 2; +} +message DebugLevelResponse { + string sub_systems = 1 [json_name = "sub_systems"]; +} + +message PayReqString { + string pay_req = 1; +} +message PayReq { + string destination = 1 [json_name = "destination"]; + string payment_hash = 2 [json_name = "payment_hash"]; + int64 num_satoshis = 3 [json_name = "num_satoshis"]; +} diff --git a/packages/lightning-webpack/server.js b/apps/desktop/scripts/dev-server.js similarity index 55% rename from packages/lightning-webpack/server.js rename to apps/desktop/scripts/dev-server.js index 6f12b2177..ab49010e7 100644 --- a/packages/lightning-webpack/server.js +++ b/apps/desktop/scripts/dev-server.js @@ -1,24 +1,31 @@ /* eslint-disable no-console */ - import express from 'express' import webpack from 'webpack' +import path from 'path' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' -import config from './webpack.config.development' +import config from '../webpack.config.development' const app = express() const compiler = webpack(config) const PORT = process.env.PORT || 4152 -app.use(webpackDevMiddleware(compiler, { +const middleware = webpackDevMiddleware(compiler, { publicPath: config.output.publicPath, noInfo: true, -})) +}) +app.use(middleware) app.use(webpackHotMiddleware(compiler)) +app.use(express.static('static')) +app.get('*', (request, response) => { + response.sendFile(path.resolve(__dirname, '..', 'app.dev.html')) +}) + app.listen(PORT, 'localhost', (err) => { - if (err) { console.error(err); return } - console.log(`Listening at http://localhost:${ PORT }`) + if (err) { console.error(err) } }) + +console.log('Building...') diff --git a/apps/desktop/scripts/package.js b/apps/desktop/scripts/package.js new file mode 100644 index 000000000..593c0cf9a --- /dev/null +++ b/apps/desktop/scripts/package.js @@ -0,0 +1,123 @@ +/* eslint-disable no-console, consistent-return */ +/* eslint generator-star-spacing: 0 */ + +import 'babel-polyfill' +import _ from 'lodash' +import os from 'os' +import path from 'path' +import webpack from 'webpack' +import packager from 'electron-packager' +import del from 'del' +import minimist from 'minimist' +import prodCfg from '../webpack.config.production' +import electronCfg from '../webpack.config.electron' +import pkg from '../package.json' + +const argv = minimist(process.argv.slice(2)) +const toNodePath = name => `/node_modules/${ name }($|/)` +const devDeps = Object + .keys(pkg.devDependencies) + .map(toNodePath) + +const depsExternal = Object + .keys(pkg.dependencies) + .filter(name => !electronCfg.externals.includes(name)) + .map(toNodePath) + +// Because GRPC Needs Lodash But Wont Install It For Some Reason +const depsMinusLodash = + _.remove(depsExternal, path => path !== '/node_modules/lodash($|/)') + +const appName = argv.name || argv.n || pkg.productName +const shouldUseAsar = argv.asar || argv.a || false +const shouldBuildAll = argv.all || false + +const DEFAULT_OPTS = { + dir: './', + name: appName, + asar: shouldUseAsar, + icon: argv.icon || argv.i || 'assets/ln-logo', + ignore: [ + '^/test($|/)', + '^/release($|/)', + '^/main.dev.js', + ] + .concat(devDeps) + .concat(depsMinusLodash), +} + +function build(config) { + return new Promise((resolve, reject) => { + webpack(config, (err, stats) => { + if (err) return reject(err) + resolve(stats) + }) + }) +} + +function pack(plat, arch, cb) { + // there is no darwin ia32 electron + if (plat === 'darwin' && arch === 'ia32') return + + const icon = DEFAULT_OPTS.icon + ({ + 'darwin': '.icns', + 'win32': '.ico', + }[plat] || '.png') + + const opts = { + ...DEFAULT_OPTS, + icon, + platform: plat, + arch, + appVersion: pkg.version || DEFAULT_OPTS.version, + out: '../../release', + protocols: [{ + name: 'Lightning', + schemes: ['lightning'], + }], + } + + packager(opts, cb) +} + + +function log(plat, arch) { + return (err, filepath) => { + if (err) return console.error(err, filepath) + console.log(`${ plat }-${ arch } finished!`) + } +} + +function startPack() { + console.log('Start pack...') + + Promise.all( + [ + del('../../release', { force: true }), + build(electronCfg), + build(prodCfg), + ], + ).then(() => { + if (shouldBuildAll) { + const archs = ['x64'] + const platforms = ['linux', 'win32', 'darwin'] + + platforms.forEach((plat) => { + archs.forEach((arch) => { + pack(plat, arch, log(plat, arch)) + }) + }) + } else { + // build for current platform only + pack(os.platform(), os.arch(), log(os.platform(), os.arch())) + } + }).catch((error) => { + console.log('Error:', JSON.stringify(error, null, 2)) + console.log('Retrying...') + startPack() + }) +} + +const version = argv.version || argv.v +DEFAULT_OPTS.electronVersion = version || '1.4.6' +startPack() diff --git a/apps/desktop/scripts/startup-message.js b/apps/desktop/scripts/startup-message.js new file mode 100644 index 000000000..4033a31f1 --- /dev/null +++ b/apps/desktop/scripts/startup-message.js @@ -0,0 +1,12 @@ +/* eslint-disable no-console */ + +console.log('') +console.log(' ___ ________ ________ ________ ________ ') +console.log('|\\ \\ |\\ ___ \\ |\\ __ \\|\\ __ \\|\\ __ \\ ') +console.log('\\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\ \\|\\ \\ \\ \\|\\ \\ \\ \\|\\ \\ ') +console.log(' \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\ __ \\ \\ ____\\ \\ ____\\ ') +console.log(' \\ \\ \\____\\ \\ \\\\ \\ \\ \\ \\ \\ \\ \\ \\ \\___|\\ \\ \\___| ') +console.log(' \\ \\_______\\ \\__\\\\ \\__\\ \\ \\__\\ \\__\\ \\__\\ \\ \\__\\ ') +console.log(' \\|_______|\\|__| \\|__| \\|__|\\|__|\\|__| \\|__| ') +console.log('') +console.log('') diff --git a/packages/lightning-webpack/webpack.config.base.js b/apps/desktop/webpack.config.base.js similarity index 77% rename from packages/lightning-webpack/webpack.config.base.js rename to apps/desktop/webpack.config.base.js index 83ddb48a8..186629149 100644 --- a/packages/lightning-webpack/webpack.config.base.js +++ b/apps/desktop/webpack.config.base.js @@ -8,7 +8,7 @@ export default validate({ { test: /\.js?$/, loaders: ['babel?cacheDirectory'], - exclude: /node_modules\/(?!lightning-core|lightning-core-ui)/, + exclude: /node_modules/, }, { test: /\.json$/, @@ -31,20 +31,18 @@ export default validate({ // https://webpack.github.io/docs/configuration.html#resolve resolve: { - root: __dirname, extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'], - alias: { - 'redux-grpc-middlware': 'packages/redux-grpc-middlware', - 'lightning-notifications': 'packages/lightning-notifications', - 'lightning-store': 'packages/lightning-store', - }, }, plugins: [ new webpack.DefinePlugin({ 'global.GENTLY': false }), ], + resolveLoader: { + root: path.resolve(__dirname, 'node_modules'), + }, + externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) diff --git a/packages/lightning-webpack/webpack.config.development.js b/apps/desktop/webpack.config.development.js similarity index 98% rename from packages/lightning-webpack/webpack.config.development.js rename to apps/desktop/webpack.config.development.js index 67efe6050..0a4eeba1a 100644 --- a/packages/lightning-webpack/webpack.config.development.js +++ b/apps/desktop/webpack.config.development.js @@ -14,7 +14,7 @@ export default validate(merge(baseConfig, { app: [ `webpack-hot-middleware/client?path=http://localhost:${ port }/__webpack_hmr`, 'babel-polyfill', - './app/index', + './index', ], vendor: ['react', 'redux', 'lodash'], }, diff --git a/packages/lightning-webpack/webpack.config.electron.js b/apps/desktop/webpack.config.electron.js similarity index 93% rename from packages/lightning-webpack/webpack.config.electron.js rename to apps/desktop/webpack.config.electron.js index bf92d99a0..3107dc215 100644 --- a/packages/lightning-webpack/webpack.config.electron.js +++ b/apps/desktop/webpack.config.electron.js @@ -6,12 +6,13 @@ import baseConfig from './webpack.config.base' export default validate(merge(baseConfig, { devtool: 'source-map', - entry: ['babel-polyfill', './main.development'], + entry: ['babel-polyfill', './main.dev'], // 'main.js' in root output: { path: __dirname, filename: './main.js', + libraryTarget: 'commonjs2', }, plugins: [ @@ -56,5 +57,7 @@ export default validate(merge(baseConfig, { externals: [ 'font-awesome', 'source-map-support', + 'grpc', + 'protobufjs', ], })) diff --git a/packages/lightning-webpack/webpack.config.production.js b/apps/desktop/webpack.config.production.js similarity index 90% rename from packages/lightning-webpack/webpack.config.production.js rename to apps/desktop/webpack.config.production.js index 0e70dab9b..a18fa8c1a 100644 --- a/packages/lightning-webpack/webpack.config.production.js +++ b/apps/desktop/webpack.config.production.js @@ -9,10 +9,13 @@ import baseConfig from './webpack.config.base' const config = validate(merge(baseConfig, { devtool: 'cheap-module-source-map', - entry: [ - 'babel-polyfill', - './app/index', - ], + entry: { + app: [ + 'babel-polyfill', + './index', + ], + vendor: ['react', 'redux', 'lodash'], + }, output: { publicPath: '../dist/', @@ -60,6 +63,7 @@ const config = validate(merge(baseConfig, { // Set the ExtractTextPlugin output filename new ExtractTextPlugin('style.css', { allChunks: true }), + new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js', Infinity), ], // https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works diff --git a/lerna.json b/lerna.json index 6f3c8e3c4..609861fad 100644 --- a/lerna.json +++ b/lerna.json @@ -1,6 +1,7 @@ { "lerna": "2.0.0-beta.31", "packages": [ + "apps/*", "packages/*" ], "version": "independent" diff --git a/package.json b/package.json index 5987a0ad7..5325fbaf5 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,19 @@ { "name": "lightning-app", - "version": "0.1.0", + "version": "0.1.3-1", "description": "", "main": "index.js", "scripts": { "postinstall": "lerna bootstrap", "publish": "lerna publish", - "clean": "find . -name 'node_modules' -exec rm -rf '{}' +" + "clean": "lerna clean", + "reinstall": "npm run clean && npm install", + "start": "cd apps/desktop && npm start -s --", + "setup": "npm install && npm run install-grpc", + "package-electron": "cd apps/desktop && npm run package", + "package-all-electron": "cd apps/desktop && npm run package-all", + "eslint": "node_modules/.bin/eslint packages/**/*.js --quiet", + "install-grpc": "cd apps/desktop && npm run install-grpc" }, "repository": { "type": "git", @@ -15,12 +22,13 @@ "author": "case ", "private": true, "devDependencies": { - "babel-eslint": "^6.1.2", - "eslint": "^3.6.0", - "eslint-config-airbnb": "^11.2.0", - "eslint-plugin-import": "^1.16.0", - "eslint-plugin-jsx-a11y": "^2.2.2", - "eslint-plugin-react": "^6.3.0", - "lerna": "2.0.0-beta.31" + "@case/eslint-config": "^0.1.2", + "babel-preset-es2015": "^6.14.0", + "babel-preset-react": "^6.11.1", + "babel-preset-react-hmre": "^1.1.1", + "babel-preset-stage-0": "^6.5.0", + "lerna": "2.0.0-beta.31", + "react": "^15.4.1", + "react-dom": "^15.4.1" } } diff --git a/packages/lightning-app/App.js b/packages/lightning-app/App.js new file mode 100644 index 000000000..4f1b07884 --- /dev/null +++ b/packages/lightning-app/App.js @@ -0,0 +1,61 @@ +import React from 'react' +import reactCSS from 'reactcss' + +import { Route, Switch, Redirect } from 'react-router-dom' +import { Box } from 'lightning-components' +import { Notifications } from 'lightning-notifications' +import { Sidebar, PayPage, RequestPage, AccountsPage, CreateChannelPage, + TransactionsPage, SettingsPage, Streams } from 'lightning-core' + +const App = () => { + const styles = reactCSS({ + 'default': { + app: { + direction: 'row', + absolute: '0 0 0 0', + fontFamily: '"Roboto", "Helvetica", sans-serif', + overflow: 'hidden', + }, + lights: { + paddingTop: 'medium', + paddingLeft: 'medium', + }, + sidebar: { + direction: 'column', + userSelect: 'none', + cursor: 'default', + width: '170px', + color: 'white', + }, + content: { + background: 'off-white', + flex: '1', + overflowY: 'scroll', + display: 'flex', + }, + }, + }) + + return ( + + + + + + + + + + + + + } /> + + + + + + ) +} + +export default App diff --git a/packages/lightning-app/index.js b/packages/lightning-app/index.js new file mode 100644 index 000000000..f52c042e6 --- /dev/null +++ b/packages/lightning-app/index.js @@ -0,0 +1 @@ +export { default as App } from './App' diff --git a/packages/lightning-app/package.json b/packages/lightning-app/package.json new file mode 100644 index 000000000..487b9c2c2 --- /dev/null +++ b/packages/lightning-app/package.json @@ -0,0 +1,19 @@ +{ + "version": "0.1.0", + "name": "lightning-app", + "main": "index.js", + "scripts": { + "start": "node index.js" + }, + "author": "case ", + "license": "MIT", + "dependencies": { + "@components/electron": "^0.3.0", + "lightning-components": "^0.1.0", + "lightning-core": "^1.9.1", + "lightning-notifications": "^0.1.0", + "react": "^15.4.1", + "react-router-dom": "^4.0.0", + "reactcss": "^1.1.1" + } +} diff --git a/packages/lightning-components/Box/index.js b/packages/lightning-components/Box/index.js index 55a87de1e..983eadfd5 100644 --- a/packages/lightning-components/Box/index.js +++ b/packages/lightning-components/Box/index.js @@ -9,7 +9,6 @@ const keys = ['display', 'direction', 'color', 'background', 'padding', 'padding 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontSize', 'align', 'verticalAlign', 'spread', 'zDepth'] - export const Box = (props) => { const styles = reactCSS({ 'default': { @@ -35,12 +34,10 @@ export const Box = (props) => { row: { display: 'flex', flexDirection: 'row', - // alignItems: 'stretch', }, column: { display: 'flex', flexDirection: 'column', - // alignItems: 'stretch', }, }, 'box'), @@ -144,7 +141,7 @@ export const Box = (props) => { const Tag = props.tag || 'div' return ( - + { props.children } ) diff --git a/packages/lightning-components/Icon/index.js b/packages/lightning-components/Icon/index.js new file mode 100644 index 000000000..b25e69d38 --- /dev/null +++ b/packages/lightning-components/Icon/index.js @@ -0,0 +1,43 @@ +import React from 'react' +import reactCSS from 'reactcss' +import { colors, css, icons } from '../helpers' + +export const Icon = (props) => { + const styles = reactCSS({ + 'default': { + icon: { + width: 24, + height: 24, + }, + }, + 'small': { + icon: { + width: 20, + height: 20, + }, + }, + 'large': { + icon: { + width: 48, + height: 48, + }, + }, + 'clickable': { + icon: { + cursor: 'pointer', + }, + }, + ...css.build('icon', 'color', _.mapKeys(colors, (v, k) => (`color-${ k }`))), + }, props, props.style, { + 'clickable': !!props.onClick, + 'large': props.size === 'large', + }) + + return ( + + { icons.find(props.name || (props.style && props.style.name)) } + + ) +} + +export default Icon diff --git a/packages/lightning-components/Icon/story.js b/packages/lightning-components/Icon/story.js new file mode 100644 index 000000000..29347a2e5 --- /dev/null +++ b/packages/lightning-components/Icon/story.js @@ -0,0 +1,21 @@ +import React from 'react' +import { storiesOf } from '@kadira/storybook' + +import Icon from './' + +storiesOf('Icon', module) + .add('`swap-horizontal` icon', () => ( + + )) + .add('`chart-bubble` icon', () => ( + + )) + .add('`n/a` icon', () => ( + + )) + .add('small icon', () => ( + + )) + .add('`teal` icon', () => ( + + )) diff --git a/packages/lightning-components/Input/index.js b/packages/lightning-components/Input/index.js index 317d81854..7d160b12f 100644 --- a/packages/lightning-components/Input/index.js +++ b/packages/lightning-components/Input/index.js @@ -34,7 +34,7 @@ export const Input = ({ style, large, onEnter, onKeyDown, value, placeholder, const handleKeyDown = (e) => { const ENTER = 13 if (e.keyCode === ENTER) { - onEnter && onEnter() + onEnter && onEnter(e) } onKeyDown && onKeyDown(e) } diff --git a/packages/lightning-components/LinkWithIcon/index.js b/packages/lightning-components/LinkWithIcon/index.js index 55f3ec90d..8216b8d27 100644 --- a/packages/lightning-components/LinkWithIcon/index.js +++ b/packages/lightning-components/LinkWithIcon/index.js @@ -31,7 +31,7 @@ export const LinkWithIcon = ({ onClick, label, icon, paddingBottom, color }) => } LinkWithIcon.defaultProps = { - color: 'teal', + color: 'blue', } export default LinkWithIcon diff --git a/packages/lightning-components/Popup/index.js b/packages/lightning-components/Popup/index.js new file mode 100644 index 000000000..29879dd28 --- /dev/null +++ b/packages/lightning-components/Popup/index.js @@ -0,0 +1,40 @@ +import React from 'react' +import reactCSS from 'reactcss' + +export const Popup = ({ children, visible, onClose }) => { + const styles = reactCSS({ + 'default': { + wrap: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + }, + cover: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + background: 'rgba(39, 36, 41, 0.4)', + }, + box: { + position: 'absolute', + left: '50%', + top: '50%', + transform: 'translate(-50%, -50%)', + }, + }, + }) + return visible ? ( +
+
+
+ { children } +
+
+ ) : null +} + +export default Popup diff --git a/packages/lightning-components/QRCode/index.js b/packages/lightning-components/QRCode/index.js new file mode 100644 index 000000000..a54b29e33 --- /dev/null +++ b/packages/lightning-components/QRCode/index.js @@ -0,0 +1,27 @@ +import React from 'react' +import { format } from 'url' +import qrImage from 'qr-image' + +export const QRCode = { + bitcoin: ({ address }) => { + const bitcoinURL = format({ protocol: 'bitcoin:', host: address }) + const svg = qrImage.svgObject(bitcoinURL, { type: 'svg' }) + + return ( + + + + ) + }, + lightning: ({ paymentRequest }) => { + const svg = qrImage.svgObject(paymentRequest, { type: 'svg' }) + + return ( + + + + ) + } +} + +export default QRCode diff --git a/packages/lightning-components/Select/index.js b/packages/lightning-components/Select/index.js index 9d2046fb7..6192b2a8f 100644 --- a/packages/lightning-components/Select/index.js +++ b/packages/lightning-components/Select/index.js @@ -27,6 +27,12 @@ export const Media = (props) => { color: '#777', }, }, + 'bare': { + select: { + boxShadow: 'none', + padding: 0, + }, + }, ...css.build('media', 'color', colors), }, props) diff --git a/packages/lightning-components/SidebarItem/index.js b/packages/lightning-components/SidebarItem/index.js index 6ff0e3d24..a1ccfb1f9 100644 --- a/packages/lightning-components/SidebarItem/index.js +++ b/packages/lightning-components/SidebarItem/index.js @@ -25,7 +25,7 @@ export const SidebarItem = ({ color, hoverColor, hover, active, ellipsis, }, 'active': { item: { - color: 'teal', + color: 'blue', }, }, 'ellipsis': { diff --git a/packages/lightning-components/Tab/index.js b/packages/lightning-components/Tab/index.js index e56c7bb67..c85361a5d 100644 --- a/packages/lightning-components/Tab/index.js +++ b/packages/lightning-components/Tab/index.js @@ -1,7 +1,7 @@ import React from 'react' import reactCSS, { hover as h } from 'reactcss' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import { Box, Text } from '../' diff --git a/packages/lightning-components/Tabs/story.js b/packages/lightning-components/Tabs/story.js index 97746ad09..09afab92c 100644 --- a/packages/lightning-components/Tabs/story.js +++ b/packages/lightning-components/Tabs/story.js @@ -20,5 +20,5 @@ const tabs = [ storiesOf('Tabs', module) .add('tabs', () => ( - + )) diff --git a/packages/lightning-components/helpers/colors.js b/packages/lightning-components/helpers/colors.js index d59b46c55..5197b0ee5 100644 --- a/packages/lightning-components/helpers/colors.js +++ b/packages/lightning-components/helpers/colors.js @@ -1,6 +1,5 @@ - export default { - 'teal': '#59D9A4', + 'blue': '#4990E2', 'dark-teal': '#93B9A9', 'dark-purple': '#272429', 'orange': '#F5A623', diff --git a/packages/lightning-components/helpers/fonts.js b/packages/lightning-components/helpers/fonts.js index 3c13d5f55..40f9c5eb0 100644 --- a/packages/lightning-components/helpers/fonts.js +++ b/packages/lightning-components/helpers/fonts.js @@ -1,4 +1,3 @@ - export default { fontFamily: '"Roboto", "Helvetica", sans-serif', sizes: { diff --git a/packages/lightning-components/helpers/icons.js b/packages/lightning-components/helpers/icons.js index ac9a112b6..a67ab0c88 100644 --- a/packages/lightning-components/helpers/icons.js +++ b/packages/lightning-components/helpers/icons.js @@ -1,4 +1,3 @@ -/* eslint import/prefer-default-export: 0 */ import React from 'react' const icons = { @@ -6,12 +5,16 @@ const icons = { 'arrow-right': , 'arrow-right-bold-circle-outline': , 'chart-bubble': , + 'close': , 'coin': , 'coins': , + 'currency-btc': , 'dots-vertical': , 'flash': , 'history': , 'magnify': , + 'playlist-remove': , + 'qrcode': , 'radiobox-blank': , 'radiobox-marked': , 'settings': , diff --git a/packages/lightning-components/helpers/spacing.js b/packages/lightning-components/helpers/spacing.js index a5f908fc4..30baaa7ad 100644 --- a/packages/lightning-components/helpers/spacing.js +++ b/packages/lightning-components/helpers/spacing.js @@ -1,4 +1,3 @@ - export default { none: 0, xs: 2, diff --git a/packages/lightning-components/index.js b/packages/lightning-components/index.js index c855aa06e..db8c03db1 100644 --- a/packages/lightning-components/index.js +++ b/packages/lightning-components/index.js @@ -3,6 +3,8 @@ export { default as Icon } from './Icon' export { default as Input } from './Input' export { default as LinkWithIcon } from './LinkWithIcon' export { default as Media } from './Media' +export { default as Popup } from './Popup' +export { default as QRCode } from './QRCode' export { default as Select } from './Select' export { default as Tab } from './Tab' export { default as Text } from './Text' diff --git a/packages/lightning-components/package.json b/packages/lightning-components/package.json index 270b905cb..4feb5da9a 100644 --- a/packages/lightning-components/package.json +++ b/packages/lightning-components/package.json @@ -1,6 +1,6 @@ { "name": "lightning-components", - "version": "0.1.0", + "version": "0.1.1", "description": "", "main": "index.js", "scripts": { @@ -10,8 +10,12 @@ "license": "MIT", "dependencies": { "lodash": "^4.16.1", + "qr-image": "^3.1.0", "react": "^15.3.2", - "react-router": "^4.0.0-alpha.5", + "react-router-dom": "^4.0.0", "reactcss": "^1.0.8" + }, + "devDependencies": { + "@kadira/storybook": "^2.35.3" } } diff --git a/packages/lightning-core/accounts/ChannelList.js b/packages/lightning-core/accounts/ChannelList.js new file mode 100644 index 000000000..876b6be11 --- /dev/null +++ b/packages/lightning-core/accounts/ChannelList.js @@ -0,0 +1,57 @@ +import React from 'react' +import _ from 'lodash' +import reactCSS from 'reactcss' + +import { Icon } from 'lightning-components' +import { LoadingIcon } from '../common' +import ChannelListItem from './ChannelListItem' + +export const ChannelList = ({ channels, loading }) => { + const styles = reactCSS({ + 'default': { + list: { + borderTop: '1px solid #ddd', + display: 'flex', + flexDirection: 'column', + flex: 1, + }, + empty: { + display: 'flex', + flexDirection: 'column', + flex: 1, + alignItems: 'center', + justifyContent: 'center', + color: '#bbb', + userSelect: 'none', + cursor: 'default', + }, + emptyLabel: { + fontSize: 24, + paddingTop: 10, + }, + }, + }) + + return ( +
+ { _.map(channels, (channel, i) => ( + + )) } + + { loading ? ( +
+ +
+ ) : null } + + { !channels.length && !loading ? ( +
+ +
No Channels Yet
+
+ ) : null } +
+ ) +} + +export default ChannelList diff --git a/packages/lightning-core/accounts/ChannelListItem.js b/packages/lightning-core/accounts/ChannelListItem.js new file mode 100644 index 000000000..4365fd531 --- /dev/null +++ b/packages/lightning-core/accounts/ChannelListItem.js @@ -0,0 +1,186 @@ +import React from 'react' +import reactCSS, { handleHover } from 'reactcss' +import { remote } from 'electron' +import { connect } from 'react-redux' +import { actions as notificationActions } from 'lightning-notifications' +import { actions as accountsActions } from '../accounts' +import { Box, Icon } from 'lightning-components' +import { Popup, actions as popupActions } from 'lightning-popup' +import { actions } from './reducer' +import { Prompt } from '../common' +import { Money, MoneySign } from '../common' +import { withRouter } from 'react-router' +import { store } from 'lightning-store' + +const { Menu, MenuItem } = remote + +export const ChannelListItem = ({ id, capacity, currency, localBalance, remoteBalance, + active, status, hover, channelPoint, onShowPopup, onClosePopup, onCloseChannel, + onSuccess, onFetchChannels }) => { + const pending = status === 'pending-open' + || status === 'pending-closing' + || status === 'pending-force-closing' + + const styles = reactCSS({ + 'default': { + channel: { + borderBottom: '1px solid #ddd', + paddingTop: 20, + paddingBottom: 20, + }, + split: { + display: 'flex', + justifyContent: 'space-between', + marginBottom: 7, + }, + id: { + color: '#333', + fontSize: 20, + display: 'flex', + }, + closeLabel: { + color: '#ce5c6a', + marginLeft: 10, + display: 'none', + height: 20, + cursor: 'pointer', + }, + active: { + color: '#4990e2', + marginRight: 10, + }, + status: { + fontSize: 13, + textTransform: 'uppercase', + color: '#999', + }, + local: { + fontSize: 16, + color: '#4990E2', + }, + remote: { + fontSize: 16, + color: '#666', + }, + bar: { + borderRadius: 2, + background: 'lighter-gray', + marginTop: 10, + }, + percent: { + background: 'blue', + height: 12, + borderRadius: 2, + }, + }, + 'hover': { + closeLabel: { + display: 'inline-block', + }, + }, + 'pending': { + id: { + color: '#999', + }, + local: { + color: '#999', + }, + remote: { + color: '#999', + }, + percent: { + background: 'light-gray', + }, + }, + }, { hover, pending }) + + const PROMPT = `CHANNEL_LIST/PROMPT-${ channelPoint }` + + // eslint-disable-next-line + const close = ({ channelPoint, force }) => { + const call = onCloseChannel({ channelPoint, force }) + call.on('data', () => { + onSuccess('Channel Closed') + onFetchChannels() + }) + call.on('error', err => onSuccess(err.message)) + } + + const showPopupOrClose = () => + (active ? close({ channelPoint }) : onShowPopup(PROMPT)) + const menu = new Menu() + menu.append(new MenuItem({ label: 'Close Channel', click() { showPopupOrClose() } })) + const handleMenu = () => menu.popup(remote.getCurrentWindow()) + const handleClose = () => { + close({ channelPoint, force: true }) + onClosePopup(PROMPT) + } + const handleCancel = () => onClosePopup(PROMPT) + + const width = `${ (localBalance / capacity) * 100 }%` + const title = { + 'open': `CID: ${ id }`, + 'pending-open': 'OPENING', + 'pending-closing': 'CLOSING', + 'pending-force-closing': 'CLOSING', + }[status] + + return ( +
+
+
+ { title } + { !pending && ( +
+ +
+ ) } +
+
+ { active ? ( + active + ) : null } + { status } +
+
+ +
+
My Balance:
+
Available to Receive:
+
+ + + + + + + + +
+ ) +} + +export default connect( + state => ({ + serverRunning: store.getServerRunning(state), + isSynced: store.getSyncedToChain(state), + pubkey: store.getAccountPubkey(state), + currency: store.getCurrency(state), + balances: store.getAccountBalances(state), + }), { + onShowPopup: popupActions.onOpen, + onClosePopup: popupActions.onClose, + onCloseChannel: actions.startCloseChannel, + onSuccess: notificationActions.addNotification, + onFetchChannels: accountsActions.fetchChannels, + onfetchAccount: accountsActions.fetchAccount, + onfetchBalances: accountsActions.fetchBalances, + }, +)(handleHover(ChannelListItem)) diff --git a/packages/lightning-core/accounts/CreateChannelPage.js b/packages/lightning-core/accounts/CreateChannelPage.js new file mode 100644 index 000000000..817927694 --- /dev/null +++ b/packages/lightning-core/accounts/CreateChannelPage.js @@ -0,0 +1,64 @@ +import React from 'react' +import { connect } from 'react-redux' +import { Form } from 'lightning-forms' +import { actions } from './reducer' +import { remote } from 'electron' +import { CurrencyInput, Head, Input, Page } from '../common' + +const { Menu, MenuItem } = remote + +export const CreateChannelPage = ({ createChannel, push }) => { + const fields = [ + { + name: 'ip', + placeholder: 'Pubkey@HostIP', + required: true, + component: Input, + }, + { + name: 'amount', + placeholder: 'Amount', + required: true, + component: CurrencyInput, + }, + ] + + const menu = new Menu() + menu.append(new MenuItem({ label: 'Paste', role: 'paste' })) + const handleMenu = () => menu.popup(remote.getCurrentWindow()) + + const handleSuccess = ({ ip, amount }, clear) => { + createChannel({ ip, amount }) + .then(() => { + clear() + push('/accounts') + }) + // eslint-disable-next-line no-console + .catch(console.error) + } + + return ( + + +
+
+
+
+ ) +} + +export default connect( + () => ({}), { + createChannel: actions.createChannel, + push: actions.push, + }, +)(CreateChannelPage) diff --git a/packages/lightning-core/accounts/Wallet.js b/packages/lightning-core/accounts/Wallet.js new file mode 100644 index 000000000..bdcd204fe --- /dev/null +++ b/packages/lightning-core/accounts/Wallet.js @@ -0,0 +1,126 @@ +import React from 'react' +import _ from 'lodash' +import reactCSS from 'reactcss' +import { connect } from 'react-redux' +import { withRouter } from 'react-router' +import { actions as accountActions } from '../accounts' +import { store } from 'lightning-store' +import { Money, MoneySign } from '../common' +import { total } from '../helpers' +import { Text } from 'lightning-components' + +export const Wallet = ({ pubkey, currency, balances }) => { + const styles = reactCSS({ + 'default': { + bg: { + background: '#4990E2', + color: '#fff', + padding: 30, + paddingBottom: 20, + }, + title: { + color: 'rgba(0,0,0,0.4)', + fontSize: 24, + userSelect: 'none', + cursor: 'default', + }, + details: { + display: 'flex', + justifyContent: 'space-between', + alignItems: 'flex-end', + }, + total: { + + }, + amount: { + fontSize: 32, + marginBottom: 10, + }, + address: { + fontSize: 16, + color: 'rgba(0,0,0,0.4)', + minWidth: 300, + wordBreak: 'break-word', + marginRight: 20, + marginBottom: 10, + }, + breakdown: { + fontSize: 16, + }, + item: { + display: 'flex', + marginBottom: 10, + }, + label: { + color: 'rgba(0,0,0,0.4)', + whiteSpace: 'nowrap', + marginRight: 10, + width: 90, + userSelect: 'none', + cursor: 'default', + }, + count: { + flex: 1, + color: 'reba(255,255,255,0.9)', + whiteSpace: 'nowrap', + }, + }, + }) + + const breakdown = [ + { + label: 'On Chain', + amount: balances.wallet, + }, { + label: 'In Channels', + amount: balances.channel, + }, + ] + + if (balances.limbo) { + breakdown.push({ + label: 'In Limbo', + amount: balances.limbo, + }) + } + + return ( +
+
Your Wallet
+
+
+
+ +
+
Pubkey: { pubkey }
+
+
+ + { _.map(breakdown, (item, i) => ( +
+
+ { item.label } +
+
+ +
+
+ )) } + +
+
+
+ ) +} +export default withRouter(connect( + state => ({ + serverRunning: store.getServerRunning(state), + isSynced: store.getSyncedToChain(state), + pubkey: store.getAccountPubkey(state), + currency: store.getCurrency(state), + balances: store.getAccountBalances(state), + }), { + fetchAccount: accountActions.fetchAccount, + fetchBalances: accountActions.fetchBalances, + }, +)(Wallet)) diff --git a/packages/lightning-core/accounts/index.js b/packages/lightning-core/accounts/index.js new file mode 100644 index 000000000..2a4a583d5 --- /dev/null +++ b/packages/lightning-core/accounts/index.js @@ -0,0 +1,73 @@ +import React from 'react' +import reactCSS from 'reactcss' +import { connect } from 'react-redux' +import { store } from 'lightning-store' +import { Link } from 'react-router-dom' +import { actions } from './reducer' + +import { Head, Page } from '../common' +import Wallet from './Wallet' +import ChannelList from './ChannelList' + +export class Accounts extends React.Component { + componentDidMount() { + this.props.fetchBalances() + this.props.onMount() + } + + render() { + const { pubkey, balances, channels, loading } = this.props + const styles = reactCSS({ + default: { + page: { + display: 'flex', + flexDirection: 'column', + flex: 1, + }, + link: { + fontSize: 12, + textTransform: 'uppercase', + textDecoration: 'none', + color: '#4990E2', + }, + }, + }) + const createChannel = ( + Create Channel + ) + return ( +
+ + + + + +
+ ) + } +} + +export default connect( + state => ({ + channels: store.getChannels(state), + loading: store.getChannelsLoading(state), + balances: store.getAccountBalances(state), + pubkey: store.getAccountPubkey(state), + }), { + onMount: actions.fetchChannels, + fetchBalances: actions.fetchBalances, + }, +)(Accounts) + +export { default as reducer, actions, selectors } from './reducer' +export { default as CreateChannelPage } from './CreateChannelPage' diff --git a/packages/lightning-core/accounts/reducer.js b/packages/lightning-core/accounts/reducer.js new file mode 100644 index 000000000..0a5cc8364 --- /dev/null +++ b/packages/lightning-core/accounts/reducer.js @@ -0,0 +1,273 @@ +import _ from 'lodash' +import { GRPC, SERVER_RUNNING } from 'redux-grpc-middleware' +import { actions as notificationActions } from 'lightning-notifications' + +export const FETCH_ACCOUNT = 'ACCOUNTS/FETCH_ACCOUNT' +export const FETCH_BALANCES = 'ACCOUNTS/FETCH_BALANCES' +export const SET_BALANCES = 'ACCOUNTS/SET_BALANCES' +export const REQUEST_CHANNELS = 'ACCOUNTS/REQUEST_CHANNELS' +export const FETCH_CHANNELS = 'ACCOUNTS/FETCH_CHANNELS' +export const FETCH_CHANNELS_FAILURE = 'ACCOUNTS/FETCH_CHANNELS_FAILURE' +export const LIST_PEERS = 'ACCOUNTS/LIST_PEERS' +export const OPEN_CHANNEL = 'ACCOUNTS/OPEN_CHANNEL' +export const CONNECT_PEER = 'ACCOUNTS/CONNECT_PEER' +export const START_CLOSING_CHANNEL = 'ACCOUNTS/START_CLOSING_CHANNEL' +export const CLOSE_CHANNEL = 'ACCOUNTS/CLOSE_CHANNEL' +export const PENDING_CHANNELS = 'ACCOUNTS/PENDING_CHANNELS' +export const FETCH_ACCOUNT_FAILURE = 'ACCOUNTS/FETCH_ACCOUNT_ERROR' + +const initialState = { + pubkey: '', + isSynced: true, + serverRunning: false, + currency: 'satoshi', + balances: { + wallet: 0, + channel: 0, + }, + channels: [], + pendingChannels: [], + loadingChannels: false, +} + +export default (state = initialState, action) => { + switch (action.type) { + case SERVER_RUNNING: + return { ...state, serverRunning: true } + case REQUEST_CHANNELS: + return { ...state, loadingChannels: true } + case FETCH_ACCOUNT: + return { ...state, pubkey: action.pubkey, isSynced: action.isSynced } + case FETCH_ACCOUNT_FAILURE: + return { ...state, isSynced: false } + case SET_BALANCES: + return { ...state, balances: { ...state.balances, ...action.balances } } + case PENDING_CHANNELS: + return { + ...state, + pendingChannels: action.pendingChannels, + balances: { + ...state.balances, + limbo: action.limboBalance, + }, + loadingChannels: false, + } + case FETCH_CHANNELS: + return { + ...state, + channels: action.channels, + loadingChannels: false, + } + case START_CLOSING_CHANNEL: + return { + ...state, + channels: _.map(state.channels, (c) => { + if (c.channelPoint === action.channelPoint) { + return { + ...c, + status: 'closing', + } + } + return c + }), + } + case FETCH_CHANNELS_FAILURE: + return { ...state, channels: [], loadingChannels: false } + default: return state + } +} + +export const actions = { + fetchAccount: () => ({ + [GRPC]: { + method: 'getInfo', + types: [null, FETCH_ACCOUNT, FETCH_ACCOUNT_FAILURE], + schema: account => ({ + pubkey: account.identity_pubkey, + isSynced: account.synced_to_chain, + }), + }, + }), + fetchBalances: () => (dispatch) => { + Promise.all([ + dispatch({ + [GRPC]: { + method: 'walletBalance', + schema: wallet => ({ + wallet: parseInt(wallet.balance, 10), // To SAT, + }), + }, + }), + dispatch({ + [GRPC]: { + method: 'channelBalance', + schema: channel => ({ + channel: parseInt(channel.balance, 10), + }), + }, + }), + ]) + .then((results) => { + const account = _.reduce(results, _.extend) + dispatch({ + type: SET_BALANCES, + balances: { + wallet: account.wallet, + channel: account.channel, + }, + }) + }) + // eslint-disable-next-line no-console + .catch(console.error) + }, + pendingChannels: () => ({ + [GRPC]: { + method: 'pendingChannels', + types: [null, PENDING_CHANNELS, FETCH_CHANNELS_FAILURE], + schema: (data) => { + const decorateChannels = (channels, transform) => + _.map(channels, channel => ({ + remotePubkey: channel.remote_node_pub, + capacity: channel.capacity, + localBalance: channel.local_balance, + remoteBalance: channel.remote_balance, + channelPoint: channel.channel_point, + ...transform(channel), + })) + + return { + pendingChannels: [ + ...decorateChannels(data.pending_open_channels, () => ({ status: 'pending-open' })), + ...decorateChannels(data.pending_closing_channels, () => ({ status: 'pending-closing' })), + ...decorateChannels(data.pending_force_closing_channels, () => ({ status: 'pending-force-closing' })), + ], + limboBalance: parseInt(data.total_limbo_balance, 0), + } + }, + }, + }), + listChannels: () => ({ + [GRPC]: { + method: 'listChannels', + types: [REQUEST_CHANNELS, FETCH_CHANNELS, FETCH_CHANNELS_FAILURE], + schema: data => ({ + channels: _.map(data.channels, channel => ({ + remotePubkey: channel.remote_pubkey, + id: channel.chan_id, + capacity: channel.capacity, + localBalance: channel.local_balance, + remoteBalance: channel.remote_balance, + channelPoint: channel.channel_point, + active: channel.active, + status: 'open', + })), + }), + }, + }), + fetchChannels: () => (dispatch) => { + dispatch(actions.listChannels()) + dispatch(actions.pendingChannels()) + }, + listPeers: () => ({ + [GRPC]: { + method: 'listPeers', + types: LIST_PEERS, + schema: list => ({ + peers: list.peers || {}, + }), + }, + }), + openChannel: ({ pubkey, amount }) => ({ + [GRPC]: { + method: 'openChannel', + types: OPEN_CHANNEL, + params: { + node_pubkey: new Buffer(pubkey, 'hex'), + local_funding_amount: amount, + num_confs: 1, + }, + stream: true, + }, + }), + connectPeer: ({ host, pubkey }) => ({ + [GRPC]: { + method: 'connectPeer', + body: { + addr: { host, pubkey }, + }, + types: CONNECT_PEER, + }, + }), + createChannel: ({ ip, amount }) => (dispatch) => { + return new Promise((resolve, reject) => { + const [pubkey, host] = ip && ip.split('@') + + const rejectError = (err) => { + dispatch(notificationActions.addNotification(err.message)) + reject(err.message) + } + + const handleResolve = () => { + dispatch(notificationActions.addNotification('Opening Channel')) + resolve() + } + + dispatch(actions.listPeers()) + .then(({ peers }) => { + const peer = _.find(peers, { pub_key: pubkey }) + + if (peer) { + const call = dispatch(actions.openChannel({ pubkey, amount })) + call.on('data', handleResolve) + call.on('error', rejectError) + } else { + dispatch(actions.connectPeer({ host, pubkey })) + .then(() => { + const call = dispatch(actions.openChannel({ pubkey, amount })) + call.on('data', handleResolve) + call.on('error', rejectError) + }) + .catch(rejectError) + } + }) + .catch(rejectError) + }) + }, + startCloseChannel: params => (dispatch) => { + dispatch({ type: START_CLOSING_CHANNEL, channelPoint: params.channelPoint }) + return dispatch(actions.closeChannel(params)) + }, + closeChannel: ({ channelPoint, force = false }) => { + const txid = channelPoint.split(':')[0] + const index = channelPoint.split(':')[1] + return { + [GRPC]: { + method: 'closeChannel', + types: CLOSE_CHANNEL, + params: { + channel_point: { + funding_txid: new Buffer(txid, 'hex').reverse(), + output_index: parseInt(index, 10), + }, + force, + }, + stream: true, + }, + } + }, + push: (...args) => + ({ type: '@@router/CALL_HISTORY_METHOD', payload: { method: 'push', args } }), +} + +export const selectors = { + getSyncedToChain: state => state.isSynced, + getServerRunning: state => state.serverRunning, + getAccountPubkey: state => state.pubkey, + getCurrency: state => state.currency, + getAccountBalances: state => state.balances, + getChannels: (state) => { + const channels = [...state.channels, ...state.pendingChannels] + return channels.length ? channels : [] + }, + getChannelsLoading: state => state.loadingChannels, +} diff --git a/packages/lightning-core/common/CurrencyInput.js b/packages/lightning-core/common/CurrencyInput.js new file mode 100644 index 000000000..90271991b --- /dev/null +++ b/packages/lightning-core/common/CurrencyInput.js @@ -0,0 +1,36 @@ +import React from 'react' +import reactCSS from 'reactcss' + +import Input from './Input' +import { enforceNumbers } from '../helpers/currencies' + +export const CurrencyInput = (props) => { + const styles = reactCSS({ + 'default': { + changer: { + marginTop: 10, + marginBottom: 10, + borderLeft: '1px solid #ddd', + paddingLeft: 15, + paddingRight: 15, + display: 'flex', + alignItems: 'center', + color: '#999', + }, + }, + }) + + const changer = ( +
SAT
+ ) + + return ( + + ) +} + +export default CurrencyInput diff --git a/packages/lightning-core/common/Head.js b/packages/lightning-core/common/Head.js new file mode 100644 index 000000000..a0b337a0a --- /dev/null +++ b/packages/lightning-core/common/Head.js @@ -0,0 +1,40 @@ +import React from 'react' +import reactCSS from 'reactcss' + +export const Head = ({ title, body, right }) => { + const styles = reactCSS({ + 'default': { + head: { + paddingBottom: 30, + paddingRight: 30, + userSelect: 'none', + cursor: 'default', + }, + title: { + fontSize: 24, + color: '#666', + paddingBottom: 10, + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', + }, + body: { + fontSize: 16, + lineHeight: '21px', + color: '#999', + }, + }, + }) + + return ( +
+
+ { title } + { right } +
+
{ body }
+
+ ) +} + +export default Head diff --git a/packages/lightning-core/common/InfiniteScroll.js b/packages/lightning-core/common/InfiniteScroll.js new file mode 100644 index 000000000..7de302639 --- /dev/null +++ b/packages/lightning-core/common/InfiniteScroll.js @@ -0,0 +1,52 @@ +import React from 'react' +import reactCSS from 'reactcss' + +import Infinite from 'react-infinite' + +export class InfiniteScroll extends React.Component { + state = { + height: 300, + } + + componentDidMount() { + // eslint-disable-next-line react/no-did-mount-set-state + this.setState({ height: this.outside.offsetHeight - 30 }) + } + + componentWillReceiveProps() { + this.setState({ height: this.outside.offsetHeight - 30 }) + } + + render() { + const { children, startAtBottom, insideStyles, elementHeight } = this.props + + const styles = reactCSS({ + default: { + wrap: { + flex: 1, + }, + }, + }) + + return ( +
(this.outside = wrap) }> + + { children } + +
+ ) + } +} + +InfiniteScroll.defaultProps = { + startAtBottom: false, + insideStyles: {}, + elementHeight: 15, +} diff --git a/packages/lightning-core/common/Input.js b/packages/lightning-core/common/Input.js new file mode 100644 index 000000000..a672e7b27 --- /dev/null +++ b/packages/lightning-core/common/Input.js @@ -0,0 +1,93 @@ +import React from 'react' +import reactCSS from 'reactcss' + +export class Input extends React.Component { + state = { + focused: false, + } + + handleFocus = () => this.setState({ focused: true }) + handleBlur = () => this.setState({ focused: false }) + handleClick = () => { + const { selectOnClick, copyOnClick, onCopy, onClick } = this.props + if (copyOnClick) { + this.input.select() + + try { + const wasCopied = document.execCommand('copy') + wasCopied && onCopy && onCopy() + } catch (error) { + // eslint-disable-next-line no-console + console.log('Error Copying to Clipboard:', error) + } + } + selectOnClick && this.input.select() + onClick && onClick() + } + + render() { + const { name, right, left, type, placeholder, value, sanitizeReturn, + onChange, outlineColor, fullWidth, disabled } = this.props + const styles = reactCSS({ + 'default': { + bg: { + backgroundColor: '#fff', + boxShadow: `0 0 2px ${ outlineColor }, 0 2px 4px ${ outlineColor }`, + borderRadius: 2, + height: 54, + display: 'flex', + alignItems: 'stretch', + maxWidth: fullWidth ? null : 350, + fontSize: 16, + flex: 1, + + transition: 'box-shadow 100ms ease-out', + }, + input: { + background: 'none', + flex: 1, + border: 'none', + outline: 'none', + fontSize: 16, + paddingLeft: 20, + color: '#333', + }, + }, + 'focused': { + bg: { + boxShadow: '0 0 2px rgba(0,0,0,0.2), 0 4px 8px rgba(0,0,0,0.2)', + }, + }, + }, { focused: this.state.focused }) + + const handleChange = ({ target }) => onChange({ + [target.name]: sanitizeReturn ? sanitizeReturn(target.value) : target.value, + }) + + return ( +
+ { left || null } + (this.input = input) } + name={ name } + type={ type } + placeholder={ placeholder } + value={ value } + disabled={ disabled } + onChange={ handleChange } + onKeyPress= { this.props.onKeyPress } + onFocus={ this.handleFocus } + onBlur={ this.handleBlur } + /> + { right || null } +
+ ) + } +} + +Input.defaultProps = { + outlineColor: 'rgba(0, 0, 0, 0.12)', +} + +export default Input diff --git a/packages/lightning-core/common/LoadingIcon.js b/packages/lightning-core/common/LoadingIcon.js new file mode 100644 index 000000000..b77bf52b2 --- /dev/null +++ b/packages/lightning-core/common/LoadingIcon.js @@ -0,0 +1,21 @@ +import React from 'react' + +export const LoadingIcon = () => { + return ( +
+ + + + + +
+ ) +} diff --git a/packages/lightning-core/common/Money.js b/packages/lightning-core/common/Money.js new file mode 100644 index 000000000..7ae236a39 --- /dev/null +++ b/packages/lightning-core/common/Money.js @@ -0,0 +1,26 @@ +import React from 'react' + +import { currencies } from '../helpers' + +export const Money = ({ currency, amount, sign }) => { + const money = currencies.find(currency) + + return ( + + { sign ? `${ money.sign } ` : null } + { money.format(amount) } + + ) +} + +export const MoneyCode = ({ currency }) => { + const money = currencies.find(currency) + + return { money.code } +} + +export const MoneySign = ({ currency }) => { + const money = currencies.find(currency) + + return { money.sign } +} diff --git a/packages/lightning-core/components/nav/NavFooter.js b/packages/lightning-core/common/NavFooter.js similarity index 56% rename from packages/lightning-core/components/nav/NavFooter.js rename to packages/lightning-core/common/NavFooter.js index 4a6aa3ab6..6845ee7a5 100644 --- a/packages/lightning-core/components/nav/NavFooter.js +++ b/packages/lightning-core/common/NavFooter.js @@ -2,11 +2,11 @@ import React from 'react' import { Box, Media, Text } from 'lightning-components' import NavFooterAccount from './NavFooterAccount' -import { Money, MoneySign } from '../common' +import { Money, MoneySign } from './' -import { total } from '../../helpers/wallet' +import { total } from '../helpers/wallet' -export const NavFooter = ({ currency, amount, identity, onClickAccount, account }) => { +export const NavFooter = ({ pubkey, currency, balances, onClickAccount }) => { return (
@@ -15,11 +15,14 @@ export const NavFooter = ({ currency, amount, identity, onClickAccount, account left={ } > - + - +
) } diff --git a/packages/lightning-core/components/nav/NavFooterAccount.js b/packages/lightning-core/common/NavFooterAccount.js similarity index 69% rename from packages/lightning-core/components/nav/NavFooterAccount.js rename to packages/lightning-core/common/NavFooterAccount.js index 4c88652f2..f5c74b002 100644 --- a/packages/lightning-core/components/nav/NavFooterAccount.js +++ b/packages/lightning-core/common/NavFooterAccount.js @@ -1,12 +1,12 @@ import React from 'react' import { hover as h } from 'reactcss' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import { SidebarItem } from 'lightning-components' -export const NavFooterAccount = ({ onClick, identity, hover }) => { +export const NavFooterAccount = ({ identity, hover }) => { return ( - + { +export const NavLinks = ({ onChange }) => { const links = [ { icon: 'coin', - label: 'Send / Request', - id: 'payment', + label: 'Pay', + id: 'pay', }, { - icon: 'wallet', - label: 'Your Wallets', - id: 'wallets', + icon: 'coin', + label: 'Request', + id: 'request', }, { + icon: 'wallet', + label: 'Channels', + id: 'accounts', + }, { icon: 'swap-horizontal', label: 'Transactions', id: 'transactions', - }, - { - icon: 'chart-bubble', - label: 'Channels', - id: 'channels', + }, { + icon: 'settings', + label: 'Advanced', + id: 'settings', }, ] @@ -33,7 +36,6 @@ export const NavLinks = ({ active, onChange }) => { )) } diff --git a/packages/lightning-core/components/nav/NavLinksItem.js b/packages/lightning-core/common/NavLinksItem.js similarity index 62% rename from packages/lightning-core/components/nav/NavLinksItem.js rename to packages/lightning-core/common/NavLinksItem.js index 7044648f0..dd38f08d7 100644 --- a/packages/lightning-core/components/nav/NavLinksItem.js +++ b/packages/lightning-core/common/NavLinksItem.js @@ -1,16 +1,16 @@ import React from 'react' import { hover as h } from 'reactcss' -import { Link } from 'react-router' +import { Link, withRouter } from 'react-router-dom' import { SidebarItem } from 'lightning-components' -export const NavLinksItem = ({ id, icon, label, active, hover }) => { +export const NavLinksItem = ({ id, icon, label, hover, location }) => { return ( { ) } -export default h(NavLinksItem) +export default withRouter(h(NavLinksItem)) diff --git a/packages/lightning-core/common/Page.js b/packages/lightning-core/common/Page.js new file mode 100644 index 000000000..f46e4bcd0 --- /dev/null +++ b/packages/lightning-core/common/Page.js @@ -0,0 +1,8 @@ +import React from 'react' + +export const Page = ({ children }) => +
+ { children } +
+ +export default Page diff --git a/packages/lightning-core/common/Prompt.js b/packages/lightning-core/common/Prompt.js new file mode 100644 index 000000000..3d8921c74 --- /dev/null +++ b/packages/lightning-core/common/Prompt.js @@ -0,0 +1,69 @@ +import React from 'react' +import reactCSS from 'reactcss' + +export const Prompt = ({ title, prompt, acceptLabel, cancelLabel, onAccept, + onCancel }) => { + const styles = reactCSS({ + default: { + prompt: { + background: '#fff', + borderRadius: 2, + width: 400, + padding: 20, + fontSize: 16, + lineHeight: '22px', + color: '#666', + }, + promptTitle: { + fontSize: 24, + marginBottom: 15, + color: '#333', + }, + promptActions: { + marginTop: 15, + display: 'flex', + justifyContent: 'flex-end', + }, + button: { + height: 44, + display: 'flex', + alignItems: 'center', + paddingLeft: 15, + paddingRight: 15, + borderRadius: 3, + cursor: 'pointer', + textTransform: 'uppercase', + }, + accept: { + background: '#DA7783', + marginRight: 15, + color: '#fff', + }, + cancel: { + background: '#eee', + color: '#666', + }, + }, + }) + + return ( +
+ { title ?
{ title }
: null } + { prompt } +
+
+ { acceptLabel } +
+
+ { cancelLabel } +
+
+
+ ) +} diff --git a/packages/lightning-core/common/Sidebar.js b/packages/lightning-core/common/Sidebar.js new file mode 100644 index 000000000..fd9804e93 --- /dev/null +++ b/packages/lightning-core/common/Sidebar.js @@ -0,0 +1,102 @@ +/* eslint-disable no-console, react/no-danger */ +import React from 'react' +import reactCSS from 'reactcss' +import { connect } from 'react-redux' +import { withRouter } from 'react-router' +import { store } from 'lightning-store' + +import { Box, Text } from 'lightning-components' +import { actions as accountActions } from '../accounts' +import NavLinks from './NavLinks' +import NavFooter from './NavFooter' + +export class Sidebar extends React.Component { + componentDidMount() { + this.props.fetchAccount() + .catch(console.error) + this.props.location.pathname !== '/accounts' && this.props.fetchBalances() + } + + render() { + const { navigateToSubpage, currency, pubkey, balances, isSynced, + serverRunning } = this.props + const styles = reactCSS({ + 'default': { + sidebar: { + direction: 'column', + spread: true, + flex: 1, + }, + section: { + padding: 'small', + }, + synced: { + background: 'blue', + direction: 'column', + align: 'center', + verticalAlign: 'center', + marginLeft: -7, + marginTop: 7, + marginRight: -7, + marginBottom: -7, + borderBottomLeftRadius: 4, + height: 34, + }, + syncedText: { + color: 'black', + size: 'small', + }, + }, + }) + + return ( + + + + + + { pubkey ? ( + + ) : null } + + { serverRunning && isSynced ? null : ( + + - -
-
- - - -
-
- - diff --git a/packages/lightning-electron/main.development.js b/packages/lightning-electron/main.development.js deleted file mode 100644 index 2cd479cd7..000000000 --- a/packages/lightning-electron/main.development.js +++ /dev/null @@ -1,126 +0,0 @@ -/* eslint-disable global-require, no-console */ - -import { app, BrowserWindow } from 'electron' -import windowStateKeeper from 'electron-window-state' -import _ from 'lodash' -import observe from 'observe' -import cp from 'child_process' -import ps from 'ps-node' -import './lnd' - -let mainWindow = null - -const isProcessRunning = command => new Promise((resolve, reject) => { - ps.lookup({ command }, - (err, resultList) => { - if (err) { throw new Error(err) } - resultList[0] ? resolve(resultList[0]) : reject() - } - ) -}) - -const runProcesses = (processes, logs) => { - _.map(processes, (process) => { - isProcessRunning(process.name) - .then((p) => { - console.log(`${ process.name } Already Running`, p) - }) - .catch(() => { - const prefix = `${ process.name }: ` - const instance = cp.execFile(process.name, process.args, { cwd: './bin' }, (error) => { - if (error) { logs.push(`${ error.code }: ${ error.errno }`); return } - }) - instance.stdout.on('data', data => logs.push(prefix + data)) - instance.stderr.on('data', data => logs.push(prefix + data)) - }) - }) -} - -const logBuffer = [] -const logs = observe(logBuffer) - -const processes = [ - { - name: 'lnd', - args: [ - '--btcdhost=127.0.0.1', - '--rpcuser=kek', - '--rpcpass=kek', - '--simnet', - '--debuglevel=trace', - '--debughtlc', - ], - }, { - name: 'btcd', - args: [ - '--rpcuser=kek', - '--rpcpass=kek', - '--simnet', - '--miningaddr=4NyWssGkW6Nbwj3nXrJU54U2ijHgWaKZ1N19w', - ], - }, -] - -runProcesses(processes, logs) - -const createWindow = () => { - const mainWindowState = windowStateKeeper({ - defaultWidth: 750, - defaultHeight: 500, - }) - - const { x, y, width, height } = mainWindowState - mainWindow = new BrowserWindow({ - x, - y, - width, - height, - show: false, - transparent: true, - frame: false, - title: 'Lightning', - }) - - mainWindowState.manage(mainWindow) - mainWindow.loadURL(`file://${ __dirname }/app/app.html`) - - mainWindow.webContents.on('did-finish-load', () => { - mainWindow.show() - mainWindow.focus() - - mainWindow.webContents.send('logs', logBuffer) - }) - - logs.on('change', (change) => { - const log = logBuffer[change.index] - mainWindow && mainWindow.webContents.send('log', log) - }) - - if (process.env.NODE_ENV === 'development') { - mainWindow.openDevTools() - } - - mainWindow.on('closed', () => { - mainWindow = null - }) -} - -if (process.env.NODE_ENV === 'development') { - require('electron-debug')() -} - -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') app.quit() -}) - -// if (process.platform === 'darwin') { -// const template = [ -// { -// label: app.getName(), -// }, -// ] -// const menu = Menu.buildFromTemplate(template) -// Menu.setApplicationMenu(menu) -// } - -app.on('ready', createWindow) diff --git a/packages/lightning-electron/package.js b/packages/lightning-electron/package.js deleted file mode 100644 index 039b3779a..000000000 --- a/packages/lightning-electron/package.js +++ /dev/null @@ -1,157 +0,0 @@ -/* eslint-disable no-console, consistent-return */ -/* eslint generator-star-spacing: 0 */ - -import 'babel-polyfill' -import os from 'os' -import webpack from 'webpack' -import packager from 'electron-packager' -import del from 'del' -import minimist from 'minimist' -import { exec } from 'child_process' -import cfg from './webpack.config.production' -import pkg from './package.json' - -import electronCfg from './webpack.config.electron' - - -/** - * First two values are node path and current script path - * https://nodejs.org/docs/latest/api/process.html#process_process_argv - */ -const argv = minimist(process.argv.slice(2)) - -/** - * Do not package node modules from 'devDependencies' - * and 'dependencies' that are set as external - */ -const toNodePath = name => `/node_modules/${ name }($|/)` -const devDeps = Object - .keys(pkg.devDependencies) - .map(toNodePath) - -const depsExternal = Object - .keys(pkg.dependencies) - .filter(name => !electronCfg.externals.includes(name)) - .map(toNodePath) - - -const appName = argv.name || argv.n || pkg.productName -const shouldUseAsar = argv.asar || argv.a || false -const shouldBuildAll = argv.all || false - - -const DEFAULT_OPTS = { - dir: './', - name: appName, - asar: shouldUseAsar, - ignore: [ - '^/test($|/)', - '^/release($|/)', - '^/main.development.js', - ] - .concat(devDeps) - .concat(depsExternal), -} - -const icon = argv.icon || argv.i || 'app/app' -if (icon) DEFAULT_OPTS.icon = icon - - -/** - * @desc Execute the webpack build process on given config object - * @param {Object} cfg - * @return {Promise} - */ -function build(config) { - return new Promise((resolve, reject) => { - webpack(config, (err, stats) => { - if (err) return reject(err) - resolve(stats) - }) - }) -} - -function pack(plat, arch, cb) { - // there is no darwin ia32 electron - if (plat === 'darwin' && arch === 'ia32') return - - const iconObj = { - icon: DEFAULT_OPTS.icon + (() => { - let extension = '.png' - if (plat === 'darwin') extension = '.icns' - if (plat === 'win32') extension = '.ico' - - return extension - })(), - } - - const opts = Object.assign({}, DEFAULT_OPTS, iconObj, { - 'platform': plat, - arch, - 'prune': true, - 'app-version': pkg.version || DEFAULT_OPTS.version, - 'out': `release/${ plat }-${ arch }`, - }) - - packager(opts, cb) -} - - -function log(plat, arch) { - return (err, filepath) => { - if (err) return console.error(err, filepath) - console.log(`${ plat }-${ arch } finished!`) - } -} - - -/** @desc Build, clear previous releases and pack new versions */ -async function startPack() { - console.log('start pack...') - - try { - /** - * - Build the 'Main process' and 'Renderer Process' files. - * - Clear the ./release directory - */ - await build(electronCfg) - await build(cfg) - await del('release') - - // Start the packing process - if (shouldBuildAll) { - // build for all platforms - const archs = ['ia32', 'x64'] - const platforms = ['linux', 'win32', 'darwin'] - - platforms.forEach((plat) => { - archs.forEach((arch) => { - pack(plat, arch, log(plat, arch)) - }) - }) - } else { - // build for current platform only - pack(os.platform(), os.arch(), log(os.platform(), os.arch())) - } - } catch (error) { - console.error(error) - } -} - - -const version = argv.version || argv.v -if (version) { - DEFAULT_OPTS.version = version - startPack() -} else { - // use the same version as the currently-installed electron-prebuilt - exec('npm list electron --dev', (err, stdout) => { - if (err) { - DEFAULT_OPTS.version = '1.2.0' - } else { - DEFAULT_OPTS.version = stdout.split('electron@')[1].replace(/\s/g, '') - } - - startPack() - }) -} diff --git a/packages/lightning-electron/package.json b/packages/lightning-electron/package.json deleted file mode 100644 index 2aea7e83e..000000000 --- a/packages/lightning-electron/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "lightning-electron", - "version": "0.1.0", - "description": "", - "main": "main.development.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "case ", - "license": "MIT", - "dependencies": { - "electron": "^1.4.12", - "electron-debug": "^1.1.0", - "electron-window-state": "^4.0.1", - "lodash": "^4.17.2", - "observe": "^1.3.7", - "ps-node": "^0.1.4" - } -} diff --git a/packages/lightning-forms/components/Field.js b/packages/lightning-forms/components/Field.js new file mode 100644 index 000000000..ba0bbcef7 --- /dev/null +++ b/packages/lightning-forms/components/Field.js @@ -0,0 +1,59 @@ +import React from 'react' +import reactCSS from 'reactcss' + +export const Field = ({ name, type, placeholder, value, component, onChange, + disabled, errorText, error }) => { + const styles = reactCSS({ + 'default': { + field: { + display: 'flex', + }, + error: { + display: 'flex', + alignItems: 'center', + paddingLeft: 20, + fontSize: 14, + color: 'rgba(213, 61, 80, 1)', + }, + }, + }) + + const handleChange = e => + (component ? onChange(e) : onChange({ [e.target.name]: e.target.value })) + + const Component = component || 'input' + + return ( +
+ + { errorText ?
{ errorText }
: null } +
+ ) +} + +Field.defaultProps = { + type: 'text', + value: '', +} + +Field.propTypes = { + name: React.PropTypes.string.isRequired, + type: React.PropTypes.string, + placeholder: React.PropTypes.string, + value: React.PropTypes.string, + // component: React.PropTypes.element, + // required: React.PropTypes.bool, + // requiredMessage: React.PropTypes.string, + // validate: React.PropTypes.func, +} + +export default Field diff --git a/packages/lightning-forms/components/Form.js b/packages/lightning-forms/components/Form.js new file mode 100644 index 000000000..06ca03f4b --- /dev/null +++ b/packages/lightning-forms/components/Form.js @@ -0,0 +1,158 @@ +/* eslint-disable react/forbid-prop-types */ + +import React from 'react' +import _ from 'lodash' +import reactCSS from 'reactcss' +import { connect } from 'react-redux' +import { actions, selectors } from '../reducer' + +import Field from './Field' + +const validate = fields => new Promise((resolve, reject) => { + const errors = {} + _.map(fields, (field) => { + if (field.required && field.value === '') { + errors[field.name] = { error: true, errorText: `${ field.name } is empty` } + } + }) + + const values = _.reduce(fields, (all, field) => { + // eslint-disable-next-line no-param-reassign + all[field.name] = field.value + return all + }, {}) + + _.isEmpty(errors) ? resolve(values) : reject(errors) +}) + +class Form extends React.Component { + componentDidMount() { + const { name, fields, initForm } = this.props + const data = _.reduce(fields, (all, field) => { + // eslint-disable-next-line no-param-reassign + all[field.name] = field.value || '' + return all + }, {}) + initForm(name, data) + } + + render() { + const { submitLabel, clearLabel, name, combinedFields, spacing, + onError, onSuccess, editForm, clearForm, setFormErrors, onChange } = this.props + + const wasEdited = _.some(combinedFields, 'value') + const canSubmit = _(combinedFields).filter('required').every('value') + + const styles = reactCSS({ + 'default': { + form: { + userSelect: 'none', + cursor: 'default', + }, + field: { + paddingBottom: spacing, + }, + controls: { + display: 'flex', + alignItems: 'stretch', + height: 54, + }, + button: { + display: 'flex', + alignItems: 'center', + paddingLeft: 20, + paddingRight: 20, + fontSize: 16, + }, + submit: { + backgroundColor: '#ddd', + borderRadius: 2, + color: '#fff', + + transition: 'background-color 100ms ease-out', + }, + clear: { + color: '#999', + cursor: 'pointer', + }, + }, + 'canSubmit': { + submit: { + cursor: 'pointer', + backgroundColor: '#4990E2', + boxShadow: '0 2px 4px rgba(89, 217, 164, 0.3)', + }, + }, + }, { canSubmit }) + + const handleSubmit = () => { + validate(combinedFields) + .then((values) => { + const clear = () => clearForm(name) + onSuccess(values, clear) + }) + .catch((errors) => { + setFormErrors(name, errors) + onError(errors) + }) + } + + const handleClear = () => clearForm(name) + + const handleFieldChange = (change) => { + onChange && onChange(change) + editForm(name, change) + } + + return ( +
+ + { _.map(combinedFields, field => ( +
+ +
+ ))} + +
+
+ { submitLabel } +
+ { wasEdited ? ( +
+ { clearLabel } +
+ ) : null } +
+
+ ) + } +} + +Form.defaultProps = { + submitLabel: 'Submit', + clearLabel: 'Clear', + onSuccess: () => {}, + onError: () => {}, + spacing: 20, +} + +Form.propTypes = { + name: React.PropTypes.string.isRequired, + fields: React.PropTypes.array.isRequired, +} + +export default connect( + (state, ownProps) => { + const values = selectors.getFormFields(state.forms, ownProps.name) + const errors = selectors.getFormErrors(state.forms, ownProps.name) + return { + combinedFields: _.map(ownProps.fields, (field) => { + return { ...field, ...errors[field.name], value: values[field.name] } + }), + } + }, + actions, +)(Form) diff --git a/packages/lightning-forms/index.js b/packages/lightning-forms/index.js new file mode 100644 index 000000000..b5a5b9483 --- /dev/null +++ b/packages/lightning-forms/index.js @@ -0,0 +1,3 @@ +export { default as Form } from './components/Form' + +export { reducer, actions, selectors } from './reducer' diff --git a/packages/lightning-forms/package.json b/packages/lightning-forms/package.json new file mode 100644 index 000000000..fa79b0fa7 --- /dev/null +++ b/packages/lightning-forms/package.json @@ -0,0 +1,18 @@ +{ + "name": "lightning-forms", + "version": "0.1.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT", + "dependencies": { + "lodash": "^4.16.2", + "react": "^15.4.2", + "react-redux": "^4.4.6", + "reactcss": "^1.1.1", + "redux": "^3.6.0" + } +} diff --git a/packages/lightning-forms/reducer.js b/packages/lightning-forms/reducer.js new file mode 100644 index 000000000..48f75ef40 --- /dev/null +++ b/packages/lightning-forms/reducer.js @@ -0,0 +1,43 @@ +import _ from 'lodash' + +export const INIT_FORM = 'LIGHTNING_FORMS/INIT_FORM' +export const EDIT_FORM = 'LIGHTNING_FORMS/EDIT_FORM' +export const CLEAR_FORM = 'LIGHTNING_FORMS/CLEAR_FORM' +export const SET_FORM_ERRORS = 'LIGHTNING_FORMS/SET_FORM_ERRORS' + +const formReducer = (state = {}, action) => { + switch (action.type) { + case INIT_FORM: + case EDIT_FORM: + return { ...state, fields: { ...state.fields, ...action.form.data } } + case CLEAR_FORM: + return { ...state, fields: _.mapValues(state.fields, () => ''), errors: {} } + case SET_FORM_ERRORS: + return { ...state, errors: action.errors } + default: return state + } +} + +export const reducer = (state = {}, action) => { + switch (action.type) { + case INIT_FORM: + case EDIT_FORM: + case CLEAR_FORM: + case SET_FORM_ERRORS: + return { ...state, [action.form.name]: formReducer(state[action.form.name], action) } + default: return state + } +} + +export const actions = { + initForm: (name, data) => ({ type: INIT_FORM, form: { name, data } }), + editForm: (name, data) => ({ type: EDIT_FORM, form: { name, data } }), + clearForm: name => ({ type: CLEAR_FORM, form: { name } }), + setFormErrors: (name, errors) => ({ type: SET_FORM_ERRORS, form: { name }, errors }), +} + +export const selectors = { + getForm: (state, name) => state[name] || {}, + getFormFields: (state, name) => (state[name] && state[name].fields) || {}, + getFormErrors: (state, name) => (state[name] && state[name].errors) || {}, +} diff --git a/packages/lightning-notifications/helpers.js b/packages/lightning-notifications/helpers.js new file mode 100644 index 000000000..18864983e --- /dev/null +++ b/packages/lightning-notifications/helpers.js @@ -0,0 +1,8 @@ +export const guid = () => { + const s4 = () => + Math.floor((1 + Math.random()) * 0x10000) + .toString(16) + .substring(1) + + return `${ s4() + s4() }-${ s4() }-${ s4() }-${ s4() }-${ s4() }${ s4() }${ s4() }` +} diff --git a/packages/lightning-notifications/index.js b/packages/lightning-notifications/index.js index 10a8d26e3..be0479924 100644 --- a/packages/lightning-notifications/index.js +++ b/packages/lightning-notifications/index.js @@ -1,4 +1,5 @@ import _ from 'lodash' +import { guid } from './helpers' export { default as Notifications } from './Notifications' @@ -6,15 +7,6 @@ export const ADD = 'NOTIFICATIONS/ADD' export const REMOVE = 'NOTIFICATIONS/REMOVE' export const NOTIFICATION = 'NOTIFICATIONS/NOTIFICATION' -function guid() { - function s4() { - return Math.floor((1 + Math.random()) * 0x10000) - .toString(16) - .substring(1) - } - return `${ s4() + s4() }-${ s4() }-${ s4() }-${ s4() }-${ s4() }${ s4() }${ s4() }` -} - export default function notifications(state = [], action) { const data = { [ADD]: () => { diff --git a/packages/lightning-notifications/package.json b/packages/lightning-notifications/package.json index 544a58b4f..756a395a3 100644 --- a/packages/lightning-notifications/package.json +++ b/packages/lightning-notifications/package.json @@ -1,6 +1,6 @@ { "name": "lightning-notifications", - "version": "0.1.0", + "version": "0.1.1", "description": "", "main": "index.js", "scripts": { @@ -9,11 +9,12 @@ "author": "case ", "license": "MIT", "dependencies": { - "lightning-components": "^0.1.0", - "lightning-store": "^0.1.0", + "lightning-components": "^0.1.1", + "lightning-store": "^0.1.1", "lodash": "^4.17.2", "react": "^15.4.1", - "react-redux": "^5.0.1", - "reactcss": "^1.1.1" + "react-redux": "^4.4.6", + "reactcss": "^1.1.1", + "redux": "^3.6.0" } } diff --git a/packages/lightning-popup/Popup.js b/packages/lightning-popup/Popup.js new file mode 100644 index 000000000..84bc9b98c --- /dev/null +++ b/packages/lightning-popup/Popup.js @@ -0,0 +1,51 @@ +import React from 'react' +import reactCSS from 'reactcss' +import { connect } from 'react-redux' +import { store } from 'lightning-store' +import { actions } from './reducer' + +export const Popup = ({ children, visible, onClose, name }) => { + const styles = reactCSS({ + 'default': { + wrap: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + }, + cover: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + background: 'rgba(39, 36, 41, 0.7)', + }, + box: { + position: 'absolute', + left: '50%', + top: '50%', + transform: 'translate(-50%, -50%)', + }, + }, + }) + + const handleClose = () => onClose(name) + + return visible ? ( +
+
+
+ { children } +
+
+ ) : null +} + +export default connect( + (state, ownProps) => ({ + visible: store.getPopupVisibility(state, ownProps.name), + }), + actions, +)(Popup) diff --git a/packages/lightning-popup/index.js b/packages/lightning-popup/index.js new file mode 100644 index 000000000..b269cb89d --- /dev/null +++ b/packages/lightning-popup/index.js @@ -0,0 +1,2 @@ +export { default as Popup } from './Popup' +export { reducer, actions, selectors } from './reducer' diff --git a/packages/lightning-popup/package.json b/packages/lightning-popup/package.json new file mode 100644 index 000000000..d2ee64d8a --- /dev/null +++ b/packages/lightning-popup/package.json @@ -0,0 +1,20 @@ +{ + "name": "lightning-popup", + "version": "0.1.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT", + "dependencies": { + "lightning-components": "^0.1.1", + "lightning-store": "^0.1.1", + "lodash": "^4.17.2", + "react": "^15.4.1", + "react-redux": "^4.4.6", + "reactcss": "^1.1.1", + "redux": "^3.6.0" + } +} diff --git a/packages/lightning-popup/reducer.js b/packages/lightning-popup/reducer.js new file mode 100644 index 000000000..14a641118 --- /dev/null +++ b/packages/lightning-popup/reducer.js @@ -0,0 +1,21 @@ +export const OPEN_POPUP = 'LIGHTNING_POPUP/OPEN_POPUP' +export const CLOSE_POPUP = 'LIGHTNING_POPUP/CLOSE_POPUP' + +export const reducer = (state = {}, action) => { + switch (action.type) { + case OPEN_POPUP: + return { ...state, [action.name]: true } + case CLOSE_POPUP: + return { ...state, [action.name]: false } + default: return state + } +} + +export const actions = { + onClose: name => ({ type: CLOSE_POPUP, name }), + onOpen: name => ({ type: OPEN_POPUP, name }), +} + +export const selectors = { + getPopupVisibility: (state, name) => state[name] || false, +} diff --git a/packages/lightning-store/index.js b/packages/lightning-store/index.js index 9afc3a10a..fda20939e 100644 --- a/packages/lightning-store/index.js +++ b/packages/lightning-store/index.js @@ -1,17 +1,13 @@ /* eslint-disable import/no-named-as-default-member */ import { createStore } from 'redux' -import storage from './local-storage' -import middleware from './middleware' +import middleware, { history } from './middleware' import reducers from './reducers' -const state = { ...storage.load(), transactions: [] } - -export function configureStore(initialState = state) { - const store = createStore(reducers, initialState, middleware) - storage.save(store) - - return store +export function configureStore(initialState = {}) { + return createStore(reducers, initialState, middleware) } +export { history } + export { default as store } from './selectors' diff --git a/packages/lightning-store/local-storage.js b/packages/lightning-store/local-storage.js deleted file mode 100644 index c5f92c5d2..000000000 --- a/packages/lightning-store/local-storage.js +++ /dev/null @@ -1,17 +0,0 @@ -import _ from 'lodash' - -const STATE = 'LIGHTNING_STATE' - -export const save = (store) => { - // const saveState = _.debounce(() => { - // localStorage.setItem(STATE, JSON.stringify(store.getState())) - // }, 5000) - - // store.subscribe(saveState) -} - -export const load = () => { - return JSON.parse(localStorage.getItem(STATE)) || {} -} - -export default exports diff --git a/packages/lightning-store/middleware.js b/packages/lightning-store/middleware.js index 3664bf835..6472bce8b 100644 --- a/packages/lightning-store/middleware.js +++ b/packages/lightning-store/middleware.js @@ -1,17 +1,19 @@ import { applyMiddleware } from 'redux' -import { hashHistory } from 'react-router' import { routerMiddleware } from 'react-router-redux' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import createIpc from 'redux-electron-ipc' -import createGrpc from 'redux-grpc-middlware' -import { actions as logActions } from 'lightning-core/src/reducers/lnd' +import createGrpc from 'redux-grpc-middleware' +import { actions as logActions } from 'lightning-core/settings' + +import { createHashHistory } from 'history' const ipc = createIpc(logActions) -const grpc = createGrpc({ path: './lnd' }) +const grpc = createGrpc() const logger = createLogger({ level: 'info', collapsed: true }) -const router = routerMiddleware(hashHistory) +export const history = createHashHistory() +const router = routerMiddleware(history) export default applyMiddleware( grpc, diff --git a/packages/lightning-store/package.json b/packages/lightning-store/package.json index f40811bb6..afe83717a 100644 --- a/packages/lightning-store/package.json +++ b/packages/lightning-store/package.json @@ -1,6 +1,6 @@ { "name": "lightning-store", - "version": "0.1.0", + "version": "0.1.1", "description": "", "main": "index.js", "scripts": { @@ -9,12 +9,18 @@ "author": "case ", "license": "MIT", "dependencies": { + "history": "^4.6.1", + "lightning-core": "^1.9.1", + "lightning-forms": "^0.1.0", + "lightning-notifications": "^0.1.1", + "lightning-popup": "^0.1.0", "lodash": "^4.17.2", - "react-router": "^3.0.0", - "react-router-redux": "^4.0.7", + "react": "^15.4.1", + "react-router-dom": "^4.0.0", + "react-router-redux": "^5.0.0-alpha.6", "redux": "^3.6.0", "redux-electron-ipc": "^1.1.3", - "redux-grpc-middleware": "^0.1.0", + "redux-grpc-middleware": "^0.1.1", "redux-logger": "^2.7.4", "redux-selector": "^0.1.0", "redux-thunk": "^2.1.0" diff --git a/packages/lightning-store/reducers.js b/packages/lightning-store/reducers.js index 6672e992f..fc95db77b 100644 --- a/packages/lightning-store/reducers.js +++ b/packages/lightning-store/reducers.js @@ -1,23 +1,15 @@ import { combineReducers } from 'redux' -import { routerReducer as routing } from 'react-router-redux' - -import channels from 'lightning-core/src/reducers/channels' -import lnd from 'lightning-core/src/reducers/lnd' -import payment from 'lightning-core/src/reducers/payment' -import transactions from 'lightning-core/src/reducers/transactions' -import ui from 'lightning-core/src/reducers/ui' -import wallets from 'lightning-core/src/reducers/wallets' +import { routerReducer as router } from 'react-router-redux' +import { reducer as core } from 'lightning-core' +import { reducer as forms } from 'lightning-forms' import notifications from 'lightning-notifications' +import { reducer as popup } from 'lightning-popup' export default combineReducers({ - channels, - lnd, - payment, - transactions, - ui, - wallets, - + router, + core, + forms, notifications, - routing, + popup, }) diff --git a/packages/lightning-store/selectors.js b/packages/lightning-store/selectors.js index f6dacb54e..8eb310fc0 100644 --- a/packages/lightning-store/selectors.js +++ b/packages/lightning-store/selectors.js @@ -1,21 +1,13 @@ import { scopeStateToSelectors } from 'redux-selector' -import { selectors as channels } from 'lightning-core/src/reducers/channels' -import { selectors as lnd } from 'lightning-core/src/reducers/lnd' -import { selectors as payment } from 'lightning-core/src/reducers/payment' -import { selectors as transactions } from 'lightning-core/src/reducers/transactions' -import { selectors as ui } from 'lightning-core/src/reducers/ui' -import { selectors as wallets } from 'lightning-core/src/reducers/wallets' +import { selectors as core } from 'lightning-core' +import { selectors as forms } from 'lightning-forms' import { selectors as notifications } from 'lightning-notifications' +import { selectors as popup } from 'lightning-popup' -export default { - ...scopeStateToSelectors({ - wallets, - ui, - payment, - transactions, - lnd, - channels, - notifications, - }), -} +export default scopeStateToSelectors({ + core, + forms, + notifications, + popup, +}) diff --git a/packages/lightning-webpack/package.json b/packages/lightning-webpack/package.json deleted file mode 100644 index 5d6a0c387..000000000 --- a/packages/lightning-webpack/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "lightning-webpack", - "version": "0.1.0", - "description": "", - "main": "server.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "start": "node server.js" - }, - "author": "case ", - "license": "MIT", - "dependencies": { - "babel-register": "^6.18.0", - "express": "^4.14.0", - "extract-text-webpack-plugin": "^1.0.1", - "webpack": "^1.14.0", - "webpack-dev-middleware": "^1.9.0", - "webpack-hot-middleware": "^2.13.2", - "webpack-merge": "^1.1.2", - "webpack-validator": "^2.3.0" - } -} diff --git a/packages/lightning-webpack/webpack.config.eslint.js b/packages/lightning-webpack/webpack.config.eslint.js deleted file mode 100644 index 52dadf45c..000000000 --- a/packages/lightning-webpack/webpack.config.eslint.js +++ /dev/null @@ -1,3 +0,0 @@ -require('babel-register') - -module.exports = require('./webpack.config.development') diff --git a/packages/redux-grpc-middleware/index.js b/packages/redux-grpc-middleware/index.js index 985d5c447..f47242023 100644 --- a/packages/redux-grpc-middleware/index.js +++ b/packages/redux-grpc-middleware/index.js @@ -1,38 +1,108 @@ -import electron from 'electron' +/* eslint-disable no-console */ + +import _ from 'lodash' +import { remote } from 'electron' const defaults = { - path: './main.development.js', + global: { + connection: 'connection', + metadata: 'metadata', + serverReady: 'serverReady', + }, selector: 'default', } export const GRPC = 'GRPC/API' +export const SERVER_STARTING = 'GRPC/SERVER_STARTING' +export const SERVER_RUNNING = 'GRPC/SERVER_RUNNING' export default (opts = {}) => { const options = { ...defaults, ...opts } - const client = electron.remote.require(options.path)[options.selector] + const serverReady = remote.getGlobal(options.global.serverReady) + const metadata = remote.getGlobal(options.global.metadata) + + let client + let ready = false + let serverStartingActionSent = false + let serverRunningActionSent = false + + serverReady && serverReady(() => (ready = true)) + + try { + client = remote.getGlobal(options.global.connection) + } catch (err) { + console.log('Error Connecting to GRPC Server', err) + } return () => next => (action) => { + if (!serverStartingActionSent) { + serverStartingActionSent = true + next({ type: SERVER_STARTING }) + } + + if (ready && !serverRunningActionSent) { + serverRunningActionSent = true + next({ type: SERVER_RUNNING }) + } + const call = action && action[GRPC] if (typeof call === 'undefined' || !call) { return next(action) } - const { method, types = [], body, model, passthrough = {}, stream = false } = call - const [REQUEST, SUCCESS, ERROR] = types + const { method, body } = call + const { + params = {}, + types = [], + passthrough = {}, + schema = data => data, + stream = false, + } = call + const [REQUEST, SUCCESS, ERROR] = _.isArray(types) ? types : [null, types] REQUEST && next({ type: REQUEST }) - if (stream) { return client[method](body ? { body } : {}) } + if (!ready) { + return new Promise((resolve, reject) => + reject('GRPC Call Deferred, Server Still Starting')) + } - return new Promise((resolve, reject) => { - const api = client[method](body || {}, (error, res) => { - if (error) { - ERROR && next({ type: ERROR, error }) - reject({ ...error, stream: api }) - } else { - const data = { [model || method]: res } - SUCCESS && next({ type: SUCCESS, ...data, ...passthrough }) - resolve({ ...data, stream: api, ...passthrough }) + if (stream) { + if (client[method]) { + let streamCall + try { + if (method === "sendPayment") { + streamCall = client[method](metadata, { body }) + } else { + streamCall = client[method](params, metadata) + } + } catch (err) { + console.log('Error From Stream Method', method, err) + } finally { + // eslint-disable-next-line + return streamCall } - }) + } + return { on: () => {} } + } + + const now = new Date() + const deadline = now.setSeconds(now.getSeconds() + 30) + + return new Promise((resolve, reject) => { + try { + client[method] && client[method](body, metadata, { deadline }, + (error, res) => { + if (error) { + ERROR && next({ type: ERROR, error }) + reject({ ...error }) + } else { + SUCCESS && next({ type: SUCCESS, ...schema(res), ...passthrough, noSchema: res }) + resolve({ ...schema(res), ...passthrough, noSchema: res }) + } + }) + } catch (err) { + console.log('Error From Method', method, err) + reject('Error From Method', method, err) + } }) } } diff --git a/packages/redux-grpc-middleware/package.json b/packages/redux-grpc-middleware/package.json index 99c26593d..5b7b0a4f2 100644 --- a/packages/redux-grpc-middleware/package.json +++ b/packages/redux-grpc-middleware/package.json @@ -1,6 +1,6 @@ { "name": "redux-grpc-middleware", - "version": "0.1.0", + "version": "0.1.1", "description": "", "main": "index.js", "scripts": { diff --git a/screenshot.png b/screenshot.png new file mode 100644 index 000000000..9583f8c17 Binary files /dev/null and b/screenshot.png differ