commit 3c0e27054393e72cd2afcd524a386b26aedf3dac Author: Aaron Dewes Date: Fri Oct 22 16:22:10 2021 +0100 A new beginning for the Citadel project diff --git a/.citadel b/.citadel new file mode 100644 index 0000000..e69de29 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d4fe304 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: 2020 Umbrel +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Files and data directories created by services +# that we shouldn't accidently commit + +*.dat +*.log +*.lock +*.cookie +*.pid +*.env +.backup +*.pyc +bitcoin/* +lnd/* +tor/* +db/* +statuses/* +app-data +apps +electrs +nginx +events/signals + +# Commit these empty directories +!statuses/update-status.json +!apps/.gitkeep +!db/.gitkeep +!db/citadel-seed +db/citadel-seed/* +!db/citadel-seed/.gitkeep +!events/signals/.gitkeep +!lnd/.gitkeep +!logs/.gitkeep +!tor/data/.gitkeep +!tor/run/.gitkeep +!db/.gitkeep + +!**/*.license +services/installed.json diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000..5ca01d3 --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,10 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: Citadel +Upstream-Contact: Aaron Dewes +Source: runcitadel.space + +# Sample paragraph, commented out: +# +# Files: src/* +# Copyright: $YEAR $NAME <$CONTACT> +# License: ... diff --git a/.umbrel b/.umbrel new file mode 100644 index 0000000..e69de29 diff --git a/LICENSES/AGPL-3.0-or-later.txt b/LICENSES/AGPL-3.0-or-later.txt new file mode 100644 index 0000000..0c97efd --- /dev/null +++ b/LICENSES/AGPL-3.0-or-later.txt @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..be9f146 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ + + +[![Discord Server](https://img.shields.io/badge/Community%20Chat-Discord-%235351FB)](https://discord.gg/6U3kM2cjdB) +[![Twitter](https://img.shields.io/twitter/follow/runcitadel?style=social)](https://twitter.com/runcitadel) + +# 🏰 Citadel Core + +Citadel Core contains simple, minimalistic host system components for running a Citadel server. +It uses docker and docker-compose to orchestrate containers for the core system and apps. + +This repository also contains `karen`, a background daemon responsible for communication between Citadel docker containers and the Citadel Core. + +Citadel Core is a fully FLOSS project which replaces the previous `compose` and `compose-nonfree` repositories. diff --git a/app-standard-v1.json b/app-standard-v1.json new file mode 100644 index 0000000..2223087 --- /dev/null +++ b/app-standard-v1.json @@ -0,0 +1,195 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "app.yml specification v1", + "description": "The app.yml format, cleaned up. This format should be used for new apps, but the autoconverter can only convert to v0, so v0 will be kept for some time.", + "type": "object", + "properties": { + "version": { + "type": ["string", "number"], + "description": "The version of the app.yml format you're using." + }, + "metadata": { + "type": "object", + "properties": { + "name": { + "description": "Displayed name of the app", + "type": "string" + }, + "version": { + "description": "Displayed version for the app", + "type": "string" + }, + "category": { + "description": "The category you'd put the app in", + "type": "string" + }, + "tagline": { + "description": "A clever tagline", + "type": "string" + }, + "description": { + "description": "A longer description of the app", + "type": "string" + }, + "developer": { + "description": "The awesome people behind the app", + "type": "string" + }, + "website": { + "description": "Displayed version for the app", + "type": "string" + }, + "dependencies": { + "description": "The services the app depends on", + "type": "array", + "items": { + "type": "string" + } + }, + "repo": { + "description": "The development repository for your app", + "type": "string" + }, + "support": { + "description": "A link to the app support wiki/chat/...", + "type": "string" + }, + "gallery": { + "type": "array", + "description": "URLs or paths in the runcitadel/app-images/[app-name] folder with app images", + "items": { + "type": "string" + } + }, + "path": { + "description": "The path of the app's visible site the open button should open", + "type": "string" + }, + "defaultPassword": { + "description": "The app's default password", + "type": "string" + }, + "torOnly": { + "description": "Whether the app is only available over tor", + "type": "boolean" + }, + "mainContainer": { + "type": "string", + "description": "The name of the main container for the app. If set, IP, port, and hidden service will be assigned to it automatically." + }, + "updateContainer": { + "type": "string", + "description": "The container the developer system should automatically update." + } + }, + "required": [ + "name", + "version", + "category", + "tagline", + "description", + "developer", + "website", + "repo", + "support", + "gallery" + ], + "additionalProperties": false + }, + "containers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "image": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "type": "string", + "enum": ["lnd", "bitcoind", "electrum", "root", "hw"] + } + }, + "ports": { + "type": "array", + "items": { + "type": ["string", "number"] + } + }, + "port": { + "type": "number", + "description": "If this is the main container, the port inside the container which will be exposed to the outside as the port specified in metadata." + }, + "environment": { + "type": ["object", "array"] + }, + "data": { + "type": "array", + "description": "An array of at directories in the container the app stores its data in. Can be empty. Please only list top-level directories.", + "items": { + "type": "string" + } + }, + "user": { + "type": "string", + "description": "The user the container should run as" + }, + "stop_grace_period": { + "type": "string", + "description": "The grace period for stopping the container. Defaults to 1 minute." + }, + "depends_on": { + "type": "array", + "description": "The services the container depends on" + }, + "entrypoint": { + "type": ["string", "array"], + "description": "The entrypoint for the container" + }, + "command": { + "type": ["string", "array"], + "description": "The command for the container" + }, + "init": { + "type": "boolean", + "description": "Whether the container should be run with init" + }, + "stop_signal": { + "type": "string", + "description": "The signal to send to the container when stopping" + }, + "noNetwork": { + "type": "boolean", + "description": "Set this to true if the container shouldn't get an IP & port exposed." + }, + "needsHiddenService": { + "type": "boolean", + "description": "Set this to true if the container should be assigned a hidden service even if it's not the main container." + }, + "hiddenServicePort": { + "type": "number", + "description": "Set this to a port if your container exposes multiple ports, but only one should be a hidden service." + }, + "hiddenServicePorts": { + "type": "object", + "description": "Set this to a map of service names to hidden service ports if your container exposes multiple ports, and all of them should be hidden services.", + "patternProperties": { + "^[a-zA-Z0-9_]+$": { + "type": ["number", "array"] + } + } + } + }, + "additionalProperties": false + }, + "required": ["name", "image"], + "additionalProperties": false + } + }, + "required": ["metadata", "containers"], + "additionalProperties": false +} diff --git a/app-standard-v1.json.license b/app-standard-v1.json.license new file mode 100644 index 0000000..4551d97 --- /dev/null +++ b/app-standard-v1.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021 Aaron Dewes + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/app-system/apps.json b/app-system/apps.json new file mode 100644 index 0000000..fb114b2 --- /dev/null +++ b/app-system/apps.json @@ -0,0 +1,177 @@ +[ + { + "id": "thunderhub", + "image": "apotdevin/thunderhub", + "name": "ThunderHub", + "repo": "https://github.com/apotdevin/thunderhub", + "version": "0.12.30" + }, + { + "id": "ride-the-lightning", + "image": "shahanafarooqui/rtl", + "name": "Ride The Lightning", + "repo": "https://github.com/Ride-The-Lightning/RTL", + "version": "0.11.2" + }, + { + "id": "squeaknode", + "image": "yzernik/squeaknode", + "name": "Squeaknode", + "repo": "https://github.com/yzernik/squeaknode", + "version": "0.1.161" + }, + { + "id": "pi-hole", + "image": "pihole/pihole", + "name": "Pi-hole", + "repo": "https://github.com/pi-hole/pi-hole", + "version": "2021.09" + }, + { + "id": "specter-desktop", + "image": "lncm/specter-desktop", + "name": "Specter Desktop", + "repo": "https://github.com/cryptoadvance/specter-desktop", + "version": "1.6.0" + }, + { + "id": "krystal-bull", + "image": "bitcoinscala/oracle-server-ui", + "name": "Krystal Bull", + "repo": "https://github.com/bitcoin-s/krystal-bull", + "version": "1.7.0-212-d9126650" + }, + { + "id": "element", + "image": "getumbrel/element-web", + "name": "Element", + "repo": "https://github.com/vector-im/element-web", + "version": "2.1.5" + }, + { + "id": "home-assistant", + "image": "homeassistant/home-assistant", + "name": "Home Assistant", + "repo": "https://github.com/home-assistant/core", + "version": "2021.10.4" + }, + { + "id": "photoprism", + "image": "photoprism/photoprism", + "name": "PhotoPrism", + "repo": "https://github.com/photoprism/photoprism", + "version": "210925-96168e4b" + }, + { + "id": "mempool", + "image": "mempool/frontend", + "name": "Mempool", + "repo": "https://github.com/mempool/mempool", + "version": "2.2.2" + }, + { + "id": "samourai-server", + "image": "louneskmt/dojo-nodejs", + "name": "Samourai Server", + "repo": "https://github.com/louneskmt/umbrel-samourai-dojo/tree/v1.10.1-umbrel", + "version": "1.11.0" + }, + { + "id": "btc-rpc-explorer", + "image": "runcitadel/btc-rpc-explorer", + "name": "BTC RPC Explorer", + "repo": "https://github.com/janoside/btc-rpc-explorer", + "version": "3.2.0" + }, + { + "id": "nextcloud", + "image": "nextcloud", + "name": "Nextcloud", + "repo": "https://github.com/nextcloud/server", + "version": "22.1.1" + }, + { + "id": "sphinx-relay", + "image": "sphinxlightning/sphinx-relay", + "name": "Sphinx Relay", + "repo": "https://github.com/stakwork/sphinx-relay", + "version": "2.2.1" + }, + { + "id": "code-server", + "image": "codercom/code-server", + "name": "code-server", + "repo": "https://github.com/cdr/code-server", + "version": "3.12.0" + }, + { + "id": "vaultwarden", + "image": "vaultwarden/server", + "name": "Vaultwarden", + "repo": "https://github.com/dani-garcia/vaultwarden", + "version": "1.22.2" + }, + { + "id": "bluewallet", + "image": "bluewalletorganization/lndhub", + "name": "BlueWallet Lightning", + "repo": "https://github.com/BlueWallet/LndHub", + "version": "1.4.1" + }, + { + "id": "gitea", + "image": "gitea/gitea", + "name": "Gitea", + "repo": "https://github.com/go-gitea/gitea", + "version": "1.15.4" + }, + { + "id": "lightning-terminal", + "image": "lightninglabs/lightning-terminal", + "name": "Lightning Terminal", + "repo": "https://github.com/lightninglabs/lightning-terminal", + "version": "0.5.2-alpha" + }, + { + "id": "node-red", + "image": "nodered/node-red", + "name": "Node-RED", + "repo": "https://github.com/node-red/node-red", + "version": "2.0.6" + }, + { + "id": "btcpay-server", + "image": "btcpayserver/btcpayserver", + "name": "BTCPay Server", + "repo": "https://github.com/btcpayserver/btcpayserver", + "version": "1.2.4" + }, + { + "id": "lnbits", + "image": "lnbitsdocker/lnbits", + "name": "LNbits", + "repo": "https://github.com/lnbits/lnbits", + "version": "3167645" + }, + { + "id": "simple-torrent", + "image": "boypt/cloud-torrent", + "name": "SimpleTorrent", + "repo": "https://github.com/boypt/simple-torrent", + "version": "1.3.9" + }, + { + "id": "synapse", + "image": "matrixdotorg/synapse", + "name": "Synapse", + "repo": "https://github.com/matrix-org/synapse", + "version": "1.43.0" + }, + { + "id": "lnmarkets", + "image": "ghcr.io/lnmarkets/umbrel", + "name": "LN Markets", + "repo": "https://github.com/lnmarkets/umbrel", + "version": "1.0.0" + } +] \ No newline at end of file diff --git a/app-system/apps.json.license b/app-system/apps.json.license new file mode 100644 index 0000000..454d3ee --- /dev/null +++ b/app-system/apps.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021 Citadel and contributors + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/app-system/docker-compose.common.yml b/app-system/docker-compose.common.yml new file mode 100644 index 0000000..dddc9ca --- /dev/null +++ b/app-system/docker-compose.common.yml @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +version: "3.8" + +networks: + default: + name: citadel_main_network + external: true diff --git a/app-system/sources.list b/app-system/sources.list new file mode 100644 index 0000000..5337f49 --- /dev/null +++ b/app-system/sources.list @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later +# A collection of fully FLOSS app definitions and FLOSS apps for Citadel. +https://github.com/runcitadel/apps main +# Some apps copied from Umbrel which aren't fully FLOSS yet. +# Enabled by default so we have all features from Umbrel. +https://github.com/runcitadel/apps-nonfree main diff --git a/app/app-manager.py b/app/app-manager.py new file mode 100755 index 0000000..46610b9 --- /dev/null +++ b/app/app-manager.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import json +from lib.manage import compose, createDataDir, deleteData, getUserData, setInstalled, setRemoved, startInstalled, stopInstalled, update, deriveEntropy, updateRepos +from lib.validate import findAndValidateApps +import os +import argparse + +# Print an error if user is not root +if os.getuid() != 0: + print('This script must be run as root!') + exit(1) + +# The directory with this script +scriptDir = os.path.dirname(os.path.realpath(__file__)) +nodeRoot = os.path.join(scriptDir, "..") +appsDir = os.path.join(nodeRoot, "apps") +appDataDir = os.path.join(nodeRoot, "app-data") +userFile = os.path.join(nodeRoot, "db", "user.json") +legacyScript = os.path.join(nodeRoot, "scripts", "app") + +parser = argparse.ArgumentParser(description="Manage apps on your Citadel") +parser.add_argument('action', help='What to do with the app database.', choices=[ + "list", "download", "update", "update-online", "ls-installed", "install", "uninstall", "stop", "start", "compose", "restart", "entropy"]) +# Add the --invoked-by-configure option, which is hidden from the user in --help +parser.add_argument('--invoked-by-configure', + action='store_true', help=argparse.SUPPRESS) +parser.add_argument('--verbose', '-v', action='store_true') +parser.add_argument( + 'app', help='Optional, the app to perform an action on. (For install, uninstall, stop, start and compose)', nargs='?') +parser.add_argument( + 'other', help='Anything else (For compose)', nargs="*") +args = parser.parse_args() + +# If no action is specified, the list action is used +if args.action is None: + args.action = 'list' + +if args.action == 'list': + apps = findAndValidateApps(appsDir) + for app in apps: + print(app) + exit(0) +elif args.action == 'download': + updateRepos() + exit(0) +elif args.action == 'update': + if(args.invoked_by_configure): + update(args.app) + else: + os.system(os.path.join(nodeRoot, "scripts", "configure")) + os.chdir(nodeRoot) + os.system("docker compose stop app_tor") + os.system("docker compose start app_tor") + os.system("docker compose stop app_2_tor") + os.system("docker compose start app_2_tor") + os.system("docker compose stop app_3_tor") + os.system("docker compose start app_3_tor") + exit(0) +elif args.action == 'update-online': + updateRepos() + print("Downloaded all updates") + if(args.invoked_by_configure): + update(args.app) + else: + os.system(os.path.join(nodeRoot, "scripts", "configure")) + os.chdir(nodeRoot) + os.system("docker compose stop app_tor") + os.system("docker compose start app_tor") + os.system("docker compose stop app_2_tor") + os.system("docker compose start app_2_tor") + os.system("docker compose stop app_3_tor") + os.system("docker compose start app_3_tor") + exit(0) +elif args.action == 'ls-installed': + # Load the userFile as JSON, check if installedApps is in it, and if so, print the apps + with open(userFile, "r") as f: + userData = json.load(f) + if "installedApps" in userData: + print("\n".join(userData["installedApps"])) + else: + # To match the behavior of the old script, print a newline if there are no apps installed + print("\n") +elif args.action == 'install': + if not args.app: + print("No app provided") + exit(1) + createDataDir(args.app) + compose(args.app, "pull") + compose(args.app, "up --detach") + setInstalled(args.app) +elif args.action == 'uninstall': + if not args.app: + print("No app provided") + exit(1) + userData = getUserData() + if not "installedApps" in userData or args.app not in userData["installedApps"]: + print("App {} is not installed".format(args.app)) + exit(1) + print("Stopping app {}...".format(args.app)) + compose(args.app, "rm --force --stop") + print("Deleting data...") + deleteData(args.app) + print("Removing from the list of installed apps...") + setRemoved(args.app) +elif args.action == 'stop': + if not args.app: + print("No app provided") + exit(1) + userData = getUserData() + if(args.app == "installed"): + if "installedApps" in userData: + stopInstalled() + exit(0) + print("Stopping app {}...".format(args.app)) + compose(args.app, "rm --force --stop") +elif args.action == 'start': + if not args.app: + print("No app provided") + exit(1) + + userData = getUserData() + if(args.app == "installed"): + if "installedApps" in userData: + startInstalled() + exit(0) + + if not "installedApps" in userData or args.app not in userData["installedApps"]: + print("App {} is not yet installed".format(args.app)) + exit(1) + compose(args.app, "up --detach") + +elif args.action == 'restart': + if not args.app: + print("No app provided") + exit(1) + if(args.app == "installed"): + stopInstalled() + startInstalled() + exit(0) + + userData = getUserData() + if not "installedApps" in userData or args.app not in userData["installedApps"]: + print("App {} is not yet installed".format(args.app)) + exit(1) + compose(args.app, "rm --force --stop") + compose(args.app, "up --detach") + +elif args.action == 'compose': + if not args.app: + print("No app provided") + exit(1) + compose(args.app, " ".join(args.other)) + +elif args.action == "entropy": + if(args.app == ""): + print("Missing identifier for entropy") + exit(1) + print(deriveEntropy(args.app)) + +else: + print("Error: Unknown action") + print("See --help for usage") + exit(1) diff --git a/app/app-standard-v1.json b/app/app-standard-v1.json new file mode 100644 index 0000000..2223087 --- /dev/null +++ b/app/app-standard-v1.json @@ -0,0 +1,195 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "app.yml specification v1", + "description": "The app.yml format, cleaned up. This format should be used for new apps, but the autoconverter can only convert to v0, so v0 will be kept for some time.", + "type": "object", + "properties": { + "version": { + "type": ["string", "number"], + "description": "The version of the app.yml format you're using." + }, + "metadata": { + "type": "object", + "properties": { + "name": { + "description": "Displayed name of the app", + "type": "string" + }, + "version": { + "description": "Displayed version for the app", + "type": "string" + }, + "category": { + "description": "The category you'd put the app in", + "type": "string" + }, + "tagline": { + "description": "A clever tagline", + "type": "string" + }, + "description": { + "description": "A longer description of the app", + "type": "string" + }, + "developer": { + "description": "The awesome people behind the app", + "type": "string" + }, + "website": { + "description": "Displayed version for the app", + "type": "string" + }, + "dependencies": { + "description": "The services the app depends on", + "type": "array", + "items": { + "type": "string" + } + }, + "repo": { + "description": "The development repository for your app", + "type": "string" + }, + "support": { + "description": "A link to the app support wiki/chat/...", + "type": "string" + }, + "gallery": { + "type": "array", + "description": "URLs or paths in the runcitadel/app-images/[app-name] folder with app images", + "items": { + "type": "string" + } + }, + "path": { + "description": "The path of the app's visible site the open button should open", + "type": "string" + }, + "defaultPassword": { + "description": "The app's default password", + "type": "string" + }, + "torOnly": { + "description": "Whether the app is only available over tor", + "type": "boolean" + }, + "mainContainer": { + "type": "string", + "description": "The name of the main container for the app. If set, IP, port, and hidden service will be assigned to it automatically." + }, + "updateContainer": { + "type": "string", + "description": "The container the developer system should automatically update." + } + }, + "required": [ + "name", + "version", + "category", + "tagline", + "description", + "developer", + "website", + "repo", + "support", + "gallery" + ], + "additionalProperties": false + }, + "containers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "image": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "type": "string", + "enum": ["lnd", "bitcoind", "electrum", "root", "hw"] + } + }, + "ports": { + "type": "array", + "items": { + "type": ["string", "number"] + } + }, + "port": { + "type": "number", + "description": "If this is the main container, the port inside the container which will be exposed to the outside as the port specified in metadata." + }, + "environment": { + "type": ["object", "array"] + }, + "data": { + "type": "array", + "description": "An array of at directories in the container the app stores its data in. Can be empty. Please only list top-level directories.", + "items": { + "type": "string" + } + }, + "user": { + "type": "string", + "description": "The user the container should run as" + }, + "stop_grace_period": { + "type": "string", + "description": "The grace period for stopping the container. Defaults to 1 minute." + }, + "depends_on": { + "type": "array", + "description": "The services the container depends on" + }, + "entrypoint": { + "type": ["string", "array"], + "description": "The entrypoint for the container" + }, + "command": { + "type": ["string", "array"], + "description": "The command for the container" + }, + "init": { + "type": "boolean", + "description": "Whether the container should be run with init" + }, + "stop_signal": { + "type": "string", + "description": "The signal to send to the container when stopping" + }, + "noNetwork": { + "type": "boolean", + "description": "Set this to true if the container shouldn't get an IP & port exposed." + }, + "needsHiddenService": { + "type": "boolean", + "description": "Set this to true if the container should be assigned a hidden service even if it's not the main container." + }, + "hiddenServicePort": { + "type": "number", + "description": "Set this to a port if your container exposes multiple ports, but only one should be a hidden service." + }, + "hiddenServicePorts": { + "type": "object", + "description": "Set this to a map of service names to hidden service ports if your container exposes multiple ports, and all of them should be hidden services.", + "patternProperties": { + "^[a-zA-Z0-9_]+$": { + "type": ["number", "array"] + } + } + } + }, + "additionalProperties": false + }, + "required": ["name", "image"], + "additionalProperties": false + } + }, + "required": ["metadata", "containers"], + "additionalProperties": false +} diff --git a/app/app-standard-v1.json.license b/app/app-standard-v1.json.license new file mode 100644 index 0000000..4551d97 --- /dev/null +++ b/app/app-standard-v1.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021 Aaron Dewes + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/app/lib/__init__.py b/app/lib/__init__.py new file mode 100644 index 0000000..364fef7 --- /dev/null +++ b/app/lib/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/app/lib/citadelutils.py b/app/lib/citadelutils.py new file mode 100644 index 0000000..5d57f6f --- /dev/null +++ b/app/lib/citadelutils.py @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import re + +# Helper functions +# Return a list of env vars in a string, supports both $NAM§ and ${NAME} format for the env var +# This can potentially be used to get around permissions, so this check is critical for security +# Please report any security vulnerabilities you find in this check to aaron.dewes@protonmail.com +def getEnvVars(string: str): + string = str(string) + envVars = re.findall(r'\$\{.*?\}', string) + newEnvVars = re.findall(r"\$(?!{)([A-z1-9]+)", string) + return [envVar[2:-1] for envVar in envVars] + newEnvVars + + +# Check if an array only contains values which are also in another array +def checkArrayContainsAllElements(array: list, otherArray: list): + for element in array: + if element not in otherArray: + return False + return True + +# Parse a dotenv file +# Values can either be KEY=VALUE or KEY="VALUE" or KEY='VALUE' +# Returns all env vars as a dict +def parse_dotenv(file_path): + envVars: dict = {} + with open(file_path, 'r') as file: + for line in file: + line = line.strip() + if line.startswith('#') or len(line) == 0: + continue + if '=' in line: + key, value = line.split('=', 1) + value = value.strip('"').strip("'") + envVars[key] = value + else: + print("Error: Invalid line in {}: {}".format(file_path, line)) + print("Line should be in the format KEY=VALUE or KEY=\"VALUE\" or KEY='VALUE'") + exit(1) + return envVars + +# Combines two objects +# If the key exists in both objects, the value of the second object is used +# If the key does not exist in the first object, the value from the second object is used +# If a key contains a list, the second object's list is appended to the first object's list +# If a key contains another object, these objects are combined +def combineObjects(obj1: dict, obj2: dict): + for key in obj2: + if key in obj1: + if isinstance(obj1[key], list): + obj1[key] = obj1[key] + obj2[key] + elif isinstance(obj1[key], dict): + obj1[key] = combineObjects(obj1[key], obj2[key]) + else: + obj1[key] = obj2[key] + else: + obj1[key] = obj2[key] + return obj1 diff --git a/app/lib/composegenerator/shared/const.py b/app/lib/composegenerator/shared/const.py new file mode 100644 index 0000000..18790a8 --- /dev/null +++ b/app/lib/composegenerator/shared/const.py @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +def permissions(): + return { + "lnd": { + "environment_allow": { + "LND_IP": "${LND_IP}", + "LND_GRPC_PORT": "${LND_GRPC_PORT}", + "LND_REST_PORT": "${LND_REST_PORT}", + "BITCOIN_NETWORK": "${BITCOIN_NETWORK}" + }, + "volumes": [ + '${LND_DATA_DIR}:/lnd:ro' + ] + }, + "bitcoind": { + "environment_allow": { + "BITCOIN_IP": "${BITCOIN_IP}", + "BITCOIN_NETWORK": "${BITCOIN_NETWORK}", + "BITCOIN_P2P_PORT": "${BITCOIN_P2P_PORT}", + "BITCOIN_RPC_PORT": "${BITCOIN_RPC_PORT}", + "BITCOIN_RPC_USER": "${BITCOIN_RPC_USER}", + "BITCOIN_RPC_PASS": "${BITCOIN_RPC_PASS}", + "BITCOIN_RPC_AUTH": "${BITCOIN_RPC_AUTH}", + "BITCOIN_ZMQ_RAWBLOCK_PORT": "${BITCOIN_ZMQ_RAWBLOCK_PORT}", + "BITCOIN_ZMQ_RAWTX_PORT": "${BITCOIN_ZMQ_RAWTX_PORT}", + "BITCOIN_ZMQ_HASHBLOCK_PORT": "${BITCOIN_ZMQ_HASHBLOCK_PORT}", + }, + "volumes": [ + "${BITCOIN_DATA_DIR}:/bitcoin:ro" + ] + }, + "electrum": { + "environment_allow": { + "ELECTRUM_IP": "${ELECTRUM_IP}", + "ELECTRUM_PORT": "${ELECTRUM_PORT}", + } + } + } + +# Vars which are always allowed without permissions +always_allowed_env = ["TOR_PROXY_IP", "TOR_PROXY_PORT", + "APP_DOMAIN", "APP_HIDDEN_SERVICE", "BITCOIN_NETWORK"] diff --git a/app/lib/composegenerator/shared/env.py b/app/lib/composegenerator/shared/env.py new file mode 100644 index 0000000..922d21d --- /dev/null +++ b/app/lib/composegenerator/shared/env.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import re +from lib.composegenerator.shared.const import always_allowed_env +from lib.citadelutils import checkArrayContainsAllElements, getEnvVars + +def validateEnvByValue(env: list, allowed: list, app_name: str): + # Combine always_allowed_env with allowed into one list + # Then check if all elements in env are in the resulting list + all_allowed = allowed + always_allowed_env + if(not checkArrayContainsAllElements(env, all_allowed)): + # This has a weird syntax, and it confuses VSCode, but it works + validation_regex = r"APP_{}(\S+)".format( + app_name.upper().replace("-", "_")) + for key in env: + # If the key is neither in all_allowed nor is a full match against the validation regex, print a warning and return false + if key not in all_allowed and re.fullmatch(validation_regex, key) is None and not key.startswith("APP_HIDDEN_SERVICE")and not key.startswith("APP_SEED"): + print("Invalid environment variable {} in app {}".format( + key, app_name)) + return False + return True + + +def validateEnv(app: dict): + # For every container of the app, check if all env vars in the strings in environment are defined in env + for container in app['containers']: + if 'environment' in container: + if 'environment_allow' in container: + existingEnv = list(container['environment_allow'].keys()) + del container['environment_allow'] + else: + existingEnv = [] + # The next step depends on the type of the environment object, which is either a list or dict + # If it's a list, split every string in it by the first=, then run getEnvVars(envVarValue) on it + # ON a dict, run getEnvVars(envVarValue) on every value of the environment object + # Then check if all env vars returned by getEnvVars are defined in env + if(isinstance(container['environment'], list)): + raise Exception("List env vars are no longer supported for container {} of app {}".format( + container['name'], app['metadata']['name'])) + elif(isinstance(container['environment'], dict)): + for envVar in container['environment'].values(): + if(not validateEnvByValue(getEnvVars(envVar), existingEnv, app['metadata']['id'])): + raise Exception("Env vars not defined for container {} of app {}".format( + container['name'], app['metadata']['name'])) diff --git a/app/lib/composegenerator/shared/main.py b/app/lib/composegenerator/shared/main.py new file mode 100644 index 0000000..024a0ca --- /dev/null +++ b/app/lib/composegenerator/shared/main.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Main functions +from lib.citadelutils import combineObjects +from lib.composegenerator.shared.const import permissions + + +def convertContainerPermissions(app): + for container in app['containers']: + if 'permissions' in container: + for permission in container['permissions']: + if(permission in permissions()): + container = combineObjects( + container, permissions()[permission]) + else: + print("Warning: container {} of app {} defines unknown permission {}".format(container['name'], app['metadata']['name'], permission)) + del container['permissions'] + return app + +def convertContainersToServices(app: dict): + app['services'] = {} + for container in app['containers']: + app['services'][container['name']] = container + del app['services'][container['name']]['name'] + del app['containers'] + return app + +# Converts the data of every container in app['containers'] to a volume, which is then added to the app +def convertDataDirToVolume(app: dict): + for container in app['containers']: + # Loop through data dirs in container['data'], if they don't contain a .., add them to container['volumes'] + # Also, a datadir shouldn't start with a / + if 'data' in container: + for dataDir in container['data']: + if not 'volumes' in container: + container['volumes'] = [] + if(dataDir.find("..") == -1 and dataDir[0] != "/"): + container['volumes'].append( + '${APP_DATA_DIR}/' + dataDir) + else: + print("Data dir " + dataDir + + " contains invalid characters") + del container['data'] + return app + +def addStopConfig(app: dict): + for container in app['containers']: + if not 'stop_grace_period' in container: + container['stop_grace_period'] = '1m' + container['restart'] = "on-failure" + return app diff --git a/app/lib/composegenerator/v1/generate.py b/app/lib/composegenerator/v1/generate.py new file mode 100644 index 0000000..11f6d63 --- /dev/null +++ b/app/lib/composegenerator/v1/generate.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +from lib.composegenerator.v1.networking import configureHiddenServices, configureIps, configureMainPort +from lib.composegenerator.shared.main import convertDataDirToVolume, convertContainerPermissions, addStopConfig, convertContainersToServices +from lib.composegenerator.shared.env import validateEnv +import os + +def createComposeConfigFromV1(app: dict, nodeRoot: str): + if("version" in app): + if(str(app['version']) != "1"): + print("Warning: app version is not supported") + return False + envFile = os.path.join(nodeRoot, ".env") + networkingFile = os.path.join(nodeRoot, "apps", "networking.json") + + app = convertContainerPermissions(app) + validateEnv(app) + app = convertDataDirToVolume(app) + app = configureIps(app, networkingFile, envFile) + app = configureMainPort(app, nodeRoot) + app = configureHiddenServices(app, nodeRoot) + app = addStopConfig(app) + app = convertContainersToServices(app) + del app['metadata'] + if("version" in app): + del app["version"] + # Set version to 3.8 (current compose file version) + app = {'version': '3.8', **app} + return app diff --git a/app/lib/composegenerator/v1/networking.py b/app/lib/composegenerator/v1/networking.py new file mode 100644 index 0000000..619eadd --- /dev/null +++ b/app/lib/composegenerator/v1/networking.py @@ -0,0 +1,208 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +from lib.citadelutils import parse_dotenv +import json +from os import path +import random +from lib.composegenerator.v1.utils.networking import getContainerHiddenService, getFreePort, getHiddenService + + +def assignIp(container: dict, appId: str, networkingFile: str, envFile: str): + # Strip leading/trailing whitespace from container['name'] + container['name'] = container['name'].strip() + # If the name still contains a newline, throw an error + if(container['name'].find("\n") != -1): + raise Exception("Newline in container name") + env_var = "APP_{}_{}_IP".format( + appId.upper().replace("-", "_"), + container['name'].upper().replace("-", "_") + ) + # Write a list of used IPs to the usedIpFile as JSON, and read that file to check if an IP + # can be used + usedIps = [] + networkingData = {} + if(path.isfile(networkingFile)): + with open(networkingFile, 'r') as f: + networkingData = json.load(f) + + if('ip_addresses' in networkingData): + usedIps = list(networkingData['ip_addresses'].values()) + else: + networkingData['ip_addresses'] = {} + # An IP 10.21.21.xx, with x being a random number above 40 is asigned to the container + # If the IP is already in use, it will be tried again until it's not in use + # If it's not in use, it will be added to the usedIps list and written to the usedIpFile + # If the usedIpsFile contains all IPs between 10.21.21.40 and 10.21.21.255 (inclusive), + # Throw an error, because no more IPs can be used + if(len(usedIps) == 215): + raise Exception("No more IPs can be used") + + if("{}-{}".format(appId, container['name']) in networkingData['ip_addresses']): + ip = networkingData['ip_addresses']["{}-{}".format(appId, container['name'])] + else: + while True: + ip = "10.21.21." + str(random.randint(40, 255)) + if(ip not in usedIps): + networkingData['ip_addresses']["{}-{}".format(appId, container['name'])] = ip + break + container['networks'] = {'default': { + 'ipv4_address': "$" + env_var}} + + dotEnv = parse_dotenv(envFile) + if(env_var in dotEnv and str(dotEnv[env_var]) == str(ip)): + return container + + # Now append a new line with APP_{app_name}_{container_name}_IP=${IP} to the envFile + with open(envFile, 'a') as f: + f.write("{}={}\n".format(env_var, ip)) + with open(networkingFile, 'w') as f: + json.dump(networkingData, f) + return container + + +def assignPort(container: dict, appId: str, networkingFile: str, envFile: str): + # Strip leading/trailing whitespace from container['name'] + container['name'] = container['name'].strip() + # If the name still contains a newline, throw an error + if(container['name'].find("\n") != -1 or container['name'].find(" ") != -1): + raise Exception("Newline or space in container name") + + env_var = "APP_{}_{}_PORT".format( + appId.upper().replace("-", "_"), + container['name'].upper().replace("-", "_") + ) + + port = getFreePort(networkingFile, appId) + + dotEnv = parse_dotenv(envFile) + if(env_var in dotEnv and str(dotEnv[env_var]) == str(port)): + return {"port": port, "env_var": "${{{}}}".format(env_var)} + + # Now append a new line with APP_{app_name}_{container_name}_PORT=${PORT} to the envFile + with open(envFile, 'a') as f: + f.write("{}={}\n".format(env_var, port)) + + # This is confusing, but {{}} is an escaped version of {} so it is ${{ {} }} + # where the outer {{ }} will be replaced by {} in the returned string + return {"port": port, "env_var": "${{{}}}".format(env_var)} + +def getMainContainer(app: dict): + if len(app['containers']) == 1: + return app['containers'][0] + else: + if not 'mainContainer' in app['metadata']: + app['metadata']['mainContainer'] = 'main' + for container in app['containers']: + if container['name'] == app['metadata']['mainContainer']: + return container + raise Exception("No main container found for app {}".format(app['metadata']['name'])) + +def configureMainPort(app: dict, nodeRoot: str): + registryFile = path.join(nodeRoot, "apps", "registry.json") + registry: list = [] + if(path.isfile(registryFile)): + with open(registryFile, 'r') as f: + registry = json.load(f) + else: + raise Exception("Registry file not found") + + + dotEnv = parse_dotenv(path.join(nodeRoot, ".env")) + + mainContainer = getMainContainer(app) + + portDetails = assignPort(mainContainer, app['metadata']['id'], path.join( + nodeRoot, "apps", "networking.json"), path.join(nodeRoot, ".env")) + containerPort = portDetails['port'] + portAsEnvVar = portDetails['env_var'] + portToAppend = portAsEnvVar + + if "port" in mainContainer: + portToAppend = "{}:{}".format(portAsEnvVar, mainContainer['port']) + del mainContainer['port'] + else: + portToAppend = "{}:{}".format(portAsEnvVar, portAsEnvVar) + + if "ports" in mainContainer: + mainContainer['ports'].append(portToAppend) + else: + mainContainer['ports'] = [portToAppend] + + mainContainer = assignIp(mainContainer, app['metadata']['id'], path.join( + nodeRoot, "apps", "networking.json"), path.join(nodeRoot, ".env")) + + # If the IP wasn't in dotenv before, now it should be + dotEnv = parse_dotenv(path.join(nodeRoot, ".env")) + + containerIP = dotEnv['APP_{}_{}_IP'.format(app['metadata']['id'].upper().replace( + "-", "_"), mainContainer['name'].upper().replace("-", "_"))] + + hiddenservice = getHiddenService( + app['metadata']['name'], app['metadata']['id'], containerIP, containerPort) + + torDaemons = ["torrc-apps", "torrc-apps-2", "torrc-apps-3"] + torFileToAppend = torDaemons[random.randint(0, len(torDaemons) - 1)] + with open(path.join(nodeRoot, "tor", torFileToAppend), 'a') as f: + f.write(hiddenservice) + + # Also set the port in metadata + app['metadata']['port'] = int(containerPort) + + for registryApp in registry: + if(registryApp['id'] == app['metadata']['id']): + registry[registry.index(registryApp)]['port'] = int(containerPort) + break + + with open(registryFile, 'w') as f: + json.dump(registry, f, indent=4, sort_keys=True) + + return app + + +def configureIps(app: dict, networkingFile: str, envFile: str): + for container in app['containers']: + if('noNetwork' in container and container['noNetwork']): + # Check if port is defined for the container + if('port' in container): + raise Exception("Port defined for container without network") + if(app['metadata']['mainContainer'] == container['name']): + raise Exception("Main container without network") + # Skip this iteration of the loop + continue + + container = assignIp(container, app['metadata']['id'], networkingFile, envFile) + + return app + +def configureHiddenServices(app: dict, nodeRoot: str): + dotEnv = parse_dotenv(path.join(nodeRoot, ".env")) + hiddenServices = "" + + if len(app['containers']) == 1: + mainContainer = app['containers'][0] + else: + mainContainer = None + if not 'mainContainer' in app['metadata']: + app['metadata']['mainContainer'] = 'main' + for container in app['containers']: + if container['name'] == app['metadata']['mainContainer']: + mainContainer = container + break + if mainContainer is None: + raise Exception("No main container found") + + for container in app['containers']: + env_var = "APP_{}_{}_IP".format( + app["metadata"]["id"].upper().replace("-", "_"), + container['name'].upper().replace("-", "_") + ) + hiddenServices += getContainerHiddenService(app["metadata"]["name"], app["metadata"]["id"], container, dotEnv[env_var], container["name"] == mainContainer["name"]) + + torDaemons = ["torrc-apps", "torrc-apps-2", "torrc-apps-3"] + torFileToAppend = torDaemons[random.randint(0, len(torDaemons) - 1)] + with open(path.join(nodeRoot, "tor", torFileToAppend), 'a') as f: + f.write(hiddenServices) + + return app \ No newline at end of file diff --git a/app/lib/composegenerator/v1/utils/networking.py b/app/lib/composegenerator/v1/utils/networking.py new file mode 100644 index 0000000..03a73b2 --- /dev/null +++ b/app/lib/composegenerator/v1/utils/networking.py @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import json +import os +import random + + +def getFreePort(networkingFile: str, appId: str): + # Ports used currently in Umbrel + usedPorts = [80, 8333, 8332, 28332, 28333, 28334, 10009, 8080, 50001, 9050, 3002, 3000, 3300, 3001, 3004, 25441, + 3003, 3007, 3006, 3009, 3005, 8898, 3008, 8081, 8082, 8083, 8085, 2222, 8086, 8087, 8008, 8088, 8089, 8091] + networkingData = {} + if(os.path.isfile(networkingFile)): + with open(networkingFile, 'r') as f: + networkingData = json.load(f) + if('ports' in networkingData): + usedPorts += list(networkingData['ports'].values()) + else: + networkingData['ports'] = {} + + if(appId in networkingData['ports']): + return networkingData['ports'][appId] + + while True: + port = str(random.randint(1024, 49151)) + if(port not in usedPorts): + # Check if anyhing is listening on the specific port + if(os.system("netstat -ntlp | grep " + port + " > /dev/null") != 0): + networkingData['ports'][appId] = port + break + + with open(networkingFile, 'w') as f: + json.dump(networkingData, f) + + return port + + +def getHiddenServiceMultiPort(name: str, id: str, internalIp: str, ports: list) -> str: + hiddenServices = ''' +# {} Hidden Service +HiddenServiceDir /var/lib/tor/app-{} +'''.format(name, id) + for port in ports: + hiddenServices += 'HiddenServicePort {} {}:{}'.format( + port, internalIp, port) + hiddenServices += "\n" + return hiddenServices + + +def getHiddenServiceString(name: str, id: str, internalPort, internalIp: str, publicPort) -> str: + return ''' +# {} Hidden Service +HiddenServiceDir /var/lib/tor/app-{} +HiddenServicePort {} {}:{} + +'''.format(name, id, publicPort, internalIp, internalPort) + + +def getHiddenService(appName: str, appId: str, appIp: str, appPort: str) -> str: + return getHiddenServiceString(appName, appId, appPort, appIp, "80") + + +def getContainerHiddenService(appName: str, appId: str, container: dict, containerIp: str, isMainContainer: bool) -> str: + if not "needsHiddenService" in container and not isMainContainer: + return "" + if ("ports" in container or not "port" in container) and not "hiddenServicePort" in container and not isMainContainer: + print("Container {} for app {} isn't compatible with hidden service assignment".format( + container["name"], appName)) + return "" + + if isMainContainer: + if not "hiddenServicePorts" in container: + return "" + # hiddenServicePorts is a map of hidden service name to port + # We need to generate a hidden service for each one + hiddenServices = "" + for name, port in container["hiddenServicePorts"].items(): + if ".." in name: + print(".. Not allowed in service names, this app ({}) isn't getting a hidden service.".format(appName)) + + # If port is a list, use getHiddenServiceMultiPort + if isinstance(port, list): + hiddenServices += getHiddenServiceMultiPort("{} {}".format(appName, name), "{}-{}".format( + appId, name), containerIp, port) + else: + hiddenServices += getHiddenServiceString("{} {}".format(appName, name), "{}-{}".format( + appId, name), port, containerIp, port) + del container["hiddenServicePorts"] + return hiddenServices + + del container["needsHiddenService"] + if not "port" in container: + data = getHiddenServiceString(appName + container["name"], "{}-{}".format( + appId, container["name"]), container["hiddenServicePort"], containerIp, "80") + del container["hiddenServicePort"] + return data + else: + return getHiddenServiceString(appName + container["name"], "{}-{}".format( + appId, container["name"]), container["port"], containerIp, container["port"]) diff --git a/app/lib/entropy.py b/app/lib/entropy.py new file mode 100644 index 0000000..196e7e7 --- /dev/null +++ b/app/lib/entropy.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import os +import subprocess + +scriptDir = os.path.dirname(os.path.realpath(__file__)) +nodeRoot = os.path.join(scriptDir, "..", "..") + +def deriveEntropy(identifier: str): + seedFile = os.path.join(nodeRoot, "db", "citadel-seed", "seed") + alternativeSeedFile = os.path.join(nodeRoot, "db", "citadel-seed", "seed") + if not os.path.isfile(seedFile): + if(os.path.isfile(alternativeSeedFile)): + seedFile = alternativeSeedFile + else: + print("No seed file found, exiting...") + exit(1) + with open(seedFile, "r") as f: + node_seed = f.read().strip() + entropy = subprocess.check_output( + 'printf "%s" "{}" | openssl dgst -sha256 -binary -hmac "{}" | xxd -p | tr --delete "\n"'.format(identifier, node_seed), shell=True) + return entropy.decode("utf-8") diff --git a/app/lib/manage.py b/app/lib/manage.py new file mode 100644 index 0000000..5c0d2f0 --- /dev/null +++ b/app/lib/manage.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import stat +import tempfile +import threading +from typing import List +from sys import argv +import os +import requests +import shutil +import json +import yaml +import subprocess + +from lib.composegenerator.v1.generate import createComposeConfigFromV1 +from lib.validate import findAndValidateApps +from lib.metadata import getAppRegistry, getSimpleAppRegistry +from lib.entropy import deriveEntropy + +# For an array of threads, join them and wait for them to finish + + +def joinThreads(threads: List[threading.Thread]): + for thread in threads: + thread.join() + + +# The directory with this script +scriptDir = os.path.dirname(os.path.realpath(__file__)) +nodeRoot = os.path.join(scriptDir, "..", "..") +appsDir = os.path.join(nodeRoot, "apps") +appSystemDir = os.path.join(nodeRoot, "app-system") +sourcesList = os.path.join(appSystemDir, "sources.list") +appDataDir = os.path.join(nodeRoot, "app-data") +userFile = os.path.join(nodeRoot, "db", "user.json") +legacyScript = os.path.join(nodeRoot, "scripts", "app") + +# Returns a list of every argument after the second one in sys.argv joined into a string by spaces + + +def getArguments(): + arguments = "" + for i in range(3, len(argv)): + arguments += argv[i] + " " + return arguments + + +def getAppYml(name): + url = 'https://raw.githubusercontent.com/runcitadel/core/main/apps/' + \ + name + '/' + 'app.yml' + response = requests.get(url) + if response.status_code == 200: + return response.text + else: + return False + + +def getAppYmlPath(app): + return os.path.join(appsDir, app, 'app.yml') + + +def update(verbose: bool = False): + apps = findAndValidateApps(appsDir) + # The compose generation process updates the registry, so we need to get it set up with the basics before that + registry = getAppRegistry(apps, appsDir) + with open(os.path.join(appsDir, "registry.json"), "w") as f: + json.dump(registry, f, indent=4, sort_keys=True) + print("Wrote registry to registry.json") + + simpleRegistry = getSimpleAppRegistry(apps, appsDir) + with open(os.path.join(appSystemDir, "apps.json"), "w") as f: + json.dump(simpleRegistry, f, indent=4, sort_keys=True) + print("Wrote version information to apps.json") + + # Loop through the apps and generate valid compose files from them, then put these into the app dir + for app in apps: + composeFile = os.path.join(appsDir, app, "docker-compose.yml") + appYml = os.path.join(appsDir, app, "app.yml") + with open(composeFile, "w") as f: + appCompose = getApp(appYml, app) + if(appCompose): + f.write(yaml.dump(appCompose, sort_keys=False)) + if verbose: + print("Wrote " + app + " to " + composeFile) + print("Generated configuration successfully") + + +def download(app: str = None): + if(app is None): + apps = findAndValidateApps(appsDir) + for app in apps: + data = getAppYml(app) + if data: + with open(getAppYmlPath(app), 'w') as f: + f.write(data) + else: + print("Warning: Could not download " + app) + else: + data = getAppYml(app) + if data: + with open(getAppYmlPath(app), 'w') as f: + f.write(data) + else: + print("Warning: Could not download " + app) + + +def getUserData(): + userData = {} + if os.path.isfile(userFile): + with open(userFile, "r") as f: + userData = json.load(f) + return userData + + +def startInstalled(): + # If userfile doen't exist, just do nothing + userData = {} + if os.path.isfile(userFile): + with open(userFile, "r") as f: + userData = json.load(f) + threads = [] + for app in userData["installedApps"]: + print("Starting app {}...".format(app)) + # Run compose(args.app, "up --detach") asynchrounously for all apps, then exit(0) when all are finished + thread = threading.Thread(target=compose, args=(app, "up --detach")) + thread.start() + threads.append(thread) + joinThreads(threads) + + +def stopInstalled(): + # If userfile doen't exist, just do nothing + userData = {} + if os.path.isfile(userFile): + with open(userFile, "r") as f: + userData = json.load(f) + threads = [] + for app in userData["installedApps"]: + print("Stopping app {}...".format(app)) + # Run compose(args.app, "up --detach") asynchrounously for all apps, then exit(0) when all are finished + thread = threading.Thread( + target=compose, args=(app, "rm --force --stop")) + thread.start() + threads.append(thread) + joinThreads(threads) + +# Loads an app.yml and converts it to a docker-compose.yml + + +def getApp(appFile: str, appId: str): + with open(appFile, 'r') as f: + app = yaml.safe_load(f) + + if not "metadata" in app: + raise Exception("Error: Could not find metadata in " + appFile) + app["metadata"]["id"] = appId + + if('version' in app and str(app['version']) == "1"): + return createComposeConfigFromV1(app, nodeRoot) + else: + raise Exception("Error: Unsupported version of app.yml") + + +def compose(app, arguments): + # Runs a compose command in the app dir + # Before that, check if a docker-compose.yml exists in the app dir + composeFile = os.path.join(appsDir, app, "docker-compose.yml") + commonComposeFile = os.path.join(appSystemDir, "docker-compose.common.yml") + os.environ["APP_DOMAIN"] = subprocess.check_output( + "hostname -s 2>/dev/null || echo 'citadel'", shell=True).decode("utf-8") + ".local" + os.environ["APP_HIDDEN_SERVICE"] = subprocess.check_output("cat {} 2>/dev/null || echo 'notyetset.onion'".format( + os.path.join(nodeRoot, "tor", "data", "app-{}/hostname".format(app))), shell=True).decode("utf-8") + os.environ["APP_SEED"] = deriveEntropy("app-{}-seed".format(app)) + # Allow more app seeds, with random numbers from 1-5 assigned in a loop + for i in range(1, 6): + os.environ["APP_SEED_{}".format(i)] = deriveEntropy("app-{}-seed{}".format(app, i)) + os.environ["APP_DATA_DIR"] = os.path.join(appDataDir, app) + # Chown and chmod dataDir to have the owner 1000:1000 and the same permissions as appDir + subprocess.call("chown -R 1000:1000 {}".format(os.path.join(appDataDir, app)), shell=True) + os.chmod(os.path.join(appDataDir, app), os.stat(os.path.join(appDataDir, app)).st_mode) + os.environ["BITCOIN_DATA_DIR"] = os.path.join(nodeRoot, "bitcoin") + os.environ["LND_DATA_DIR"] = os.path.join(nodeRoot, "lnd") + # List all hidden services for an app and put their hostname in the environment + hiddenServices: List[str] = getAppHiddenServices(app) + for service in hiddenServices: + appHiddenServiceFile = os.path.join( + nodeRoot, "tor", "data", "app-{}-{}/hostname".format(app, service)) + os.environ["APP_HIDDEN_SERVICE_{}".format(service.upper().replace("-", "_"))] = subprocess.check_output("cat {} 2>/dev/null || echo 'notyetset.onion'".format( + appHiddenServiceFile), shell=True).decode("utf-8") + + if not os.path.isfile(composeFile): + print("Error: Could not find docker-compose.yml in " + app) + exit(1) + os.system( + "docker compose --env-file '{}' --project-name '{}' --file '{}' --file '{}' {}".format( + os.path.join(nodeRoot, ".env"), app, commonComposeFile, composeFile, arguments)) + + +def remove_readonly(func, path, _): + os.chmod(path, stat.S_IWRITE) + func(path) + + +def deleteData(app: str): + dataDir = os.path.join(appDataDir, app) + try: + shutil.rmtree(dataDir, onerror=remove_readonly) + except FileNotFoundError: + pass + + +def createDataDir(app: str): + dataDir = os.path.join(appDataDir, app) + appDir = os.path.join(appsDir, app) + if os.path.isdir(dataDir): + deleteData(app) + # Recursively copy everything from appDir to dataDir while excluding .gitignore + shutil.copytree(appDir, dataDir, symlinks=False, + ignore=shutil.ignore_patterns(".gitignore")) + # Chown and chmod dataDir to have the owner 1000:1000 and the same permissions as appDir + subprocess.call("chown -R 1000:1000 {}".format(os.path.join(appDataDir, app)), shell=True) + os.chmod(dataDir, os.stat(appDir).st_mode) + + +def setInstalled(app: str): + userData = getUserData() + if not "installedApps" in userData: + userData["installedApps"] = [] + userData["installedApps"].append(app) + userData["installedApps"] = list(set(userData["installedApps"])) + with open(userFile, "w") as f: + json.dump(userData, f) + + +def setRemoved(app: str): + userData = getUserData() + if not "installedApps" in userData: + return + userData["installedApps"] = list(set(userData["installedApps"])) + userData["installedApps"].remove(app) + with open(userFile, "w") as f: + json.dump(userData, f) + + +def getAppHiddenServices(app: str): + torDir = os.path.join(nodeRoot, "tor", "data") + # List all subdirectories of torDir which start with app-${APP}- + # but return them without the app-${APP}- prefix + results = [] + for subdir in os.listdir(torDir): + if subdir.startswith("app-{}-".format(app)): + results.append(subdir[len("app-{}-".format(app)):]) + return results + + +# Parse the sources.list repo file, which contains a list of sources in the format +# +# For every line, clone the repo to a temporary dir and checkout the branch +# Then, check that repos apps in the temporary dir/apps and for every app, +# overwrite the current app dir with the contents of the temporary dir/apps/app +# Also, keep a list of apps from every repo, a repo later in the file may not overwrite an app from a repo earlier in the file +def updateRepos(): + # Get the list of repos + repos = [] + with open(sourcesList) as f: + repos = f.readlines() + # For each repo, clone the repo to a temporary dir, checkout the branch, + # and overwrite the current app dir with the contents of the temporary dir/apps/app + alreadyInstalled = [] + for repo in repos: + repo = repo.strip() + if repo == "": + continue + # Also ignore comments + if repo.startswith("#"): + continue + # Split the repo into the git url and the branch + repo = repo.split(" ") + if len(repo) != 2: + print("Error: Invalid repo format in " + sourcesList) + exit(1) + gitUrl = repo[0] + branch = repo[1] + # Clone the repo to a temporary dir + tempDir = tempfile.mkdtemp() + print("Cloning the repository") + # Git clone with a depth of 1 to avoid cloning the entire repo + # Dont print anything to stdout, as we don't want to see the git clone output + subprocess.run("git clone --depth 1 {} {}".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) + # Overwrite the current app dir with the contents of the temporary dir/apps/app + for app in os.listdir(os.path.join(tempDir, "apps")): + # if the app is already installed, don't overwrite it + if app in alreadyInstalled: + continue + if os.path.isdir(os.path.join(appsDir, app)): + shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) + if os.path.isdir(os.path.join(tempDir, "apps", app)): + shutil.copytree(os.path.join(tempDir, "apps", app), os.path.join(appsDir, app), + symlinks=False, ignore=shutil.ignore_patterns(".gitignore")) + alreadyInstalled.append(app) + # Remove the temporary dir + shutil.rmtree(tempDir) diff --git a/app/lib/metadata.py b/app/lib/metadata.py new file mode 100644 index 0000000..d08e488 --- /dev/null +++ b/app/lib/metadata.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import os +import yaml + +from lib.composegenerator.v1.networking import getMainContainer +from lib.entropy import deriveEntropy + +def getUpdateContainer(app: dict): + if len(app['containers']) == 1: + return app['containers'][0] + else: + if 'updateContainer' in app['metadata']: + for container in app['containers']: + if container['name'] == app['metadata']['updateContainer']: + return container + return getMainContainer(app) + +# For every app, parse the app.yml in ../apps/[name] and +# check their metadata, and return a list of all app's metadata +# Also check the path and defaultPassword and set them to an empty string if they don't exist +# In addition, set id on the metadata to the name of the app +# Return a list of all app's metadata +def getAppRegistry(apps, app_path): + app_metadata = [] + for app in apps: + app_yml_path = os.path.join(app_path, app, 'app.yml') + if os.path.isfile(app_yml_path): + with open(app_yml_path, 'r') as f: + app_yml = yaml.safe_load(f.read()) + metadata: dict = app_yml['metadata'] + metadata['id'] = app + metadata['path'] = metadata.get('path', '') + metadata['defaultPassword'] = metadata.get('defaultPassword', '') + if metadata['defaultPassword'] == "$APP_SEED": + metadata['defaultPassword'] = deriveEntropy("app-{}-seed".format(app)) + if("mainContainer" in metadata): + metadata.pop("mainContainer") + app_metadata.append(metadata) + return app_metadata + +# Creates a registry with just the things we need in the update checker so we can remove registry.json from this repo. +# We need these properties: id, name, repo, version, nothing else. We don't need to check for the existence of these properties. +# app_yml['metadata'] may contain other properties, but we don't need them and we remove them from the registry. +def getSimpleAppRegistry(apps, app_path): + app_metadata = [] + for app in apps: + app_yml_path = os.path.join(app_path, app, 'app.yml') + if os.path.isfile(app_yml_path): + with open(app_yml_path, 'r') as f: + app_yml = yaml.safe_load(f.read()) + metadata = { + 'id': app, + 'name': app_yml['metadata']['name'], + 'repo': app_yml['metadata']['repo'], + 'version': app_yml['metadata']['version'] + } + if"version" in app_yml and str(app_yml["version"]) == "1": + updateContainer = getUpdateContainer(app_yml) + metadata['image'] = updateContainer['image'].split(":")[0] + app_metadata.append(metadata) + return app_metadata diff --git a/app/lib/validate.py b/app/lib/validate.py new file mode 100644 index 0000000..fa8d5a3 --- /dev/null +++ b/app/lib/validate.py @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import os +import yaml +from jsonschema import validate +import json + + +# Validates app data +# Returns true if valid, false otherwise +scriptDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..") +def validateApp(app: dict): + with open(os.path.join(scriptDir, 'app-standard-v1.json'), 'r') as f: + schemaVersion1 = json.loads(f.read()) + + if('version' in app and str(app['version']) == "1"): + try: + validate(app, schemaVersion1) + return True + # Catch and log any errors, and return false + except Exception as e: + print(e) + return False + else: + print("Unsupported app version") + return False + + +# Read in an app.yml file and pass it to the validation function +# Returns true if valid, false otherwise +def validateAppFile(file: str): + with open(file, 'r') as f: + return validateApp(yaml.safe_load(f)) + +# Returns all dirs in the dir +def findApps(dir: str): + apps = [] + # Only get directories in the dir, but not recursively + for root, dirs, files in os.walk(dir, topdown=False): + for name in dirs: + app_dir = os.path.join(root, name) + if os.path.isfile(os.path.join(app_dir, "app.yml")) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml")): + apps.append(name) + return apps + + +# Lists all folders in a directory and checks if they are valid +# A folder is valid if it contains an app.yml file +# A folder is invalid if it doesn't contain an app.yml file +def findAndValidateApps(dir: str): + apps = [] + app_data = {} + for root, dirs, files in os.walk(dir, topdown=False): + for name in dirs: + app_dir = os.path.join(root, name) + if os.path.isfile(os.path.join(app_dir, "app.yml")): + apps.append(name) + # Read the app.yml and append it to app_data + with open(os.path.join(app_dir, "app.yml"), 'r') as f: + app_data[name] = yaml.safe_load(f) + # Now validate all the apps using the validateAppFile function by passing the app.yml as an argument to it, if an app is invalid, remove it from the list + for app in apps: + appyml = app_data[app] + if not validateApp(appyml): + apps.remove(app) + print("Warning: App {} is invalid".format(app)) + # Skip to the next iteration of the loop + continue + # More security validation + should_continue=True + if appyml['metadata']['dependencies']: + for dependency in appyml['metadata']['dependencies']: + if dependency not in apps and dependency not in ["bitcoind", "lnd", "electrum"]: + print("WARNING: App '{}' has unknown dependency '{}'".format(app, dependency)) + apps.remove(app) + should_continue=False + if dependency == app: + print("WARNING: App '{}' depends on itself".format(app)) + apps.remove(app) + should_continue=False + if not should_continue: + continue + for container in appyml['containers']: + if 'permissions' in container: + for permission in container['permissions']: + if permission not in appyml['metadata']['dependencies'] and permission not in ["root", "hw"]: + print("WARNING: App {}'s container '{}' requires the '{}' permission, but the app doesn't list it in it's dependencies".format(app, container['name'], permission)) + apps.remove(app) + # Skip to the next iteration of the loop + continue + return apps diff --git a/bin/bitcoin-cli b/bin/bitcoin-cli new file mode 100755 index 0000000..c1c3f59 --- /dev/null +++ b/bin/bitcoin-cli @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# SPDX-FileCopyrightText: 2021 https://github.com/o3o3o +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/..)" + +result=$(docker compose \ + --file "${CITADEL_ROOT}/docker-compose.yml" \ + --env-file "${CITADEL_ROOT}/.env" \ + exec bitcoin bitcoin-cli "$@") + +# We need to echo with quotes to preserve output formatting +echo "$result" diff --git a/bin/lncli b/bin/lncli new file mode 100755 index 0000000..4f90a7a --- /dev/null +++ b/bin/lncli @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# SPDX-FileCopyrightText: 2021 https://github.com/o3o3o +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/..)" + +result=$(docker compose \ + --file "${CITADEL_ROOT}/docker-compose.yml" \ + --env-file "${CITADEL_ROOT}/.env" \ + exec lnd lncli "$@") + +# We need to echo with quotes to preserve output formatting +echo "$result" diff --git a/db/.gitkeep b/db/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/db/citadel-seed/.gitkeep b/db/citadel-seed/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e7b2e31 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,244 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later +version: '3.8' +services: + tor: + container_name: tor + image: lncm/tor:0.4.6.7@sha256:472c8d1265679e7cfd641edcbc44ec2fa0e500f6929bd8dc1f4811feffcfefaa + user: toruser + restart: on-failure + volumes: + - ${PWD}/tor/torrc-core:/etc/tor/torrc + - ${PWD}/tor/data:/var/lib/tor/ + ports: + - 127.0.0.1:$TOR_PROXY_PORT:$TOR_PROXY_PORT + networks: + default: + ipv4_address: $TOR_PROXY_IP + app_tor: + container_name: app_tor + image: lncm/tor:0.4.6.7@sha256:472c8d1265679e7cfd641edcbc44ec2fa0e500f6929bd8dc1f4811feffcfefaa + user: toruser + restart: on-failure + volumes: + - ${PWD}/tor/torrc-apps:/etc/tor/torrc + - ${PWD}/tor/data:/var/lib/tor/ + networks: + default: + ipv4_address: $APPS_TOR_IP + app_2_tor: + container_name: app_2_tor + image: lncm/tor:0.4.6.7@sha256:472c8d1265679e7cfd641edcbc44ec2fa0e500f6929bd8dc1f4811feffcfefaa + user: toruser + restart: on-failure + volumes: + - ${PWD}/tor/torrc-apps-2:/etc/tor/torrc + - ${PWD}/tor/data:/var/lib/tor/ + networks: + default: + ipv4_address: $APPS_2_TOR_IP + app_3_tor: + container_name: app_3_tor + image: lncm/tor:0.4.5.7@sha256:a83e0d9fd1a35adf025f2f34237ec1810e2a59765988dce1dfb222ca8ef6583c + user: toruser + restart: on-failure + volumes: + - ${PWD}/tor/torrc-apps-3:/etc/tor/torrc + - ${PWD}/tor/data:/var/lib/tor/ + networks: + default: + ipv4_address: $APPS_3_TOR_IP + nginx: + container_name: nginx + image: nginx:1.21.3@sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36 + depends_on: + - dashboard + - manager + volumes: + - ${PWD}/nginx:/etc/nginx + restart: on-failure + stop_grace_period: 30s + ports: + - ${NGINX_PORT}:80 + networks: + default: + ipv4_address: $NGINX_IP + bitcoin: + container_name: bitcoin + image: lncm/bitcoind:v22.0@sha256:37a1adb29b3abc9f972f0d981f45e41e5fca2e22816a023faa9fdc0084aa4507 + depends_on: + - tor + - manager + - nginx + volumes: + - ${PWD}/bitcoin:/data/.bitcoin + restart: on-failure + stop_grace_period: 15m30s + ports: + - $BITCOIN_P2P_PORT:$BITCOIN_P2P_PORT + networks: + default: + ipv4_address: $BITCOIN_IP + lnd: + container_name: lnd + image: lightninglabs/lnd:v0.13.3-beta@sha256:b8f96d4d7fb9dcd349542240a6bff1ca0170715a16e6d79b0e9188e34ea18471 + user: 1000:1000 + depends_on: + - tor + - manager + volumes: + - ${PWD}/lnd:/data/.lnd + - ${PWD}/walletpassword:/walletpassword + environment: + HOME: /data + restart: on-failure + stop_grace_period: 5m30s + ports: + - 9735:9735 + - $LND_REST_PORT:$LND_REST_PORT + - $LND_GRPC_PORT:$LND_GRPC_PORT + networks: + default: + ipv4_address: $LND_IP + dashboard: + container_name: dashboard + image: runcitadel/dashboard:main@sha256:2a21cda0dd64883d7511f2f7056ca39497c9203d8a0dc6ea45f5dda590a12559 + restart: on-failure + stop_grace_period: 1m30s + networks: + default: + ipv4_address: $DASHBOARD_IP + manager: + container_name: manager + image: runcitadel/manager:main@sha256:2d7c01c3e6369d945ec7817ec3c500ecf824c8baf0fb1e1ea3d0507002597af0 + depends_on: + - tor + restart: on-failure + init: true + stop_grace_period: 5m30s + volumes: + - ${PWD}:${PWD} + - ${PWD}/info.json:/info.json + - ${PWD}/db:/db + - ${PWD}/events/signals:/signals + - ${PWD}/apps:/apps + - ${PWD}/lnd:/lnd:ro + - ${PWD}/statuses:/statuses + - ${PWD}/tor/data:/var/lib/tor/ + - /var/run/docker.sock:/var/run/docker.sock + - ${DOCKER_BINARY:-/usr/bin/docker}:/usr/bin/docker + - jwt-public-key:/jwt-public-key + - jwt-private-key:/jwt-private-key + environment: + PORT: '3006' + USER_PASSWORD_FILE: /db/user.json + JWT_PUBLIC_KEY_FILE: /jwt-public-key/jwt.pem + JWT_PRIVATE_KEY_FILE: /jwt-private-key/jwt.key + JWT_EXPIRATION: '3600' + DOCKER_COMPOSE_DIRECTORY: $PWD + DEVICE_HOSTS: ${DEVICE_HOSTS:-"http://citadel.local"} + DEVICE_HOSTNAME: ${DEVICE_HOSTNAME:-""} + MIDDLEWARE_API_URL: http://$MIDDLEWARE_IP + SEED_FILE: /db/citadel-seed/seed + DASHBOARD_HIDDEN_SERVICE_FILE: /var/lib/tor/web/hostname + BITCOIN_P2P_HIDDEN_SERVICE_FILE: /var/lib/tor/bitcoin-p2p/hostname + BITCOIN_P2P_PORT: $BITCOIN_P2P_PORT + BITCOIN_RPC_HIDDEN_SERVICE_FILE: /var/lib/tor/bitcoin-rpc/hostname + BITCOIN_RPC_PORT: $BITCOIN_RPC_PORT + BITCOIN_RPC_USER: $BITCOIN_RPC_USER + BITCOIN_RPC_PASSWORD: $BITCOIN_RPC_PASS + LND_REST_HIDDEN_SERVICE_FILE: /var/lib/tor/lnd-rest/hostname + LND_GRPC_HIDDEN_SERVICE_FILE: /var/lib/tor/lnd-grpc/hostname + LND_CERT_FILE: /lnd/tls.cert + LND_ADMIN_MACAROON_FILE: /lnd/data/chain/bitcoin/${BITCOIN_NETWORK}/admin.macaroon + SHUTDOWN_SIGNAL_FILE: /signals/shutdown + REBOOT_SIGNAL_FILE: /signals/reboot + GITHUB_REPO: runcitadel/core + GITHUB_BRANCH: dev + VERSION_FILE: /info.json + UPDATE_STATUS_FILE: /statuses/update-status.json + UPDATE_SIGNAL_FILE: /signals/update + UPDATE_LOCK_FILE: /statuses/update-in-progress + BACKUP_STATUS_FILE: /statuses/backup-status.json + DEBUG_STATUS_FILE: /statuses/debug-status.json + TOR_PROXY_IP: ${TOR_PROXY_IP} + TOR_PROXY_PORT: ${TOR_PROXY_PORT} + TOR_HIDDEN_SERVICE_DIR: /var/lib/tor + IS_CITADEL_OS: ${IS_CITADEL_OS:-"false"} + networks: + default: + ipv4_address: $MANAGER_IP + middleware: + container_name: middleware + image: runcitadel/middleware:main@sha256:26451df6882c310d562b6926266ae1a4344c712c9a898d4550987de6f8ba4e44 + depends_on: + - manager + - bitcoin + - lnd + command: + - ./wait-for-node-manager.sh + - $MANAGER_IP + - npm + - start + restart: on-failure + volumes: + - ${PWD}/lnd:/lnd + - jwt-public-key:/jwt-public-key + environment: + PORT: '3005' + BITCOIN_HOST: $BITCOIN_IP + RPC_PORT: $BITCOIN_RPC_PORT + RPC_USER: $BITCOIN_RPC_USER + RPC_PASSWORD: $BITCOIN_RPC_PASS + LND_NETWORK: $BITCOIN_NETWORK + LND_HOST: ${LND_IP} + JWT_PUBLIC_KEY_FILE: /jwt-public-key/jwt.pem + DEVICE_HOSTS: ${DEVICE_HOSTS:-"http://citadel.local"} + networks: + default: + ipv4_address: $MIDDLEWARE_IP + neutrino-switcher: + container_name: neutrino-switcher + image: lncm/neutrino-switcher:1.0.5@sha256:3ddf58c5599ba22db8414f2694bfeeba086455d4a19b4955b26c3ae5e967d42a + depends_on: + - bitcoin + - lnd + restart: on-failure + volumes: + - ${PWD}/lnd:/lnd + - ${PWD}/statuses:/statuses + - /var/run/docker.sock:/var/run/docker.sock + environment: + JSONRPCURL: http://${BITCOIN_IP}:${BITCOIN_RPC_PORT} + RPCUSER: $BITCOIN_RPC_USER + RPCPASS: $BITCOIN_RPC_PASS + LND_CONTAINER_NAME: lnd + SLEEPTIME: 3600 + networks: + default: + ipv4_address: $NEUTRINO_SWITCHER_IP + electrs: + container_name: electrs + image: ghcr.io/runcitadel/electrs:main@sha256:86705bd425b9b20d0b83d8ef5673cee261766b5a50bcfa8e95ebfec2e5adfcae + working_dir: /data + volumes: + - ${PWD}/bitcoin:/bitcoin:ro + - ${PWD}/electrs:/data + restart: on-failure + stop_grace_period: 5m + ports: + - $ELECTRUM_PORT:$ELECTRUM_PORT + networks: + default: + ipv4_address: $ELECTRUM_IP +networks: + default: + name: citadel_main_network + ipam: + driver: default + config: + - subnet: $NETWORK_IP/24 +volumes: + jwt-public-key: null + jwt-private-key: null diff --git a/events/triggers/app b/events/triggers/app new file mode 100755 index 0000000..a074ef6 --- /dev/null +++ b/events/triggers/app @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +signal="${1}" +command=${signal%%"-"*} +app=${signal#*"-"} + +"${CITADEL_ROOT}/app/app-manager.py" "${command}" "${app}" diff --git a/events/triggers/backup b/events/triggers/backup new file mode 100755 index 0000000..f7fac2f --- /dev/null +++ b/events/triggers/backup @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +"${CITADEL_ROOT}/scripts/backup/backup" diff --git a/events/triggers/change-password b/events/triggers/change-password new file mode 100755 index 0000000..2bc7776 --- /dev/null +++ b/events/triggers/change-password @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +"${CITADEL_ROOT}/scripts/citadel-os/change-password" diff --git a/events/triggers/debug b/events/triggers/debug new file mode 100755 index 0000000..f0bca69 --- /dev/null +++ b/events/triggers/debug @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +NODE_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" +RESULT_FILE="${NODE_ROOT}/statuses/debug-status.json" +cat < "${RESULT_FILE}" +{"status": "processing"} +EOF + +escape_for_json () { + jq --null-input --raw-input 'reduce inputs as $line (""; . += "\($line)\n")' +} + +debug_json_string=$("${NODE_ROOT}/scripts/debug" --no-colors --no-instructions --filter | escape_for_json) +dmesg_json_string=$(dmesg | escape_for_json) + +cat < "${RESULT_FILE}" +{ + "status": "success", + "debug": ${debug_json_string}, + "dmesg": ${dmesg_json_string} +} +EOF diff --git a/events/triggers/reboot b/events/triggers/reboot new file mode 100755 index 0000000..eb7e119 --- /dev/null +++ b/events/triggers/reboot @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +./scripts/stop +shutdown -r now diff --git a/events/triggers/shutdown b/events/triggers/shutdown new file mode 100755 index 0000000..ff99315 --- /dev/null +++ b/events/triggers/shutdown @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +./scripts/stop +shutdown -h now diff --git a/events/triggers/update b/events/triggers/update new file mode 100755 index 0000000..b61b76c --- /dev/null +++ b/events/triggers/update @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +"${CITADEL_ROOT}/scripts/update/update" --ota diff --git a/info.json b/info.json new file mode 100644 index 0000000..68ea16c --- /dev/null +++ b/info.json @@ -0,0 +1,6 @@ +{ + "version": "0.4.15", + "name": "Citadel 0.4.15", + "requires": ">=0.4.14", + "notes": "Unless you are beta testing Citadel OS, you should never see this update (Citadel 0.4.15) or this message. If you do, please DO NOT UPDATE! Instead, contact the Citadel developers. (Beta testers too, please)." +} diff --git a/info.json.license b/info.json.license new file mode 100644 index 0000000..cba21c8 --- /dev/null +++ b/info.json.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/karen b/karen new file mode 100755 index 0000000..9abea25 --- /dev/null +++ b/karen @@ -0,0 +1,80 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors. +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# karen watches for signals and executes triggers in the events dir +# karen gets triggered a lot + +check_root () { + if [[ $UID != 0 ]]; then + echo "Error: This script must be run as root." + echo "Can I speak to a manager please?" + exit 1 + fi +} + +check_if_not_already_running() { + if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep + then + echo "karen is already running" + exit 1 + fi +} + +check_dependencies () { + for cmd in "$@"; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_root + +check_if_not_already_running + +check_dependencies fswatch readlink dirname + +if [[ -n "$1" ]]; then + root_dir="$(readlink -f $1)" +else + root_dir="$(dirname $(readlink -f ${BASH_SOURCE[0]}))/events" +fi +signal_dir="$root_dir/signals" +trigger_dir="$root_dir/triggers" + +if [[ ! -d "$root_dir" ]]; then + echo "Root dir does not exist '$root_dir'" + exit 1 +fi + +echo "karen will start in 30 seconds" +sleep 30 +echo "karen is running in $root_dir" +fswatch -0 --event=AttributeModified $signal_dir | while read -d "" event; do + signal="${event#"$signal_dir"}" + signal="${signal#"/"}" + trigger="$trigger_dir/$signal" + args="" + + echo "Got signal: $signal" + + # If the signal starts wih app-, the trigger is "$trigger_dir/app" + # and the args are the rest of the signal + if [[ "$signal" =~ ^app- ]]; then + trigger="$trigger_dir/app" + args="${signal#"app-"}" + fi + if test -x "$trigger"; then + echo "karen is getting triggered!" + if [[ ! -f "statuses/update-in-progress" ]]; then + "$trigger" $args & + fi + else + echo "No trigger found" + fi +done diff --git a/lnd/.gitkeep b/lnd/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/logs/.gitkeep b/logs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/scripts/app b/scripts/app new file mode 100755 index 0000000..2911a31 --- /dev/null +++ b/scripts/app @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +NODE_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/.." + +"${NODE_ROOT}/app/app-manager.py" "$@" diff --git a/scripts/backup/README.md b/scripts/backup/README.md new file mode 100644 index 0000000..c89c092 --- /dev/null +++ b/scripts/backup/README.md @@ -0,0 +1,20 @@ + + +# Automatic Encrypted Backups + +The backups are encrypted client side before being uploaded over Tor and are padded with random data. Backups are made immediately as soon as the channel state changes. However, Umbrel also makes decoy backups at random intervals to prevent timing-analysis attacks. + +These features combined ensure that the backup server doesn't learn any sensitive information about the user's Umbrel. + +- The IP address of user is hidden due to Tor. +- User's channel data are encrypted client side with a key only known to the Umbrel device. +- Random interval decoy backups ensure the server can't correlate backup activity with channel state changes on the Lightning network and correlate a backup ID with a channel pubkey. +- Random padding obscures if the backup size has increased/decreased or remains unchanged due to it being a decoy. + +Due to the key/id being deterministically derived from the Umbrel seed, all that's needed to fully recover an Umbrel is the mnemonic seed phrase. Upon recovery the device can automatically regenerate the same backup id/encryption key, request the latest backup from the backup server, decrypt it, and restore the user's settings and Lightning network channel data. + +There is currently no way to disable backups or recover from them in the dashboard yet. Both of these features will be introduced in the coming updates. diff --git a/scripts/backup/backup b/scripts/backup/backup new file mode 100755 index 0000000..a6696db --- /dev/null +++ b/scripts/backup/backup @@ -0,0 +1,170 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" +BACKUP_ROOT="${CITADEL_ROOT}/.backup/$RANDOM" +BACKUP_FOLDER_NAME="backup" +BACKUP_FOLDER_PATH="${BACKUP_ROOT}/${BACKUP_FOLDER_NAME}" +BACKUP_FILE="${BACKUP_ROOT}/backup.tar.gz.pgp" +BACKUP_STATUS_FILE="${CITADEL_ROOT}/statuses/backup-status.json" + +check_dependencies () { + for cmd in "$@"; do + if ! command -v "$cmd" >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_dependencies openssl tar gpg shuf curl + +# Deterministically derives 128 bits of cryptographically secure entropy +derive_entropy () { + identifier="${1}" + umbrel_seed=$(cat "${CITADEL_ROOT}/db/citadel-seed/seed") || true + + if [[ -z "$umbrel_seed" ]] || [[ -z "$identifier" ]]; then + >&2 echo "Missing derivation parameter, this is unsafe, exiting." + exit 1 + fi + + # We need `sed 's/^.* //'` to trim the "(stdin)= " prefix from some versions of openssl + printf "%s" "${identifier}" | openssl dgst -sha256 -hmac "${umbrel_seed}" | sed 's/^.* //' +} + +[[ -f "${CITADEL_ROOT}/.env" ]] && source "${CITADEL_ROOT}/.env" +BITCOIN_NETWORK=${BITCOIN_NETWORK:-mainnet} + +echo "Deriving keys..." + +backup_id=$(derive_entropy "umbrel_backup_id") +encryption_key=$(derive_entropy "umbrel_backup_encryption_key") + +echo "Creating backup..." + +if [[ ! -f "${CITADEL_ROOT}/lnd/data/chain/bitcoin/${BITCOIN_NETWORK}/channel.backup" ]]; then + echo "No channel.backup file found, skipping backup..." + exit 1 +fi + +mkdir -p "${BACKUP_FOLDER_PATH}" + +cp --archive "${CITADEL_ROOT}/lnd/data/chain/bitcoin/${BITCOIN_NETWORK}/channel.backup" "${BACKUP_FOLDER_PATH}/channel.backup" + +# We want to back up user settings too, however we currently store the encrypted +# mnemonic in this file which is not safe to backup remotely. +# Uncomment this in the future once we've ensured there's no critical data in +# this file. +# cp --archive "${CITADEL_ROOT}/db/user.json" "${BACKUP_FOLDER_PATH}/user.json" + +echo "Adding random padding..." + +# Up to 10KB of random binary data +# This prevents the server from being able to tell if the backup has increased +# decreased or stayed the sme size. Combined with random interval decoy backups +# this makes a (already very difficult) timing analysis attack to correlate backup +# activity with channel state changes practically impossible. +padding="$(shuf -i 0-10240 -n 1)" +dd if=/dev/urandom bs="${padding}" count=1 > "${BACKUP_FOLDER_PATH}/.padding" + +echo "Creating encrypted tarball..." + +tar \ + --create \ + --gzip \ + --verbose \ + --directory "${BACKUP_FOLDER_PATH}/.." \ + "${BACKUP_FOLDER_NAME}" \ + | gpg \ + --batch \ + --symmetric \ + --cipher-algo AES256 \ + --passphrase "${encryption_key}" \ + --output "${BACKUP_FILE}" + +# To decrypt: +# cat "${BACKUP_FILE}" | gpg \ +# --batch \ +# --decrypt \ +# --passphrase "${encryption_key}" \ +# | tar \ +# --extract \ +# --verbose \ +# --gzip + +# Check if a file exists on Firebase by checking if +# "https://firebasestorage.googleapis.com/v0/b/citadel-user-backups.appspot.com/o/backups%2F?alt=media" +# returns a 200 response code. +# +check_if_exists() { + curl -s -o /dev/null -w "%{http_code}" \ + -X GET \ + "https://firebasestorage.googleapis.com/v0/b/citadel-user-backups.appspot.com/o/backups%2F${1}?alt=media" +} +} +# Upload a file to Firebase Cloud Storage by uloading its name + a random ID. +# Before uploading, we need to check if a file with the same name already exists, and if it does, change the random ID. +# For example, if we want to upload a file named "" with the content AA, we'd use this command to upload: +# curl -X POST "https://firebasestorage.googleapis.com/v0/b/citadel-user-backups.appspot.com/o/backups%2F?alt=media" -d "AA" -H "Content-Type: text/plain" +# To check if a file exists, we can check if this endpoint returns an error 404: +# curl "https://firebasestorage.googleapis.com/v0/b/citadel-user-backups.appspot.com/o/backups%2F?alt=media" +# To download a file, we can the same endpoint +upload_file() { + local file_to_send="${1}" + local file_name="${2}" + # A random ID to avoid collisions + local random_id="$(tr -dc A-Za-z0-9 /dev/null +} + +if [[ $BITCOIN_NETWORK == "testnet" ]]; then +rm -rf "${BACKUP_ROOT}" +cat < ${BACKUP_STATUS_FILE} +{"status": "skipped", "timestamp": $(date +%s000)} +EOF + exit +fi +if [[ $BITCOIN_NETWORK == "regtest" ]]; then +rm -rf "${BACKUP_ROOT}" +cat < ${BACKUP_STATUS_FILE} +{"status": "skipped", "timestamp": $(date +%s000)} +EOF + exit +fi + +echo "Uploading backup..." +if upload_file "${BACKUP_FILE}" "${backup_id}"; then + status="success" +else + status="failed" +fi +echo + +rm -rf "${BACKUP_ROOT}" + +# Update status file +cat < ${BACKUP_STATUS_FILE} +{"status": "${status}", "timestamp": $(date +%s000)} +EOF + +echo "=============================" +echo "====== Backup ${status} =======" +echo "=============================" + +exit 0 diff --git a/scripts/backup/decoy-trigger b/scripts/backup/decoy-trigger new file mode 100755 index 0000000..93a5ef7 --- /dev/null +++ b/scripts/backup/decoy-trigger @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" +MAX_BACKUP_INTERVAL_IN_HOURS="12" + +check_if_not_already_running() { + if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep + then + echo "decoy trigger is already running" + exit 1 + fi +} + +check_dependencies () { + for cmd in "$@"; do + if ! command -v "$cmd" >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_if_not_already_running + +check_dependencies shuf + +main () { + while true; do + minutes_in_seconds="60" + hours_in_seconds="$((60 * ${minutes_in_seconds}))" + max_interval="$((${MAX_BACKUP_INTERVAL_IN_HOURS} * ${hours_in_seconds}))" + delay="$(shuf -i 0-${max_interval} -n 1)" + echo "Sleeping for ${delay} seconds..." + sleep $delay + echo "Triggering decoy backup..." + touch "${CITADEL_ROOT}/events/signals/backup" + done +} + +main diff --git a/scripts/backup/monitor b/scripts/backup/monitor new file mode 100755 index 0000000..67ac8fb --- /dev/null +++ b/scripts/backup/monitor @@ -0,0 +1,73 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +check_root () { + if [[ $UID != 0 ]]; then + echo "Error: This script must be run as root." + exit 1 + fi +} + +check_if_not_already_running() { + if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep + then + echo "backup monitor is already running" + exit 1 + fi +} + +check_dependencies () { + for cmd in "$@"; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_root + +check_if_not_already_running + +check_dependencies fswatch readlink dirname + +CITADEL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/../.." + +monitor_file () { + local file_path="${1}" + echo "Monitoring $file_path" + echo + + if [[ ! -e "${file_path}" ]]; then + echo "$file_path doesn't exist, waiting for it to be created..." + echo + until [[ -e "${file_path}" ]]; do + sleep 1 + done + echo "$file_path created! Triggering backup..." + touch "${CITADEL_ROOT}/events/signals/backup" + fi + + fswatch -0 --event Updated $file_path | xargs -0 -n 1 -I {} touch "${CITADEL_ROOT}/events/signals/backup" +} + +if [[ ! -d "${CITADEL_ROOT}" ]]; then + echo "Root dir does not exist '$CITADEL_ROOT'" + exit 1 +fi + +[[ -f "${CITADEL_ROOT}/.env" ]] && source "${CITADEL_ROOT}/.env" +BITCOIN_NETWORK=${BITCOIN_NETWORK:-mainnet} + +# Monitor LND channel.backup +monitor_file "${CITADEL_ROOT}/lnd/data/chain/bitcoin/${BITCOIN_NETWORK}/channel.backup" & + +# Monitor db/user.json +# We want to back up user settings too, however we currently store the encrypted +# mnemonic in this file which is not safe to backup remotely. +# Uncomment this in the future once we've ensured there's no critical data in +# this file. +# monitor_file "${CITADEL_ROOT}/db/user.json" & diff --git a/scripts/citadel-os/change-password b/scripts/citadel-os/change-password new file mode 100755 index 0000000..73b9544 --- /dev/null +++ b/scripts/citadel-os/change-password @@ -0,0 +1,39 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" +PASSWORD_FILE="${CITADEL_ROOT}/statuses/password" + +check_root () { + if [[ $UID != 0 ]]; then + echo "This script must be run as root" + exit 1 + fi +} + +check_citadel_os () { + [[ -f "/etc/default/citadel" ]] && source "/etc/default/citadel" + if [[ -z "${CITADEL_OS:-}" ]]; then + echo "This script must only be run on Citadel OS" + exit 1 + fi +} + +password="$(cat ${PASSWORD_FILE})" +echo "false" > "${PASSWORD_FILE}" + +check_root +check_citadel_os + +if [[ "${password}" == "" ]] || [[ "${password}" == "false" ]] || [[ "${password}" == "true" ]]; then + echo "Password not set in status file: \"${PASSWORD_FILE}\"" + exit 1 +fi + +echo -e "${password}\n${password}" | passwd citadel +echo "true" > "${PASSWORD_FILE}" diff --git a/scripts/citadel-os/citadel-details b/scripts/citadel-os/citadel-details new file mode 100755 index 0000000..baf9825 --- /dev/null +++ b/scripts/citadel-os/citadel-details @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import sys +import os +import time +import subprocess +import io +import qrcode + +def create_qr(data): + output_buffer = io.TextIOWrapper(io.BytesIO(), sys.stdout.encoding) + + qr = qrcode.QRCode(border=0, error_correction=qrcode.constants.ERROR_CORRECT_Q) + qr.add_data(data) + qr.print_ascii(out=output_buffer) + + output_buffer.seek(0) + qr_ascii = output_buffer.read().strip() + + return qr_ascii + +def read_file_when_available(file_path, timeout): + start = time.time() + while not os.path.exists(file_path): + if (time.time() - start) > timeout: + return False + time.sleep(1) + + with open(file_path, "r") as file: + file_contents = file.read() + + return file_contents + +def run(command): + result = subprocess.run(command, stdout=subprocess.PIPE) + return result.stdout.decode('utf-8').rstrip("\n") + +def main(): + timeout = 30 + tor_hostname_file = "/home/citadel/citadel/tor/data/web/hostname" + tor_hostname = read_file_when_available(tor_hostname_file, timeout) + + ip = run(['hostname', '-I']).split(" ")[0] + + if not tor_hostname or not ip: + print("Couldn't get connection details") + return + + tor_hostname_qr_ascii = create_qr(tor_hostname.strip()) + + connection_details = f""" + + +{tor_hostname_qr_ascii} + + Your Citadel is up and running at: + + http://citadel.local + http://{ip} + http://{tor_hostname} + """ + print(connection_details) + +main() diff --git a/scripts/citadel-os/external-storage/monitor b/scripts/citadel-os/external-storage/monitor new file mode 100755 index 0000000..5653c4a --- /dev/null +++ b/scripts/citadel-os/external-storage/monitor @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../../..)" +block_device="${1}" +mount_point="${2}" + +check_if_not_already_running() { + if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep + then + echo "storage monitor is already running" + exit 1 + fi +} + +main () { + check_if_not_already_running + + while true; do + if ! [[ -e "/dev/${block_device}" ]]; then + echo "Mounted block device no longer exists!" + break + fi + + if ! grep --quiet " ${mount_point} " /proc/mounts; then + echo "External storage is no longer mounted!" + break + fi + + if grep " ${mount_point} " /proc/mounts | grep --quiet '[ ,]ro[ ,]'; then + echo "External storage is mounted as read only!" + break + fi + + if ! df -h "${CITADEL_ROOT}" | grep --quiet "/dev/${block_device}"; then + echo "Citadel root is no longer bind mounted to external storage!" + break + fi + + sleep 1 + done + + echo "Stopping Citadel due to failed storage device check..." + docker kill $(docker ps -aq) +} + +main diff --git a/scripts/citadel-os/external-storage/mount b/scripts/citadel-os/external-storage/mount new file mode 100755 index 0000000..fca3105 --- /dev/null +++ b/scripts/citadel-os/external-storage/mount @@ -0,0 +1,299 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +# This script will: +# - Look for external storage devices +# - Check if they contain an Citadel install +# - If yes +# - - Mount it +# - If no +# - - Format it +# - - Mount it +# - - Install Citadel on it +# - Bind mount the external installation on top of the local installation + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../../..)" +MOUNT_POINT="/mnt/data" +EXTERNAL_UMBREL_ROOT="${MOUNT_POINT}/umbrel" +EXTERNAL_CITADEL_ROOT="${MOUNT_POINT}/citadel" +DOCKER_DIR="/var/lib/docker" +EXTERNAL_DOCKER_DIR="${MOUNT_POINT}/docker" +SWAP_DIR="/swap" +SWAP_FILE="${SWAP_DIR}/swapfile" +SD_MOUNT_POINT="/sd-root" +SD_CITADEL_ROOT="${SD_MOUNT_POINT}${CITADEL_ROOT}" + +check_root () { + if [[ $UID != 0 ]]; then + echo "This script must be run as root" + exit 1 + fi +} + +check_dependencies () { + for cmd in "$@"; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +# Returns a list of block device paths +list_block_devices () { + # We need to run sync here to make sure the filesystem is reflecting the + # the latest changes in /sys/block/* + sync + # We use "2>/dev/null || true" to swallow errors if there are + # no block devices. In that case the function just returns nothing + # instead of an error which is what we want. + # + # sed 's!.*/!!' is to return the device path so we get sda (or nvme0n1) + # instead of /sys/block/sda (or /sys/block/nvme0n1) + (ls -d /sys/block/sd* /sys/block/nvme*n* 2>/dev/null || true) | sed 's!.*/!!' +} + +# Returns the vendor and model name of a block device +get_block_device_model () { + device="${1}" + # We use "2>/dev/null || true" to swallow errors if there is + # no vendor/device recognized. In that case the function just returns nothing + # instead of an error which is what we want. + vendor=$(cat "/sys/block/${device}/device/vendor" 2>/dev/null || true) + model=$(cat "/sys/block/${device}/device/model" 2>/dev/null || true) + + # We echo in a subshell without quotes to strip surrounding whitespace + echo "$(echo $vendor) $(echo $model)" +} + +is_partition_ext4 () { + partition_path="${1}" + # We need to run sync here to make sure the filesystem is reflecting the + # the latest changes in /dev/* + sync + blkid -o value -s TYPE "${partition_path}" | grep --quiet '^ext4$' +} + +# Wipes a block device and reformats it with a single EXT4 partition +format_block_device () { + device="${1}" + device_path="/dev/${device}" + if [[ $block_device != sd* ]]; then + echo "SSD device" + partition_path="${block_device_path}p1" + else + partition_path="${block_device_path}1" + fi + wipefs -a "${device_path}" + parted --script "${device_path}" mklabel gpt + parted --script "${device_path}" mkpart primary ext4 0% 100% + # We need to run sync here to make sure the filesystem is reflecting the + # the latest changes in /dev/* + sync + mkfs.ext4 -F -L citadel "${partition_path}" +} + +# Mounts the device given in the first argument at $MOUNT_POINT +mount_partition () { + partition_path="${1}" + mkdir -p "${MOUNT_POINT}" + mount "${partition_path}" "${MOUNT_POINT}" +} + +# Unmounts $MOUNT_POINT +unmount_partition () { + umount "${MOUNT_POINT}" +} + +# This disables UAS for all USB devices, then rebinds them +disable_uas () { + usb_quirks=$(lsusb | awk '{print $6":u"}' | tr '\n' ',' | sed 's/,$//') + echo -n "${usb_quirks}" > /sys/module/usb_storage/parameters/quirks + + echo "Rebinding USB drivers..." + for i in /sys/bus/pci/drivers/[uoex]hci_hcd/*:*; do + [[ -e "$i" ]] || continue; + echo "${i##*/}" > "${i%/*}/unbind" + echo "${i##*/}" > "${i%/*}/bind" + done +} + +# Formats and sets up a new device +setup_new_device () { + block_device="${1}" + partition_path="${2}" + + echo "Formatting device..." + format_block_device $block_device + + echo "Mounting partition..." + mount_partition "${partition_path}" + + echo "Copying Citadel install to external storage..." + mkdir -p "${EXTERNAL_CITADEL_ROOT}" + cp --recursive \ + --archive \ + --no-target-directory \ + "${CITADEL_ROOT}" "${EXTERNAL_CITADEL_ROOT}" +} + +# Copy Docker data dir to external storage +copy_docker_to_external_storage () { + mkdir -p "${EXTERNAL_DOCKER_DIR}" + cp --recursive \ + --archive \ + --no-target-directory \ + "${DOCKER_DIR}" "${EXTERNAL_DOCKER_DIR}" +} + +main () { + echo "Running external storage mount script..." + check_root + check_dependencies sed wipefs parted mount sync umount modprobe + + # Enable NVME kernel module if not enabled + modprobe nvme + + no_of_block_devices=$(list_block_devices | wc -l) + + retry_for_block_devices=1 + + while [[ $no_of_block_devices -lt 1 ]]; do + + echo "No block devices found" + echo "Waiting for 5 seconds before checking again..." + + sleep 5 + + no_of_block_devices=$(list_block_devices | wc -l) + retry_for_block_devices=$(( $retry_for_block_devices + 1 )) + + if [[ $retry_for_block_devices -gt 20 ]]; then + echo "No block devices found in 20 tries..." + echo "Exiting mount script without doing anything" + exit 1 + fi + + done + + if [[ $no_of_block_devices -gt 1 ]]; then + echo "Multiple block devices found, only one drive is supported" + echo "Exiting mount script without doing anything" + exit 1 + fi + + # At this point we know there is only one block device attached + block_device=$(list_block_devices) + block_device_path="/dev/${block_device}" + if [[ $block_device != sd* ]]; then + partition_path="${block_device_path}p1" + else + partition_path="${block_device_path}1" + fi + block_device_model=$(get_block_device_model $block_device) + echo "Found device \"${block_device_model}\"" + + if [[ $block_device != nvme* ]]; then + echo "Disabling UAS for USB devices..." + disable_uas + + echo "Checking if the devices can be found again..." + retry_for_usb_devices=1 + while [[ ! -e "${block_device_path}" ]]; do + retry_for_usb_devices=$(( $retry_for_usb_devices + 1 )) + if [[ $retry_for_usb_devices -gt 10 ]]; then + echo "Disabled UAS for the USB device, that seems to have broken it" + echo "Please contact the Citadel developers" + exit 1 + fi + sleep 1 + done + fi + + echo "Checking if the device is ext4..." + + if is_partition_ext4 "${partition_path}" ; then + echo "Yes, it is ext4" + mount_partition "${partition_path}" + + echo "Checking if device contains a Citadel install..." + + if [[ -f "${EXTERNAL_CITADEL_ROOT}"/.citadel ]] || [[ -f "${EXTERNAL_UMBREL_ROOT}"/.umbrel ]]; then + echo "Yes, it contains a Citadel install" + else + echo "No, it doesn't contain a Citadel install" + echo "Unmounting partition..." + unmount_partition + setup_new_device $block_device $partition_path + fi + + else + echo "No, it's not ext4" + setup_new_device $block_device $partition_path + fi + + if [[ ! -d "${EXTERNAL_DOCKER_DIR}" ]]; then + echo "Copying Docker data directory to external storage..." + copy_docker_to_external_storage + fi + + echo "Bind mounting external storage over local Citadel installation..." + SHOULD_UPGRADE=0 + # If EXTERNAL_UMBREL_ROOT exists, move it to EXTERNAL_CITADEL_ROOT + if [[ -d "${EXTERNAL_UMBREL_ROOT}" ]]; then + mv "${EXTERNAL_UMBREL_ROOT}" "${EXTERNAL_CITADEL_ROOT}" + touch "${EXTERNAL_CITADEL_ROOT}"/.citadel + SHOULD_UPGRADE=1 + fi + mount --bind "${EXTERNAL_CITADEL_ROOT}" "${CITADEL_ROOT}" + + echo "Bind mounting external storage over local Docker data dir..." + mount --bind "${EXTERNAL_DOCKER_DIR}" "${DOCKER_DIR}" + + echo "Bind mounting external storage to ${SWAP_DIR}" + mkdir -p "${MOUNT_POINT}/swap" "${SWAP_DIR}" + mount --bind "${MOUNT_POINT}/swap" "${SWAP_DIR}" + + echo "Bind mounting SD card root at /sd-card..." + [[ ! -d "/sd-root" ]] && mkdir -p "/sd-root" + mount --bind "/" "/sd-root" + + echo "Checking Citadel root is now on external storage..." + sync + sleep 1 + df -h "${CITADEL_ROOT}" | grep --quiet "${block_device_path}" + + echo "Checking ${DOCKER_DIR} is now on external storage..." + df -h "${DOCKER_DIR}" | grep --quiet "${block_device_path}" + + echo "Checking ${SWAP_DIR} is now on external storage..." + df -h "${SWAP_DIR}" | grep --quiet "${block_device_path}" + + echo "Setting up swapfile" + rm "${SWAP_FILE}" || true + fallocate -l 4G "${SWAP_FILE}" + chmod 600 "${SWAP_FILE}" + mkswap "${SWAP_FILE}" + swapon "${SWAP_FILE}" + + echo "Checking SD Card root is bind mounted at /sd-root..." + df -h "/sd-root${CITADEL_ROOT}" | grep --quiet "/dev/root" + + echo "Starting external drive mount monitor..." + echo + ${CITADEL_ROOT}/scripts/citadel-os/external-storage/monitor ${block_device} ${MOUNT_POINT} & + + if [[ ${SHOULD_UPGRADE} -eq 1 ]]; then + echo "Upgrading Citadel..." + "${CITADEL_ROOT}/scripts/update/update" --path "${EXTERNAL_CITADEL_ROOT}" + fi + echo "Mount script completed successfully!" +} + +main diff --git a/scripts/citadel-os/external-storage/update-from-sdcard b/scripts/citadel-os/external-storage/update-from-sdcard new file mode 100755 index 0000000..e86f4a0 --- /dev/null +++ b/scripts/citadel-os/external-storage/update-from-sdcard @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../../..)" +SD_MOUNT_POINT="/sd-root" +SD_CITADEL_ROOT="${SD_MOUNT_POINT}${CITADEL_ROOT}" + +check_root () { + if [[ $UID != 0 ]]; then + echo "This script must be run as root" + exit 1 + fi +} + +check_dependencies () { + for cmd in "$@"; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_semver_range () { + local range="${1}" + local version="${2}" + "${CITADEL_ROOT}/scripts/citadel-os/semver" -r "${range}" "${version}" | grep --quiet "^${version}$" +} + +main () { + check_root + check_dependencies jq + echo "Checking if SD card Citadel is newer than external storage..." + local external_version=$(cat "${CITADEL_ROOT}/info.json" | jq -r .version | cut -d "-" -f "1") + local sd_version=$(cat "${SD_CITADEL_ROOT}/info.json" | jq -r .version | cut -d "-" -f "1") + + if ! check_semver_range ">${external_version}" "${sd_version}"; then + echo "No, SD version is not newer, exiting." + exit 0 + fi + + echo "Yes, SD version is newer." + # This will fail if we ever have multiple ranges with pre-release tags. + # e.g `1.2.3-beta <2.0.0` will become `1.2.3` due to striping the `-` + local update_requirement=$(cat "${SD_CITADEL_ROOT}/info.json" | jq -r .requires | cut -d "-" -f "1") + + echo "Checking if the external storage version \"${external_version}\" satisfies update requirement \"${update_requirement}\"..." + if ! check_semver_range "${update_requirement}" "${external_version}"; then + echo "No, we can't do an automatic update, exiting." + exit 0 + fi + + echo "Yes, it does, attempting an automatic update..." + "${CITADEL_ROOT}/scripts/update/update" --path "${SD_CITADEL_ROOT}" +} + +main diff --git a/scripts/citadel-os/semver b/scripts/citadel-os/semver new file mode 100755 index 0000000..e73077c --- /dev/null +++ b/scripts/citadel-os/semver @@ -0,0 +1,525 @@ +#!/usr/bin/env bash + +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# SPDX-FileCopyrightText: Copyright (c) 2014 Józef Sokołowski + +# https://github.com/qzb/sh-semver +# Commit: 2ac2437 + +_num_part='([0-9]|[1-9][0-9]*)' +_lab_part='([0-9]|[1-9][0-9]*|[0-9]*[a-zA-Z-][a-zA-Z0-9-]*)' +_met_part='([0-9A-Za-z-]+)' + +RE_NUM="$_num_part(\.$_num_part)*" +RE_LAB="$_lab_part(\.$_lab_part)*" +RE_MET="$_met_part(\.$_met_part)*" +RE_VER="[ \t]*$RE_NUM(-$RE_LAB)?(\+$RE_MET)?" + +BRE_DIGIT='[0-9]\{1,\}' +BRE_ALNUM='[0-9a-zA-Z-]\{1,\}' +BRE_IDENT="$BRE_ALNUM\(\.$BRE_ALNUM\)*" + +BRE_MAJOR="$BRE_DIGIT" +BRE_MINOR="\(\.$BRE_DIGIT\)\{0,1\}" +BRE_PATCH="\(\.$BRE_DIGIT\)\{0,1\}" +BRE_PRERE="\(-$BRE_IDENT\)\{0,1\}" +BRE_BUILD="\(+$BRE_IDENT\)\{0,1\}" +BRE_VERSION="${BRE_MAJOR}${BRE_MINOR}${BRE_PATCH}${BRE_PRERE}${BRE_BUILD}" + +filter() +{ + local text="$1" + local regex="$2" + shift 2 + echo "$text" | grep -E "$@" "$regex" +} + +# Gets number part from normalized version +get_number() +{ + echo "${1%%-*}" +} + +# Gets prerelase part from normalized version +get_prerelease() +{ + local pre_and_meta=${1%+*} + local pre=${pre_and_meta#*-} + if [ "$pre" = "$1" ]; then + echo + else + echo "$pre" + fi +} + +# Gets major number from normalized version +get_major() +{ + echo "${1%%.*}" +} + +# Gets minor number from normalized version +get_minor() +{ + local minor_major_bug=${1%%-*} + local minor_major=${minor_major_bug%.*} + local minor=${minor_major#*.} + + if [ "$minor" = "$minor_major" ]; then + echo + else + echo "$minor" + fi +} + +get_bugfix() +{ + local minor_major_bug=${1%%-*} + local bugfix=${minor_major_bug##*.*.} + + if [ "$bugfix" = "$minor_major_bug" ]; then + echo + else + echo "$bugfix" + fi +} + +strip_metadata() +{ + echo "${1%+*}" +} + +semver_eq() +{ + local ver1 ver2 part1 part2 + ver1=$(get_number "$1") + ver2=$(get_number "$2") + + local count=1 + while true; do + part1=$(echo "$ver1"'.' | cut -d '.' -f $count) + part2=$(echo "$ver2"'.' | cut -d '.' -f $count) + + if [ -z "$part1" ] || [ -z "$part2" ]; then + break + fi + + if [ "$part1" != "$part2" ]; then + return 1 + fi + + local count=$(( count + 1 )) + done + + if [ "$(get_prerelease "$1")" = "$(get_prerelease "$2")" ]; then + return 0 + else + return 1 + fi +} + +semver_lt() +{ + local number_a number_b prerelease_a prerelease_b + number_a=$(get_number "$1") + number_b=$(get_number "$2") + prerelease_a=$(get_prerelease "$1") + prerelease_b=$(get_prerelease "$2") + + + local head_a='' + local head_b='' + local rest_a=$number_a. + local rest_b=$number_b. + while [ -n "$rest_a" ] || [ -n "$rest_b" ]; do + head_a=${rest_a%%.*} + head_b=${rest_b%%.*} + rest_a=${rest_a#*.} + rest_b=${rest_b#*.} + + if [ -z "$head_a" ] || [ -z "$head_b" ]; then + return 1 + fi + + if [ "$head_a" -eq "$head_b" ]; then + continue + fi + + if [ "$head_a" -lt "$head_b" ]; then + return 0 + else + return 1 + fi + done + + if [ -n "$prerelease_a" ] && [ -z "$prerelease_b" ]; then + return 0 + elif [ -z "$prerelease_a" ] && [ -n "$prerelease_b" ]; then + return 1 + fi + + local head_a='' + local head_b='' + local rest_a=$prerelease_a. + local rest_b=$prerelease_b. + while [ -n "$rest_a" ] || [ -n "$rest_b" ]; do + head_a=${rest_a%%.*} + head_b=${rest_b%%.*} + rest_a=${rest_a#*.} + rest_b=${rest_b#*.} + + if [ -z "$head_a" ] && [ -n "$head_b" ]; then + return 0 + elif [ -n "$head_a" ] && [ -z "$head_b" ]; then + return 1 + fi + + if [ "$head_a" = "$head_b" ]; then + continue + fi + + # If both are numbers then compare numerically + if [ "$head_a" = "${head_a%[!0-9]*}" ] && [ "$head_b" = "${head_b%[!0-9]*}" ]; then + [ "$head_a" -lt "$head_b" ] && return 0 || return 1 + # If only a is a number then return true (number has lower precedence than strings) + elif [ "$head_a" = "${head_a%[!0-9]*}" ]; then + return 0 + # If only b is a number then return false + elif [ "$head_b" = "${head_b%[!0-9]*}" ]; then + return 1 + # Finally if of identifiers is a number compare them lexically + else + test "$head_a" \< "$head_b" && return 0 || return 1 + fi + done + + return 1 +} + +semver_gt() +{ + if semver_lt "$1" "$2" || semver_eq "$1" "$2"; then + return 1 + else + return 0 + fi +} + +semver_le() +{ + semver_gt "$1" "$2" && return 1 || return 0 +} + +semver_ge() +{ + semver_lt "$1" "$2" && return 1 || return 0 +} + +semver_sort() +{ + if [ $# -le 1 ]; then + echo "$1" + return + fi + + local pivot=$1 + local args_a=() + local args_b=() + + shift 1 + + for ver in "$@"; do + if semver_le "$ver" "$pivot"; then + args_a=( "${args_a[@]}" "$ver" ) + else + args_b=( "$ver" "${args_b[@]}" ) + fi + done + + args_a=( $(semver_sort "${args_a[@]}") ) + args_b=( $(semver_sort "${args_b[@]}") ) + echo "${args_a[@]}" "$pivot" "${args_b[@]}" +} + +regex_match() +{ + local string="$1 " + local regexp="$2" + local match + match="$(eval "echo '$string' | grep -E -o '^[ \t]*($regexp)[ \t]+'")"; + + for i in $(seq 0 9); do + unset "MATCHED_VER_$i" + unset "MATCHED_NUM_$i" + done + unset REST + + if [ -z "$match" ]; then + return 1 + fi + + local match_len=${#match} + REST="${string:$match_len}" + + local part + local i=1 + for part in $string; do + local ver num + ver="$(eval "echo '$part' | grep -E -o '$RE_VER' | head -n 1 | sed 's/ \t//g'")"; + num=$(get_number "$ver") + + if [ -n "$ver" ]; then + eval "MATCHED_VER_$i='$ver'" + eval "MATCHED_NUM_$i='$num'" + i=$(( i + 1 )) + fi + done + + return 0 +} + +# Normalizes rules string +# +# * replaces chains of whitespaces with single spaces +# * replaces whitespaces around hyphen operator with "_" +# * removes wildcards from version numbers (1.2.* -> 1.2) +# * replaces "x" with "*" +# * removes whitespace between operators and version numbers +# * removes leading "v" from version numbers +# * removes leading and trailing spaces +normalize_rules() +{ + echo " $1" \ + | sed 's/\\t/ /g' \ + | sed 's/ / /g' \ + | sed 's/ \{2,\}/ /g' \ + | sed 's/ - /_-_/g' \ + | sed 's/\([~^<>=]\) /\1/g' \ + | sed 's/\([ _~^<>=]\)v/\1/g' \ + | sed 's/\.[xX*]//g' \ + | sed 's/[xX]/*/g' \ + | sed 's/^ //g' \ + | sed 's/ $//g' +} + +# Reads rule from provided string +resolve_rule() +{ + local rule operator operands + rule="$1" + operator="$( echo "$rule" | sed "s/$BRE_VERSION/#/g" )" + operands=( $( echo "$rule" | grep -o "$BRE_VERSION") ) + + case "$operator" in + '*') echo "all" ;; + '#') echo "eq ${operands[0]}" ;; + '=#') echo "eq ${operands[0]}" ;; + '<#') echo "lt ${operands[0]}" ;; + '>#') echo "gt ${operands[0]}" ;; + '<=#') echo "le ${operands[0]}" ;; + '>=#') echo "ge ${operands[0]}" ;; + '#_-_#') echo "ge ${operands[0]}" + echo "le ${operands[1]}" ;; + '~#') echo "tilde ${operands[0]}" ;; + '^#') echo "caret ${operands[0]}" ;; + *) return 1 + esac +} + +resolve_rules() +{ + local rules + rules="$(normalize_rules "$1")" + IFS=' ' read -ra rules <<< "${rules:-all}" + + for rule in "${rules[@]}"; do + resolve_rule "$rule" + done +} + +rule_eq() +{ + local rule_ver="$1" + local tested_ver="$2" + + semver_eq "$tested_ver" "$rule_ver" && return 0 || return 1; +} + +rule_le() +{ + local rule_ver="$1" + local tested_ver="$2" + + semver_le "$tested_ver" "$rule_ver" && return 0 || return 1; +} + +rule_lt() +{ + local rule_ver="$1" + local tested_ver="$2" + + semver_lt "$tested_ver" "$rule_ver" && return 0 || return 1; +} + +rule_ge() +{ + local rule_ver="$1" + local tested_ver="$2" + + semver_ge "$tested_ver" "$rule_ver" && return 0 || return 1; +} + +rule_gt() +{ + local rule_ver="$1" + local tested_ver="$2" + + semver_gt "$tested_ver" "$rule_ver" && return 0 || return 1; +} + +rule_tilde() +{ + local rule_ver="$1" + local tested_ver="$2" + + if rule_ge "$rule_ver" "$tested_ver"; then + local rule_major rule_minor + rule_major=$(get_major "$rule_ver") + rule_minor=$(get_minor "$rule_ver") + + if [ -n "$rule_minor" ] && rule_eq "$rule_major.$rule_minor" "$(get_number "$tested_ver")"; then + return 0 + fi + if [ -z "$rule_minor" ] && rule_eq "$rule_major" "$(get_number "$tested_ver")"; then + return 0 + fi + fi + + return 1 +} + +rule_caret() +{ + local rule_ver="$1" + local tested_ver="$2" + + if rule_ge "$rule_ver" "$tested_ver"; then + local rule_major + rule_major="$(get_major "$rule_ver")" + + if [ "$rule_major" != "0" ] && rule_eq "$rule_major" "$(get_number "$tested_ver")"; then + return 0 + fi + if [ "$rule_major" = "0" ] && rule_eq "$rule_ver" "$(get_number "$tested_ver")"; then + return 0 + fi + fi + + return 1 +} + +rule_all() +{ + return 0 +} + +apply_rules() +{ + local rules_string="$1" + shift + local versions=( "$@" ) + + # Loop over sets of rules (sets of rules are separated with ||) + for ver in "${versions[@]}"; do + rules_tail="$rules_string"; + + while [ -n "$rules_tail" ]; do + head="${rules_tail%%||*}" + + if [ "$head" = "$rules_tail" ]; then + rules_string="" + else + rules_tail="${rules_tail#*||}" + fi + + #if [ -z "$head" ] || [ -n "$(echo "$head" | grep -E -x '[ \t]*')" ]; then + #group=$(( $group + 1 )) + #continue + #fi + + rules="$(resolve_rules "$head")" + + # If specified rule cannot be recognised - end with error + if [ $? -eq 1 ]; then + exit 1 + fi + + if ! echo "$ver" | grep -q -E -x "[v=]?[ \t]*$RE_VER"; then + continue + fi + + ver=$(echo "$ver" | grep -E -x "$RE_VER") + + success=true + allow_prerel=false + if $FORCE_ALLOW_PREREL; then + allow_prerel=true + fi + + while read -r rule; do + comparator="${rule%% *}" + operand="${rule#* }" + + if [ -n "$(get_prerelease "$operand")" ] && semver_eq "$(get_number "$operand")" "$(get_number "$ver")" || [ "$rule" = "all" ]; then + allow_prerel=true + fi + + "rule_$comparator" "$operand" "$ver" + if [ $? -eq 1 ]; then + success=false + break + fi + done <<< "$rules" + + if $success; then + if [ -z "$(get_prerelease "$ver")" ] || $allow_prerel; then + echo "$ver" + break; + fi + fi + done + + group=$(( group + 1 )) + done +} + + + +FORCE_ALLOW_PREREL=false +USAGE="Usage: $0 [-r ] [... ] + +Omitting s reads them from STDIN. +Omitting -r simply sorts the versions according to semver ordering." + +while getopts ar:h o; do + case "$o" in + a) FORCE_ALLOW_PREREL=true ;; + r) RULES_STRING="$OPTARG||";; + h) echo "$USAGE" && exit ;; + ?) echo "$USAGE" && exit 1;; + esac +done + +shift $(( OPTIND-1 )) + +VERSIONS=( ${@:-$(cat -)} ) + +# Sort versions +VERSIONS=( $(semver_sort "${VERSIONS[@]}") ) + +if [ -z "$RULES_STRING" ]; then + printf '%s\n' "${VERSIONS[@]}" +else + apply_rules "$RULES_STRING" "${VERSIONS[@]}" +fi diff --git a/scripts/citadel-os/services/citadel-connection-details.service b/scripts/citadel-os/services/citadel-connection-details.service new file mode 100644 index 0000000..735e9fb --- /dev/null +++ b/scripts/citadel-os/services/citadel-connection-details.service @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Citadel Connection Details Logger (TTY) +# Installed at /etc/systemd/system/citadel-connection-details.service + +[Unit] +Description=Connection Details +Requires=citadel-startup.service +After=citadel-startup.service + +[Service] +Type=oneshot +Restart=no +ExecStart=/home/citadel/citadel/scripts/citadel-os/citadel-details +User=root +Group=root +StandardOutput=tty +TTYPath=/dev/tty1 +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target diff --git a/scripts/citadel-os/services/citadel-external-storage-sdcard-update.service b/scripts/citadel-os/services/citadel-external-storage-sdcard-update.service new file mode 100644 index 0000000..64f85ad --- /dev/null +++ b/scripts/citadel-os/services/citadel-external-storage-sdcard-update.service @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Citadel External Storage SDcard Updater +# Installed at /etc/systemd/system/citadel-external-storage-sdcard-update.service + +[Unit] +Description=External Storage SDcard Updater +Requires=citadel-external-storage.service +After=citadel-external-storage.service +Wants=network-online.target +After=network-online.target +Wants=docker.service +After=docker.service + +[Service] +Type=oneshot +Restart=no +ExecStart=/home/citadel/citadel/scripts/citadel-os/external-storage/update-from-sdcard +TimeoutStartSec=45min +User=root +Group=root +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target diff --git a/scripts/citadel-os/services/citadel-external-storage.service b/scripts/citadel-os/services/citadel-external-storage.service new file mode 100644 index 0000000..952de07 --- /dev/null +++ b/scripts/citadel-os/services/citadel-external-storage.service @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Citadel External Storage Mounter +# Installed at /etc/systemd/system/citadel-external-storage.service + +[Unit] +Description=External Storage Mounter +Before=docker.service + +[Service] +Type=oneshot +Restart=no +ExecStart=/home/citadel/citadel/scripts/citadel-os/external-storage/mount +TimeoutStartSec=45min +User=root +Group=root +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target diff --git a/scripts/citadel-os/services/citadel-startup.service b/scripts/citadel-os/services/citadel-startup.service new file mode 100644 index 0000000..b247cf1 --- /dev/null +++ b/scripts/citadel-os/services/citadel-startup.service @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Citadel Startup Service +# Installed at /etc/systemd/system/citadel-startup.service + +[Unit] +Description=Citadel Startup Service +Requires=citadel-external-storage.service +After=citadel-external-storage.service +Requires=citadel-external-storage-sdcard-update.service +After=citadel-external-storage-sdcard-update.service +Wants=network-online.target +After=network-online.target +Wants=docker.service +After=docker.service + +# This prevents us hitting restart rate limits and ensures we keep restarting +# indefinitely. +StartLimitInterval=0 + +[Service] +Type=forking +TimeoutStartSec=infinity +TimeoutStopSec=16min +ExecStart=/home/citadel/citadel/scripts/start +ExecStop=/home/citadel/citadel/scripts/stop +User=root +Group=root +RemainAfterExit=yes +Restart=always +RestartSec=10 + +[Install] +WantedBy=multi-user.target diff --git a/scripts/configure b/scripts/configure new file mode 100755 index 0000000..8ddc0f1 --- /dev/null +++ b/scripts/configure @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import sys +import os +from lib.rpcauth import get_data +import re +import subprocess +import json + +# Print an error if the user isn't running on Linux. +if sys.platform != 'linux': + print('This script only works on Linux!') + exit(1) + +# Print an error if user is not root +if os.getuid() != 0: + print('This script must be run as root!') + exit(1) + +# Check if the system is arm64 or amd64 +def is_arm64(): + return subprocess.check_output(['uname', '-m']).decode('utf-8').strip() == 'aarch64' +def is_amd64(): + return subprocess.check_output(['uname', '-m']).decode('utf-8').strip() == 'x86_64' + +if not is_arm64() and not is_amd64(): + print('Umbrel only works on arm64 and amd64!') + exit(1) + +# Check the output of "docker compose version", if it matches "Docker Compose version v2.0.0-rc.3", return true +# Otherwise, return false +def is_compose_rc(): + try: + output = subprocess.check_output(['docker', 'compose', 'version']) + if(output.decode('utf-8').strip() == 'Docker Compose version v2.0.0-rc.3'): + print("Using rc docker compose, updating...") + return True + else: + return False + except: + return True + +# Download docker-compose from https://github.com/docker/compose/releases/download/v2.0.1/docker-compose-linux-aarch64 +# or https://github.com/docker/compose/releases/download/v2.0.1/docker-compose-linux-x86_64 +# and put it in $HOME/.docker/cli-plugins/docker-compose +def download_docker_compose(): + # Skip if os.path.expanduser('~/.docker/cli-plugins/docker-compose') exists + subprocess.check_call(["mkdir", "-p", os.path.expanduser('~/.docker/cli-plugins/')]) + if (os.path.exists(os.path.expanduser('~/.docker/cli-plugins/docker-compose')) or os.path.exists('/usr/lib/docker/cli-plugins/docker-compose')) and not is_compose_rc(): + return + if is_arm64(): + subprocess.check_call(['wget', 'https://github.com/docker/compose/releases/download/v2.0.1/docker-compose-linux-aarch64', '-O', os.path.expanduser('~/.docker/cli-plugins/docker-compose')]) + elif is_amd64(): + subprocess.check_call(['wget', 'https://github.com/docker/compose/releases/download/v2.0.1/docker-compose-linux-x86_64', '-O', os.path.expanduser('~/.docker/cli-plugins/docker-compose')]) + os.chmod(os.path.expanduser('~/.docker/cli-plugins/docker-compose'), 0o755) + + +try: + subprocess.check_call(['wget', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +except: + print('Wget is not installed!') + exit(1) + +try: + subprocess.check_call(['docker', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +except: + print('Docker is not installed!') + exit(1) + +# Switch to node root directory. +CITADEL_ROOT=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.chdir(CITADEL_ROOT) + +updating = False +status_dir = os.path.join(CITADEL_ROOT, 'statuses') +# Make sure to use the main status dir for updates +if os.path.isfile('../.umbrel'): + status_dir = os.path.join(CITADEL_ROOT, '..', 'statuses') + updating = True + +# Configure for mainnet or testnet or regtest depending +# upon the user-supplied value of $NETWORK +# If the network is not specified, then use the mainnet +BITCOIN_NETWORK=os.environ.get('NETWORK') or 'mainnet' + +# Check if network neither mainnet nor testnet nor regtest +if BITCOIN_NETWORK not in ['mainnet', 'testnet', 'regtest']: + print('Error: Network must be either mainnet, testnet, or regtest!') + exit(1) + +with open(os.path.join(CITADEL_ROOT, "info.json"), 'r') as file: + CITADEL_VERSION=json.load(file)['version'] + +print() +print("======================================") +if os.path.isfile(status_dir+'/configured'): + print("=========== RECONFIGURING ============") + reconfiguring=True +else: + print("============ CONFIGURING =============") + reconfiguring=False + +print("============== CITADEL ==============") +print("======================================") +print() + +if not reconfiguring: + print("Installing electrs...") + data = subprocess.run("\"{}\" install electrs".format(os.path.join(CITADEL_ROOT, "services", "manage.py")), shell=True) + +print("Installing additional services") +data = subprocess.run("\"{}\" setup".format(os.path.join(CITADEL_ROOT, "services", "manage.py")), shell=True) + +# Parse a dotenv file +# Values can either be KEY=VALUE or KEY="VALUE" or KEY='VALUE' +# Returns all env vars as a dict +def parse_dotenv(file_path): + envVars: dict = {} + with open(file_path, 'r') as file: + for line in file: + line = line.strip() + if line.startswith('#') or len(line) == 0: + continue + if '=' in line: + key, value = line.split('=', 1) + value = value.strip('"').strip("'") + envVars[key] = value + else: + print("Error: Invalid line in {}: {}".format(file_path, line)) + print("Line should be in the format KEY=VALUE or KEY=\"VALUE\" or KEY='VALUE'") + exit(1) + return envVars + + +########################################################## +############ Generate configuration variables ############ +########################################################## + +NGINX_PORT=os.environ.get('NGINX_PORT') or "80" + +if reconfiguring: + if os.path.isfile('../.umbrel'): + dotenv=parse_dotenv('../.env') + else: + dotenv=parse_dotenv('./.env') + + BITCOIN_NETWORK=os.environ.get('OVERWRITE_NETWORK') or dotenv['BITCOIN_NETWORK'] + # Check if network neither mainnet nor testnet nor regtest + if BITCOIN_NETWORK not in ['mainnet', 'testnet', 'regtest']: + print('Error: Network must be either mainnet, testnet, or regtest!') + exit(1) + print("Using {} network".format(BITCOIN_NETWORK)) + print() + BITCOIN_RPC_PORT=dotenv['BITCOIN_RPC_PORT'] + BITCOIN_P2P_PORT=dotenv['BITCOIN_P2P_PORT'] + BITCOIN_RPC_USER=dotenv['BITCOIN_RPC_USER'] + BITCOIN_RPC_PASS=dotenv['BITCOIN_RPC_PASS'] + BITCOIN_RPC_AUTH=dotenv['BITCOIN_RPC_AUTH'] + TOR_PASSWORD=dotenv['TOR_PASSWORD'] + TOR_HASHED_PASSWORD=dotenv['TOR_HASHED_PASSWORD'] + NGINX_PORT=dotenv['NGINX_PORT'] +else: + # Generate RPC credentials + print("Generating auth credentials") + print() + BITCOIN_RPC_USER="umbrel" + BITCOIN_RPC_DETAILS=get_data(BITCOIN_RPC_USER) + BITCOIN_RPC_AUTH=BITCOIN_RPC_DETAILS['auth'] + BITCOIN_RPC_PASS=BITCOIN_RPC_DETAILS['password'] + + # Pull Tor image and generate Tor password + print("Generating Tor password") + print() + os.system('docker pull --quiet lncm/tor:0.4.6.7') + TOR_PASSWORD=get_data('itdoesntmatter')['password'] + + # run 'docker run --rm lncm/tor:0.4.6.7 --quiet --hash-password "$TOR_PASS"' and get its output + # this is the password that is used to connect to the Tor network + # the password is stored in the .env file + TOR_HASHED_PASSWORD=os.popen('docker run --rm lncm/tor:0.4.6.7 --quiet --hash-password "{}"'.format(TOR_PASSWORD)).read()[:-1] + +BITCOIN_NODE="neutrino" +ALIAS_AND_COLOR="" +ADDITIONAL_BITCOIN_OPTIONS="" +BOLT_DB_OPTIONS="" +CHANNEL_LIMITATIONS="" + +if os.path.isfile("./lnd/lnd.conf"): + with open("./lnd/lnd.conf", 'r') as file: + # We generally don't want to allow changing lnd.conf, but we keep as many custom settings as possible + for line in file: + if line.startswith("bitcoin.node="): + BITCOIN_NODE = line.split("=")[1].strip() + if line.startswith("alias="): + ALIAS_AND_COLOR += "\n" + line.strip() + if line.startswith("color="): + ALIAS_AND_COLOR += "\n" + line.strip() + if line.startswith("bitcoin.basefee"): + ADDITIONAL_BITCOIN_OPTIONS += "\n" + line.strip() + if line.startswith("bitcoin.feerate"): + ADDITIONAL_BITCOIN_OPTIONS += "\n" + line.strip() + if line.startswith("minchansize"): + CHANNEL_LIMITATIONS += "\n" + line.strip() + if line.startswith("maxchansize"): + CHANNEL_LIMITATIONS += "\n" + line.strip() + if line.startswith("maxpendingchannels"): + CHANNEL_LIMITATIONS += "\n" + line.strip() + if line.startswith("db.bolt.auto-compact"): + BOLT_DB_OPTIONS += "\n" + line.strip() + +if BOLT_DB_OPTIONS != "": + BOLT_DB_OPTIONS = "[bolt]\n" + BOLT_DB_OPTIONS + +if CHANNEL_LIMITATIONS == "": + CHANNEL_LIMITATIONS = "maxpendingchannels=3\nminchansize=10000" + +NEUTRINO_PEERS="" +if BITCOIN_NETWORK == "mainnet": + BITCOIN_RPC_PORT=8332 + BITCOIN_P2P_PORT=8333 +elif BITCOIN_NETWORK == "testnet": + BITCOIN_RPC_PORT=18332 + BITCOIN_P2P_PORT=18333 + NEUTRINO_PEERS=''' +[neutrino] +neutrino.addpeer=testnet1-btcd.zaphq.io +neutrino.addpeer=testnet2-btcd.zaphq.io + ''' +elif BITCOIN_NETWORK == "regtest": + BITCOIN_RPC_PORT=18334 + BITCOIN_P2P_PORT=18335 + BITCOIN_NODE="bitcoind" +else: + exit(1) + +# IP addresses for services +NETWORK_IP="10.21.21.0" +GATEWAY_IP="10.21.21.1" +NGINX_IP="10.21.21.2" +DASHBOARD_IP="10.21.21.3" +MANAGER_IP="10.21.21.4" +MIDDLEWARE_IP="10.21.21.5" +NEUTRINO_SWITCHER_IP="10.21.21.6" +BITCOIN_IP="10.21.21.8" +LND_IP="10.21.21.9" +ELECTRUM_IP="10.21.21.10" +TOR_PROXY_IP="10.21.21.11" +APPS_TOR_IP="10.21.21.12" +APPS_2_TOR_IP="10.21.21.13" +APPS_3_TOR_IP="10.21.21.14" +BITCOIN_RPC_PORT="8332" +BITCOIN_P2P_PORT="8333" +BITCOIN_ZMQ_RAWBLOCK_PORT="28332" +BITCOIN_ZMQ_RAWTX_PORT="28333" +BITCOIN_ZMQ_HASHBLOCK_PORT="28334" +LND_GRPC_PORT="10009" +LND_REST_PORT="8080" +ELECTRUM_PORT="50001" +TOR_PROXY_PORT="9050" +TOR_CONTROL_PORT="29051" + +DEVICE_HOSTNAME=subprocess.check_output("hostname").decode("utf-8").strip() +DOCKER_EXECUTABLE=subprocess.check_output(["which", "docker"]).decode("utf-8").strip() +# Get the real path by following symlinks +DOCKER_BINARY=subprocess.check_output(["readlink", "-f", DOCKER_EXECUTABLE]).decode("utf-8").strip() + +# Set LND fee URL for neutrino on mainnet +LND_FEE_URL="" +# If the network is mainnet and status_dir/node-status-bitcoind-ready doesn't exist, set the FEE_URL +if BITCOIN_NETWORK == 'mainnet' and BITCOIN_NODE == 'neutrino': + LND_FEE_URL="feeurl=https://nodes.lightning.computer/fees/v1/btc-fee-estimates.json" + +# Checks if a variable with the name exists, if not, check if an env var with the name existts +# if neither exists, then exit with an error +def get_var(var_name, other_locals, file_name): + if var_name in locals(): + return str(locals()[var_name]) + elif var_name in other_locals: + return str(other_locals[var_name]) + elif var_name in globals(): + return str(globals()[var_name]) + else: + print("Error: {} is not defined! (In file {})".format(var_name, file_name)) + exit(1) + +# Converts a string to uppercase, also replaces all - with _ +def convert_to_upper(string): + return string.upper().replace('-', '_') + +# Put variables in the config file. A config file accesses an env var $EXAMPLE_VARIABLE by containing +# in the config file. Check for such occurences and replace them with the actual variable +def replace_vars(file_path): + with open(file_path, 'r') as file: + file_contents = file.read() + return re.sub(r'<(.*?)>', lambda m: get_var(convert_to_upper(m.group(1)), locals(), file_path), file_contents) + +templates_to_build = { + "./templates/torrc-empty": "./tor/torrc-apps", + "./templates/torrc-empty": "./tor/torrc-apps-2", + "./templates/torrc-empty": "./tor/torrc-apps-3", + "./templates/torrc-core-sample": "./tor/torrc-core", + "./templates/lnd-sample.conf": "./lnd/lnd.conf", + "./templates/bitcoin-sample.conf": "./bitcoin/bitcoin.conf", + "./templates/.env-sample": "./.env", + "./templates/electrs-sample.toml": "./electrs/electrs.toml", + "./templates/nginx-sample.conf": "./nginx/nginx.conf" +} + +print("Generating configuration files") +print() + +# Loop through templates_to_build and build them +for template_path, output_path in templates_to_build.items(): + data = replace_vars(template_path) + if data != "" and data != None: + with open(output_path, 'w') as file: + file.write(data) + +print("Installing docker-compose...") +print() +download_docker_compose() +if not updating: + print("Updating apps...") + print() + os.system('./app/app-manager.py --invoked-by-configure update-online') +print("Configuring permissions") +print() +os.system('chown -R 1000:1000 {}'.format(CITADEL_ROOT)) +# Touch status_dir/configured +with open(status_dir+'/configured', 'w') as file: + file.write('') +print("Configuration successful") +print("You can now start Citadel by running:") +print(" sudo ./scripts/start") diff --git a/scripts/debug b/scripts/debug new file mode 100755 index 0000000..3d46288 --- /dev/null +++ b/scripts/debug @@ -0,0 +1,266 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +NODE_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/.." +cd "${NODE_ROOT}" + +if [[ $UID != 0 ]]; then + echo "This script must run as root" + echo "Please re-run this script as" + echo " sudo ~/citadel/scripts/debug" + exit 1 +fi + +# Try to load Citadel OS version on Citadel OS +[[ -f "/etc/default/citadel" ]] && source "/etc/default/citadel" +[[ -f "./.env" ]] && source "./.env" + +# function to upload the output to our debug log server +# Based on https://github.com/seejohnrun/haste-client#lightweight-alternative +upload() { + echo "Generating link..." + curl \ + --header "Content-Type: text/plain" \ + --request POST \ + --data-binary @- \ + https://api.debug.umbrel.tech/api/upload \ + | jq '.key' \ + | sed 's/"//g' \ + | awk -F '"' '{print "https://citadel-paste.vercel.app/"$1}' +} + +torupload() { + echo "Generating link..." + curl \ + --header "Content-Type: text/plain" \ + --request POST \ + --socks5 "localhost:${TOR_PROXY_PORT}" \ + --data-binary @- \ + https://api.debug.umbrel.tech/api/upload \ + | jq '.key' \ + | sed 's/"//g' \ + | awk -F '"' '{print "https://citadel-paste.vercel.app/"$1}' +} + +list_block_devices () { + # Documented in the mount script for the OS + sync + (ls -d /sys/block/sd* /sys/block/nvme*n* 2>/dev/null || true) | sed 's!.*/!!' +} + +if [[ "${1}" == "--run" ]]; then + echo "==============" + echo "= Debug info =" + echo "==============" + + echo + echo "Node version" + echo "------------" + cat info.json | jq .version | sed 's/"//g' + + if [[ ! -z "${CITADEL_OS:-}" ]]; then + echo + echo "Flashed OS version" + echo "-----------------" + echo $CITADEL_OS + + echo + echo "Raspberry Pi Model" + echo "------------------" + + cat /proc/cpuinfo | tail -1 + + echo + echo "Temperature" + echo "-----------" + + vcgencmd measure_temp + + echo + echo "Throttling" + echo "----------" + + vcgencmd get_throttled + fi + + echo + echo "Memory usage" + echo "------------" + free --human --mega + echo + "${NODE_ROOT}/scripts/memory-usage" + + echo + echo "Memory monitor logs" + echo "-------------------" + tail -n 10 "${NODE_ROOT}/logs/memory-monitor.log" + + echo + echo "Filesystem information" + echo "----------------------" + + df --human-readable / "${NODE_ROOT}" + + if [[ ! -z "${CITADEL_OS:-}" ]]; then + echo + echo "Startup service logs" + echo "--------------------" + journalctl --unit=citadel-startup.service | tail -n 30 | sed '/onion/d' + + echo + echo "External storage service logs" + echo "-----------------------------" + journalctl --unit=citadel-external-storage.service | tail -n 30 + + echo + echo "External storage SD card update service logs" + echo "--------------------------------------------" + journalctl --unit=citadel-external-storage-sdcard-update.service | tail -n 30 + fi + + + echo + echo "Karen logs" + echo "----------" + echo + + tail -n 50 logs/karen.log | sed '/onion/d' + + echo + echo "Docker containers" + echo "-----------------" + + docker ps --format="table {{.Names}}\t{{.Status}}" + + echo + echo "Bitcoin Core logs" + echo "-----------------" + echo + docker compose logs --tail=30 bitcoin + + echo + echo "LND logs" + echo "--------" + echo + docker compose logs --tail=30 lnd + + echo + echo "Tor logs" + echo "--------" + echo + docker compose logs --tail=30 tor + + installed_apps=$(./app/app-manager.py ls-installed) + if [[ ! -z "${installed_apps:-}" ]]; then + echo + echo "App logs" + echo "--------" + for app in $installed_apps; do + echo + echo "${app}" + echo + # Double tail because we want 30 lines total not per container + ./scripts/app compose $app logs --tail 30 | tail -n 30; + done + fi +else + filter_sensitive=false + allow_colors=true + upload=false + instructions=true + dmesg=false + tor=true + while [[ "$#" -gt 0 ]]; do + case $1 in + --no-colors) allow_colors=false ;; + --no-instructions) instructions=false ;; + -f|--filter) filter_sensitive=true ;; + -u|--upload) upload=true ;; + --no-tor) tor=false ;; + -d|--dmesg) dmesg=true ;; + -r|--run) echo "--run can't be used with other options!"; exit 1 ;; + *) echo "Unknown parameter passed: $1"; exit 1 ;; + esac + shift + done + echo "Loading data..." + OWN_OUTPUT="$(./scripts/debug --run)" + append_dmesg () { + echo "${1}" + echo "dmesg" + echo "-----" + dmesg + } + + if [[ $allow_colors = false ]]; then + OWN_OUTPUT=$(echo "${OWN_OUTPUT}" | sed -r "s/\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g") + fi + + if [[ $filter_sensitive = true ]]; then + # TODO: Add more filters + OWN_OUTPUT=$(echo "${OWN_OUTPUT}" | sed '/onion/d') + fi + + if [[ $dmesg = true ]]; then + OWN_OUTPUT=$(append_dmesg "${OWN_OUTPUT}") + fi + + echo "${OWN_OUTPUT}" + + if [[ $upload = true ]]; then + if [[ $dmesg = false ]]; then + OWN_OUTPUT=$(append_dmesg "${OWN_OUTPUT}") + fi + OWN_OUTPUT=$(echo "${OWN_OUTPUT}" | sed '/onion/d') + fi + + echo "================" + echo "==== Result ====" + echo "================" + echo + if [[ ! -z "${BITCOIN_NODE_OS:-}" ]]; then + if [[ $(vcgencmd get_throttled) != "throttled=0x0" ]]; then + if [[ $(vcgencmd get_throttled) = "throttled=0x5"* ]]; then + echo "There is probably issue with your power supply. We recommend using the official power supply to avoid this issue." + else + echo "The temperature of your Raspberry Pi is too high. We recommend either using a case that lowers the temperature of your Pi or a case with a builtin fan." + fi + exit 0 + fi + + no_of_block_devices=$(list_block_devices | wc -l) + if [[ $no_of_block_devices -lt 1 ]]; then + echo "You have either no external drive connected to your Raspberry Pi or the drive is not being detected." + echo "Please shutdown your Raspberry Pi ('sudo shutdown'), then plug the SSD into the other USB3 port." + echo "After you've finished that, boot your Raspberry Pi back up. If it still still doesn't work," + echo "you can contact us on Telegram." + if [[ $upload = true ]]; then + echo "To make it possible for us to analyze your problem easier, please share the following link with us:" + echo "${OWN_OUTPUT}" | upload + elif [[ $instructions = true ]]; then + echo "Please run this script again with the --upload flag to generate a link to share." + fi + exit 0 + elif [[ $no_of_block_devices -gt 1 ]]; then + echo "You have multiple external drives connected to your Raspberry Pi. Please remove the drive(s) you don't want to use for Citadel," + echo "then reboot your Raspberry Pi by running 'sudo reboot'." + exit 0 + fi + fi + + echo "The debug script did not automatically detect any issues with your Citadel." + if [[ $upload = true ]]; then + echo "Please copy the following link and share it with us on Telegram so we can help you with your problem." + if [[ $tor = true ]]; then + echo "${OWN_OUTPUT}" | torupload + else + echo "${OWN_OUTPUT}" | upload + fi + elif [[ $instructions = true ]]; then + echo "Please copy the entire output of this script and share it with us on Telegram so we can help you with your problem." + echo "It's recommended to upload the output somewhere and share a link to it. Run this script with '--upload' to automatically generate a link to share." + fi +fi \ No newline at end of file diff --git a/scripts/lib/__init__.py b/scripts/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/lib/rpcauth.py b/scripts/lib/rpcauth.py new file mode 100644 index 0000000..eac32f4 --- /dev/null +++ b/scripts/lib/rpcauth.py @@ -0,0 +1,42 @@ +# Copyright (c) 2015-2018 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +# SPDX-FileCopyrightText: 2015-2018 The Bitcoin Core developers +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +from argparse import ArgumentParser +from base64 import urlsafe_b64encode +from binascii import hexlify +from getpass import getpass +from os import urandom + +import hmac + +def generate_salt(size): + """Create size byte hex salt""" + return hexlify(urandom(size)).decode() + +def generate_password(): + """Create 32 byte b64 password""" + return urlsafe_b64encode(urandom(32)).decode('utf-8') + +def password_to_hmac(salt, password): + m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256') + return m.hexdigest() + +def get_data(username: str, password=None): + # If no password is given, then get it from generate_password() + if password is None: + password = generate_password() + + # Create 16 byte hex salt + salt = generate_salt(16) + password_hmac = password_to_hmac(salt, password) + + return { + 'conf_data': 'rpcauth={0}:{1}${2}'.format(username, salt, password_hmac), + 'auth': '{0}:{1}${2}'.format(username, salt, password_hmac), + 'password': password + } diff --git a/scripts/memory-usage b/scripts/memory-usage new file mode 100755 index 0000000..bd41e99 --- /dev/null +++ b/scripts/memory-usage @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2020 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/..)" + +# Fail if not running as root +if [[ $EUID -ne 0 ]]; then + echo "This script must be run as root" 1>&2 + exit 1 +fi + +# Get the memory usage of a docker container by name +function get_memory_usage() { + docker stats --no-stream --format "{{.MemPerc}}" "$1" | sed "s/%//" +} + +# Convert a memory usage in MiB to the percentage of the total memory +# With two decimal places +function mem_usage_to_percent() { + local mem_usage="$1" + local total_mem="$(free -m | awk 'NR==2 {print $2}')" + echo "$(awk "BEGIN {printf \"%.1f\", $mem_usage / $total_mem * 100}")" +} + +get_total_used_mem_raw() { + free -m | awk 'NR==2 {print $3}' +} + +get_total_used_mem() { + echo "$(mem_usage_to_percent "$(get_total_used_mem_raw)")" +} + +# To get the containers of the app, list every container whose name starts with the name of the app +get_app_containers () { + local app_name="$1" + "${CITADEL_ROOT}/app/app-manager.py" compose "${app_name}" ps | awk '{print $1}' | grep -v 'Name\|-----' +} + +# Get the memory usage of the whole system, excluding docker containers +get_system_memory_usage() { + local docker_usage_all="$(docker stats --no-stream --format "{{.MemUsage}}" | awk '{sum+=$1} END {print sum}')" + # Now, subtract that from get_total_used_mem_raw, and convert the output to a percentage + local total_usage="$(get_total_used_mem_raw)" + local system_usage="$(awk "BEGIN {printf \"%.1f\", $total_usage - $docker_usage_all}")" + echo "$(mem_usage_to_percent "$system_usage")" +} + +main() { + echo "total: $(get_total_used_mem)%"& + for service in bitcoin lnd electrs tor; do + echo "${service}: $(get_memory_usage "$service")%" & + done + for app in $("${CITADEL_ROOT}/app/app-manager.py" ls-installed); do + # For every container of the app, get the mem usage, save it, and at the end, print the total mem usage of the app + local mem_usage=0 + for container in $(get_app_containers "$app"); do + # Use awk to add, it supports floating point numbers + mem_usage=$(awk "BEGIN {printf \"%.2f\", $mem_usage + $(get_memory_usage "$container")}") + done + wait + echo "${app}: $mem_usage%" + done + echo "system: $(get_system_memory_usage)%" + wait +} + +main | sort --key 2 --numeric-sort --reverse diff --git a/scripts/start b/scripts/start new file mode 100755 index 0000000..370f02e --- /dev/null +++ b/scripts/start @@ -0,0 +1,137 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +# Start Citadel + +if [[ $UID != 0 ]]; then + echo "Citadel must be started as root" + echo "Please re-run this script as" + echo " sudo ./scripts/start" + exit 1 +fi + +check_dependencies () { + for cmd in "$@"; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +# Check system's dependencies +check_dependencies readlink dirname ip docker + +# Check karen's dependencies +check_dependencies fswatch + +# Check OTA update scripts' dependencies +check_dependencies rsync jq curl + +CITADEL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/.." +CITADEL_LOGS="${CITADEL_ROOT}/logs" + +if [[ ! -d "$CITADEL_ROOT" ]]; then + echo "Root dir does not exist '$CITADEL_ROOT'" + exit 1 +fi + +# Configure Umbrel if it isn't already configured +if [[ ! -f "${CITADEL_ROOT}/statuses/configured" ]]; then + NGINX_PORT=${NGINX_PORT:-80} NETWORK="${NETWORK:-mainnet}" "${CITADEL_ROOT}/scripts/configure" +fi + +echo +echo "======================================" +echo "============= STARTING ===============" +echo "============= CITADEL ================" +echo "======================================" +echo + +echo "Setting environment variables..." +echo + +# Check Citadel OS +[[ -f "/etc/default/citadel" ]] && source "/etc/default/citadel" +if [[ -z "${CITADEL_OS:-}" ]]; then + export IS_CITADEL_OS="false" +else + export IS_CITADEL_OS="true" +fi + +# Whitelist device IP, hostname and hidden service for CORS +DEVICE_IP=$(hostname -I | awk '{print $1}') +DEVICE_HOSTNAME="$(hostname)" +DEVICE_HOSTS="http://${DEVICE_IP},http://${DEVICE_HOSTNAME}.local,https://${DEVICE_HOSTNAME}.local,http://${DEVICE_HOSTNAME},https://${DEVICE_HOSTNAME}" +if [[ -f "${CITADEL_ROOT}/tor/data/web/hostname" ]]; then + hidden_service_url=$(cat "${CITADEL_ROOT}/tor/data/web/hostname") + DEVICE_HOSTS="${DEVICE_HOSTS},http://${hidden_service_url}" +fi +export DEVICE_HOSTS=$DEVICE_HOSTS +export DEVICE_HOSTNAME="${DEVICE_HOSTNAME}.local" + +# Increase default Docker and Compose timeouts to 240s +# as bitcoin can take a long while to respond +export DOCKER_CLIENT_TIMEOUT=240 +export COMPOSE_HTTP_TIMEOUT=240 + +cd "$CITADEL_ROOT" + +echo "Starting karen..." +echo +./karen &>> "${CITADEL_LOGS}/karen.log" & + +echo "Starting status monitors..." +pkill -f ./scripts/status-monitor || true +./scripts/status-monitor memory 60 &>> "${CITADEL_LOGS}/status-monitor.log" & +./scripts/status-monitor storage 60 &>> "${CITADEL_LOGS}/status-monitor.log" & +./scripts/status-monitor temperature 15 &>> "${CITADEL_LOGS}/status-monitor.log" & +./scripts/status-monitor uptime 15 &>> "${CITADEL_LOGS}/status-monitor.log" & + +echo "Starting backup monitor..." +echo +./scripts/backup/monitor &>> "${CITADEL_LOGS}/backup-monitor.log" & + +echo "Starting decoy backup trigger..." +echo +./scripts/backup/decoy-trigger &>> "${CITADEL_LOGS}/backup-decoy-trigger.log" & + +echo +echo "Resetting config files" +echo +./scripts/configure + +echo +echo "Starting Docker services..." +echo +docker compose up --detach --build --remove-orphans || { + echo "Failed to start containers" + exit 1 +} +echo + +# Unlock the user file on each start of Umbrel to avoid issues +# Normally, the user file shouldn't ever be locked, if it is, something went wrong, but it could still be working +if [[ -f "${CITADEL_ROOT}/db/user.json.lock" ]]; then + echo "WARNING: The user file was locked, Citadel probably wasn't shut down properly" + rm "${CITADEL_ROOT}/db/user.json.lock" +fi + +echo +echo "Starting installed apps..." +echo +./app/app-manager.py start installed +echo + +echo "Citadel is now accessible at" +echo " http://${DEVICE_HOSTNAME}" +echo " http://${DEVICE_IP}" +if [[ ! -z "${hidden_service_url:-}" ]]; then + echo " http://${hidden_service_url}" +fi diff --git a/scripts/status-monitor b/scripts/status-monitor new file mode 100755 index 0000000..fc89021 --- /dev/null +++ b/scripts/status-monitor @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/..)" + +resource="${1}" +interval="${2}"´ + +status_script="${CITADEL_ROOT}/scripts/status/${resource}" +output_path="${CITADEL_ROOT}/statuses/${resource}-status.json" + +# Every $interval seconds, run the status script and write the output to the $output_path. +while true; do + "${status_script}" > "${output_path}" + sleep "${interval}" +done diff --git a/scripts/status/memory b/scripts/status/memory new file mode 100755 index 0000000..e7653b4 --- /dev/null +++ b/scripts/status/memory @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +memory_total_bytes() { + free --bytes | awk 'NR==2 {print $2}' +} + +memory_used_bytes() { + free --bytes | awk 'NR==2 {print $3}' +} + +get_container_memory_use() { + docker stats --no-stream --format "{{.MemPerc}}" "$1" | sed "s/%//" +} + +get_app_memory_use() { + local app="${1}" + + local app_memory=0 + + local app_containers=$("${CITADEL_ROOT}/app/app-manager.py" compose "${app}" ps | awk '{print $1}' | grep -v 'Name\|-----') + for container in $app_containers; do + local container_memory=$(get_container_memory_use "${container}") + app_memory=$(awk "BEGIN {print ${app_memory}+${container_memory}}") + done + + # Above values return % of total memory used so we need to convert to bytes + total=$(memory_total_bytes) + awk "BEGIN {print int(${total}*${app_memory}/100)}" +} + +json="{}" + +total=$(memory_total_bytes) +json=$(echo $json | jq --arg total "${total}" '. + {total: $total|tonumber}') + +used=$(memory_used_bytes) +json=$(echo $json | jq --arg used "${used}" '. + {used: $used|tonumber}') + +cumulative_app_memory="0" +for app in $( "${CITADEL_ROOT}/app/app-manager.py" ls-installed); do + app_memory=$(get_app_memory_use "${app}") + cumulative_app_memory=$(($cumulative_app_memory+$app_memory)) + json=$(echo $json | jq --arg app "${app}" --arg app_memory "${app_memory}" '.breakdown |= .+ [{id: $app, used: $app_memory|tonumber}]') +done + +citadel=$(($used-$cumulative_app_memory)) +json=$(echo $json | jq --arg citadel "${citadel}" '.breakdown |= .+ [{id: "citadel", used: $citadel|tonumber}]') + +echo $json | jq '.breakdown |= sort_by(-.used)' diff --git a/scripts/status/storage b/scripts/status/storage new file mode 100755 index 0000000..9e1a2d0 --- /dev/null +++ b/scripts/status/storage @@ -0,0 +1,42 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +filesystem_total_storage_bytes() { + local directory="${1}" + df --block-size=1 --output=size "${directory}" | tail -n 1 +} + +filesystem_used_storage_bytes() { + local directory="${1}" + df --block-size=1 --output=used "${directory}" | tail -n 1 +} + +directory_size_bytes() { + local directory="${1}" + du --block-size=1 --max-depth=0 "${directory}" | awk '{print $1}' +} + +json="{}" + +total=$(filesystem_total_storage_bytes "${CITADEL_ROOT}") +json=$(echo $json | jq --arg total "${total}" '. + {total: $total|tonumber}') + +used=$(filesystem_used_storage_bytes "${CITADEL_ROOT}") +json=$(echo $json | jq --arg used "${used}" '. + {used: $used|tonumber}') + +cumulative_app_size="0" +for app in $( "${CITADEL_ROOT}/app/app-manager.py" ls-installed); do + app_size=$(directory_size_bytes "${CITADEL_ROOT}/app-data/${app}") + cumulative_app_size=$(($cumulative_app_size+$app_size)) + json=$(echo $json | jq --arg app "${app}" --arg app_size "${app_size}" '.breakdown |= .+ [{id: $app, used: $app_size|tonumber}]') +done + +citadel=$(($used-$cumulative_app_size)) +json=$(echo $json | jq --arg citadel "${citadel}" '.breakdown |= .+ [{id: "citadel", used: $citadel|tonumber}]') + +echo $json | jq '.breakdown |= sort_by(-.used)' diff --git a/scripts/status/temperature b/scripts/status/temperature new file mode 100755 index 0000000..ed9c891 --- /dev/null +++ b/scripts/status/temperature @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# If vcgencmd is available, use it to get the temperature and exit +if command -v vcgencmd &> /dev/null; then + echo "$(vcgencmd measure_temp)" | cut -d '=' -f 2 | cut -d '.' -f 1 + exit 0 +fi + +cat /sys/class/thermal/thermal_zone0/temp | awk '{print int($1/1000)}' diff --git a/scripts/status/uptime b/scripts/status/uptime new file mode 100755 index 0000000..cb33614 --- /dev/null +++ b/scripts/status/uptime @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +cat /proc/uptime | awk '{print int($1)}' diff --git a/scripts/stop b/scripts/stop new file mode 100755 index 0000000..d1e2b7c --- /dev/null +++ b/scripts/stop @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +# Stop Citadel + +if [[ $UID != 0 ]]; then + echo "Citadel must be stopped as root" + echo "Please re-run this script as" + echo " sudo ./scripts/stop" + exit 1 +fi + +CITADEL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/.." + +if [[ ! -d "$CITADEL_ROOT" ]]; then + echo "Root dir does not exist '$CITADEL_ROOT'" + exit 1 +fi + +cd "$CITADEL_ROOT" + +# Increase default Docker and Compose timeouts to 240s +# As bitcoin can take a long while to respond +export DOCKER_CLIENT_TIMEOUT=240 +export COMPOSE_HTTP_TIMEOUT=240 + +echo "Stopping installed apps..." +echo +"${CITADEL_ROOT}/app/app-manager.py" stop installed & +echo + +echo "Stopping Docker services..." +echo +docker compose down & + +echo "Waiting for everything to finish" +wait + diff --git a/scripts/update/.updateignore b/scripts/update/.updateignore new file mode 100644 index 0000000..5b41489 --- /dev/null +++ b/scripts/update/.updateignore @@ -0,0 +1,11 @@ +/.* +bitcoin/* +/db/* +lnd/* +statuses +tor/* +electrs/* +events/signals +logs/* +app-data/* +apps/networking.json diff --git a/scripts/update/.updateignore.license b/scripts/update/.updateignore.license new file mode 100644 index 0000000..19edadc --- /dev/null +++ b/scripts/update/.updateignore.license @@ -0,0 +1,4 @@ +SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +SPDX-FileCopyrightText: 2021 Citadel and contributors. + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/scripts/update/.updateinclude b/scripts/update/.updateinclude new file mode 100644 index 0000000..f68e60c --- /dev/null +++ b/scripts/update/.updateinclude @@ -0,0 +1,8 @@ +.env +bitcoin/bitcoin.conf +tor/torrc-apps +tor/torrc-apps-2 +tor/torrc-apps-3 +tor/torrc-umbrel +electrs/electrs.toml +apps/docker-compose.common.yml diff --git a/scripts/update/.updateinclude.license b/scripts/update/.updateinclude.license new file mode 100644 index 0000000..19edadc --- /dev/null +++ b/scripts/update/.updateinclude.license @@ -0,0 +1,4 @@ +SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +SPDX-FileCopyrightText: 2021 Citadel and contributors. + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/scripts/update/00-run.sh b/scripts/update/00-run.sh new file mode 100755 index 0000000..82ba937 --- /dev/null +++ b/scripts/update/00-run.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +RELEASE=$1 +CITADEL_ROOT=$2 + +# Check if $CITADEL_ROOT/.umbrel-$RELEASE exists, if it does, rename it to $CITADEL_ROOT/.citadel-$RELEASE +if [ -d "$CITADEL_ROOT/.umbrel-$RELEASE" ]; then + echo "Migrating from Umbrel..." + echo "Your Umbrel will now be turned into a Citadel" + echo "Please contact the Citadel team if anything goes wrong during the update" + mv "$CITADEL_ROOT/.umbrel-$RELEASE" "$CITADEL_ROOT/.citadel-$RELEASE" +fi + +echo +echo "=======================================" +echo "=============== UPDATE ================" +echo "=======================================" +echo "========= Stage: Pre-update ===========" +echo "=======================================" +echo + +# Stop karen early +pkill -f "\./karen" || true + +# Make sure any previous backup doesn't exist +if [[ -d "$CITADEL_ROOT"/.citadel-backup ]]; then + echo "Cannot install update. A previous backup already exists at $CITADEL_ROOT/.citadel-backup" + echo "This can only happen if the previous update installation wasn't successful" + exit 1 +fi + +echo "Installing Citadel $RELEASE at $CITADEL_ROOT" + +# Update status file +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 20, "description": "Backing up", "updateTo": "$RELEASE"} +EOF + + +# Backup +echo "Backing up existing directory tree" + +rsync -av \ + --include-from="$CITADEL_ROOT/.citadel-$RELEASE/scripts/update/.updateinclude" \ + --exclude-from="$CITADEL_ROOT/.citadel-$RELEASE/scripts/update/.updateignore" \ + "$CITADEL_ROOT"/ \ + "$CITADEL_ROOT"/.citadel-backup/ + +echo "Successfully backed up to $CITADEL_ROOT/.citadel-backup" diff --git a/scripts/update/01-run.sh b/scripts/update/01-run.sh new file mode 100755 index 0000000..030f6c6 --- /dev/null +++ b/scripts/update/01-run.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +RELEASE=$1 +CITADEL_ROOT=$2 + +# Only used on Umbrel OS and Citadel OS +SD_CARD_CITADEL_ROOT="/sd-root${CITADEL_ROOT}" + +echo +echo "=======================================" +echo "=============== UPDATE ================" +echo "=======================================" +echo "=========== Stage: Install ============" +echo "=======================================" +echo + +[[ -f "/etc/default/umbrel" ]] && source "/etc/default/umbrel" +[[ -f "/etc/default/citadel" ]] && source "/etc/default/citadel" + +IS_MIGRATING=0 +# Check if UMBREL_OS is set +if [[ ! -z "${UMBREL_OS:-}" ]]; then + echo "Umbrel OS is no longer supported." + cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 50, "description": "We're sorry, but you tried installing the update on an unsupported OS. Please unplug your node and reflash the SD card with Citadel OS to continue.", "updateTo": "$RELEASE"} +EOF + rm "${CITADEL_ROOT}/statuses/update-in-progress" + docker stop bitcoin + docker stop lnd + docker stop electrs + exit 1 +fi + +# If the Citadel OS version is 0.0.1, fail +if [[ ! -z "${CITADEL_OS:-}" ]] && [[ "${CITADEL_OS}" == "0.0.1" ]]; then + echo "Citadel OS version is 0.0.1. This is not supported." + cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 50, "description": "We're sorry, but you tried installing the update on an unsupported OS. Please unplug your node and reflash the SD card with Citadel OS to continue.", "updateTo": "$RELEASE"} +EOF + rm "${CITADEL_ROOT}/statuses/update-in-progress" + docker stop bitcoin + docker stop lnd + docker stop electrs + echo "We're sorry, but you tried installing the update on an unsupported OS. Please unplug your node and reflash the SD card with Citadel OS to continue." + exit 1 +fi + +# Make Citadel OS specific updates +if [[ ! -z "${CITADEL_OS:-}" ]]; then + echo + echo "=============================================" + echo "Installing on Citadel OS $CITADEL_OS" + echo "=============================================" + echo + + # Update SD card installation + if [[ -f "${SD_CARD_CITADEL_ROOT}/.umbrel" ]] || [[ -f "${SD_CARD_CITADEL_ROOT}/.citadel" ]]; then + echo "Replacing ${SD_CARD_CITADEL_ROOT} on SD card with the new release" + rsync --archive \ + --verbose \ + --include-from="${CITADEL_ROOT}/.citadel-${RELEASE}/scripts/update/.updateinclude" \ + --exclude-from="${CITADEL_ROOT}/.citadel-${RELEASE}/scripts/update/.updateignore" \ + --delete \ + "${CITADEL_ROOT}/.citadel-${RELEASE}/" \ + "${SD_CARD_CITADEL_ROOT}/" + + echo "Fixing permissions" + chown -R 1000:1000 "${SD_CARD_CITADEL_ROOT}/" + else + echo "ERROR: No Umbrel or Citadel installation found at SD root ${SD_CARD_CITADEL_ROOT}" + echo "Skipping updating on SD Card..." + fi + + # This makes sure systemd services are always updated (and new ones are enabled). + CITADEL_SYSTEMD_SERVICES="${CITADEL_ROOT}/.citadel-${RELEASE}/scripts/citadel-os/services/*.service" + for service_path in $CITADEL_SYSTEMD_SERVICES; do + service_name=$(basename "${service_path}") + install -m 644 "${service_path}" "/etc/systemd/system/${service_name}" + systemctl enable "${service_name}" + done +fi + +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 33, "description": "Configuring settings", "updateTo": "$RELEASE"} +EOF + +# Checkout to the new release +cd "$CITADEL_ROOT"/.citadel-"$RELEASE" + +# Configure new install +echo "Configuring new release" +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 40, "description": "Configuring new release", "updateTo": "$RELEASE"} +EOF + +./scripts/configure + +# Pulling new containers +echo "Pulling new containers" +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 50, "description": "Pulling new containers", "updateTo": "$RELEASE"} +EOF +docker compose pull + +# Stopping karen +echo "Stopping background daemon" +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 65, "description": "Stopping background daemon", "updateTo": "$RELEASE"} +EOF +pkill -f "\./karen" || true + +# Overlay home dir structure with new dir tree +echo "Overlaying $CITADEL_ROOT/ with new directory tree" +rsync --archive \ + --verbose \ + --include-from="$CITADEL_ROOT/.citadel-$RELEASE/scripts/update/.updateinclude" \ + --exclude-from="$CITADEL_ROOT/.citadel-$RELEASE/scripts/update/.updateignore" \ + --delete \ + "$CITADEL_ROOT"/.citadel-"$RELEASE"/ \ + "$CITADEL_ROOT"/ + +# Fix permissions +echo "Fixing permissions" +find "$CITADEL_ROOT" -path "$CITADEL_ROOT/app-data" -prune -o -exec chown 1000:1000 {} + +chmod -R 700 "$CITADEL_ROOT"/tor/data/* + +# If "$CITADEL_ROOT"/db/umbrel-seed exists, move it to "$CITADEL_ROOT"/db/citadel-seed +if [[ -f "$CITADEL_ROOT"/db/umbrel-seed ]]; then + echo "Moving $CITADEL_ROOT/db/umbrel-seed to $CITADEL_ROOT/db/citadel-seed" + mv "$CITADEL_ROOT"/db/umbrel-seed "$CITADEL_ROOT"/db/citadel-seed +fi + +cd "$CITADEL_ROOT" +echo "Updating installed apps" +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 70, "description": "Updating installed apps", "updateTo": "$RELEASE"} +EOF +"${CITADEL_ROOT}/app/app-manager.py" update-online +for app in $("$CITADEL_ROOT/app/app-manager.py" ls-installed); do + if [[ "${app}" != "" ]]; then + echo "${app}..." + "${CITADEL_ROOT}/app/app-manager.py" compose "${app}" pull + fi +done +wait + +# If CITADEL_ROOT doesn't contain services/installed.json, then put '["electrs"]' into it. +# This is to ensure that the 0.5.0 update doesn't remove electrs. +if [[ ! -f "${CITADEL_ROOT}/services/installed.json" ]]; then + echo '["electrs"]' > "${CITADEL_ROOT}/services/installed.json" +fi + +# Start updated containers +echo "Starting new containers" +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 80, "description": "Starting new containers", "updateTo": "$RELEASE"} +EOF +cd "$CITADEL_ROOT" +docker network rm citadel_main_network || true +./scripts/start + +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "success", "progress": 100, "description": "Successfully installed Citadel $RELEASE", "updateTo": ""} +EOF + +# Make Citadel OS specific post-update changes +if [[ ! -z "${CITADEL_OS:-}" ]]; then + # Delete unused Docker images on Citadel OS + echo "Deleting previous images" + docker image prune --all --force +fi diff --git a/scripts/update/02-run.sh b/scripts/update/02-run.sh new file mode 100755 index 0000000..c8d4ea6 --- /dev/null +++ b/scripts/update/02-run.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +RELEASE=$1 +CITADEL_ROOT=$2 + +echo +echo "=======================================" +echo "=============== UPDATE ================" +echo "=======================================" +echo "========= Stage: Post-update ==========" +echo "=======================================" +echo + +# Nothing here for now diff --git a/scripts/update/03-run.sh b/scripts/update/03-run.sh new file mode 100755 index 0000000..d647803 --- /dev/null +++ b/scripts/update/03-run.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +set -euo pipefail + +RELEASE=$1 +CITADEL_ROOT=$2 + +echo +echo "=======================================" +echo "=============== UPDATE ================" +echo "=======================================" +echo "=========== Stage: Success ============" +echo "=======================================" +echo + +# Cleanup +echo "Removing backup" +[[ -d "$CITADEL_ROOT"/.umbrel-backup ]] && rm -rf "$CITADEL_ROOT"/.umbrel-backup +[[ -d "$CITADEL_ROOT"/.citadel-backup ]] && rm -rf "$CITADEL_ROOT"/.citadel-backup + +echo "Successfully installed Citadel $RELEASE" +echo "Thank you for using Citadel!" diff --git a/scripts/update/README.md b/scripts/update/README.md new file mode 100644 index 0000000..cb07466 --- /dev/null +++ b/scripts/update/README.md @@ -0,0 +1,74 @@ + + +# Over-The-Air (OTA) Updates +How over-the-air updates work on Citadel. + +## Execution Flow + +1. New developments across the any/entire fleet of Citadel's services (bitcoind, lnd, dashboard, middleware, etc) are made, which maintain their own independent version-control and release-schedule. Subsequently, their new docker images are built, tagged and pushed to Docker Hub. + +2. The newly built and tagged images are updated in the main repository's (i.e. this repo) [`docker-compose.yml`](https://github.com/runcitadel/core/blob/main/docker-compose.yml) file. + +3. Any new developments to the main repository (i.e. this repo) are made, eg. adding a new directory or a new config file. + +4. To prepare a new release of Citadel, called `vX.Y.Z`, a PR is opened that updates the version in [`README.md`](https://github.com/runcitadel/core/blob/main/README.md) and [`info.json`](https://github.com/runcitadel/core/blob/main/info.json) file to: + +```json +{ + "version": "X.Y.Z", + "name": "Citadel vX.Y.Z", + "notes": "This release contains a number of bug fixes and new features.", + "requires": ">=A.B.C" +} +``` + +5. Once the PR is merged, the main branch is immediately tagged `vX.Y.Z` and released on GitHub. + +6. Thus the new `info.json` will automatically be available at `https://raw.githubusercontent.com/runcitadel/core/main/info.json`. This is what triggers the OTA update. + +6. When the user opens his [`dashboard`](https://github.com/runcitadel/dashboard-old), it periodically polls [`manager`](https://github.com/runcitadel/manager) to check for new updates. + +7. `manager` fetches the latest `info.json` from Citadel's main repo's main branch using `GET https://raw.githubusercontent.com/runcitadel/core/main/info.json`, compares it's `version` with the `version` of the local `$CITADEL_ROOT/info.json` file, and exits if both the versions are same. + +8. If fetched `version` > local `version`, `manager` checks if local `version` satisfies the `requires` condition in the fetched `info.json`. + +9. If not, `manager` computes the minimum satisfactory version, called `L.M.N`, required for update. Eg, for `"requires": ">=1.2.2"` the minimum satisfactory version would be `1.2.2`. `manager` then makes a `GET` request to `https://raw.githubusercontent.com/runcitadel/core/vL.M.N/info.json` and repeats step 8 and 9 until local `version` < fetched `version` **AND** local `version` fulfills the fetched `requires` condition. + +10. `manager` then returns the satisfying `info.json` to `dashboard`. + +11. `dashboard` then alerts the user regarding the available update, and after the user consents, it makes a `POST` request to `manager` to start the update process. + +12. `manager` adds the `updateTo` key to `$CITADEL_ROOT/statuses/update-status.json` (a file used to continuosly update the user with the update status and progress) with the update release tag. + +```json +{ + ... + "updateTo": "vX.Y.Z" + ... +} +``` + +13. `manager` then creates an update signal file on the mounted host OS volume (`$CITADEL_ROOT/events/signals/update`) and returns `OK` to the `dashboard`. + +14. [`karen`](https://github.com/runcitadel/core/blob/main/karen) is triggered (obviously) as soon as `$CITADEL_ROOT/events/signals/update` is touched/updated, and immediately runs the `update` trigger script [`$CITADEL_ROOT/events/triggers/update`](https://github.com/runcitadel/core/blob/main/events/triggers/update) as root. + +15. `$CITADEL_ROOT/events/triggers/update` clones release `vX.Y.Z` from github in `$CITADEL_ROOT/.umbrel-vX.Y.Z`. + +16. `$CITADEL_ROOT/events/triggers/update` then executes all of the following update scripts from the new release `$CITADEL_ROOT/.umbrel-vX.Y.Z` one-by-one: + +- [`$CITADEL_ROOT/.umbrel-vX.Y.Z/scripts/update/00-run.sh`](https://github.com/runcitadel/core/blob/main/scripts/update/00-run.sh): Pre-update preparation script (does things like making a backup) +- [`$CITADEL_ROOT/.umbrel-vX.Y.Z/scripts/update/01-run.sh`](https://github.com/runcitadel/core/blob/main/scripts/update/01-run.sh): Install update script (installs the update) +- [`$CITADEL_ROOT/.umbrel-vX.Y.Z/scripts/update/02-run.sh`](https://github.com/runcitadel/core/blob/main/scripts/update/02-run.sh): Post-update script (used to run unit-tests to make sure the update was successfully installed) +- [`$CITADEL_ROOT/.umbrel-vX.Y.Z/scripts/update/03-run.sh`](https://github.com/runcitadel/core/blob/main/scripts/update/03-run.sh): Success script (runs after the updated has been successfully downloaded and installed) + +All of the above scripts continuously update `$CITADEL_ROOT/statuses/update-status.json` with the progress of update, which the dashboard periodically fetches every 2s via `manager` to keep the user updated. + +### Further improvements + +- OTA updates should not trust GitHub, they should verify signed checksums before installing +- Catch any error during the update and restore from the backup +- Restore from backup on power-failure diff --git a/scripts/update/update b/scripts/update/update new file mode 100755 index 0000000..f9182a6 --- /dev/null +++ b/scripts/update/update @@ -0,0 +1,133 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +if [[ $UID != 0 ]]; then + echo "Update script must be run as root" + exit 1 +fi + +check_dependencies () { + for cmd in "$@"; do + if ! command -v "$cmd" >/dev/null 2>&1; then + echo "This script requires \"${cmd}\" to be installed" + exit 1 + fi + done +} + +check_dependencies jq curl rsync + +CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)" + +update_type="" +if [[ "${1}" == "--ota" ]]; then + update_type="ota" +elif [[ "${1}" == "--path" ]]; then + update_type="path" + update_path="${2}" +elif [[ "${1}" == "--repo" ]]; then + update_type="repo" + descriptor="${2}" + if [[ "${descriptor}" != *"#"* ]]; then + descriptor="${descriptor}#main" + fi + repo="${descriptor%%#*}" + branch="${descriptor#*#}" +else + echo "Update requires \"--ota\", \"--path \", or \"--repo user/repo[#branch]\" option." + exit 1 +fi + +if [[ "${update_type}" == "repo" ]]; then + repo_path="/tmp/citadel-update/" + rm -rf "${repo_path}" 2> /dev/null || true + mkdir -p "${repo_path}" + git clone --single-branch --branch "${branch}" "https://github.com/${repo}.git" "${repo_path}" + + # Now hand over to the path updater + update_type="path" + update_path="${repo_path}" +fi + +if [[ "${update_type}" == "path" ]] && [[ ! -f "${update_path}/.umbrel" ]] && [[ ! -f "${update_path}/.citadel" ]]; then + echo "Update path doesn't seem to be an Umbrel or Citadel install." + exit 1 +fi + +if [[ "${update_type}" == "ota" ]]; then + RELEASE=$(cat "$CITADEL_ROOT"/statuses/update-status.json | jq .updateTo -r) +elif [[ "${update_type}" == "path" ]]; then + RELEASE=$(cat "$update_path"/info.json | jq .version -r) +fi + +echo +echo "=======================================" +echo "=============== UPDATE ================" +echo "=======================================" +echo "========== Stage: Download ============" +echo "=======================================" +echo + +# Make sure an update is not in progres +if [[ -f "$CITADEL_ROOT/statuses/update-in-progress" ]]; then + echo "An update is already in progress. Exiting now." + exit 2 +fi + +echo "Creating lock" +touch "$CITADEL_ROOT"/statuses/update-in-progress + +# Cleanup just in case there's temp stuff lying around from previous update +echo "Cleaning up any previous mess" +[[ -d "$CITADEL_ROOT"/.citadel-"$RELEASE" ]] && rm -rf "$CITADEL_ROOT"/.citadel-"$RELEASE" + +# Update status file +cat < "$CITADEL_ROOT"/statuses/update-status.json +{"state": "installing", "progress": 10, "description": "Downloading Citadel $RELEASE", "updateTo": "$RELEASE"} +EOF + +# Download new release +if [[ "${update_type}" == "ota" ]]; then + echo "Downloading Citadel ${RELEASE}" + mkdir -p "${CITADEL_ROOT}/.citadel-${RELEASE}" + cd "${CITADEL_ROOT}/.citadel-${RELEASE}" + curl -L "https://github.com/runcitadel/core/archive/$RELEASE.tar.gz" | tar -xz --strip-components=1 +fi + +# Copy over new release from path +if [[ "${update_type}" == "path" ]]; then + echo "Copying Citadel ${RELEASE} from ${update_path}" + mkdir -p "${CITADEL_ROOT}/.citadel-${RELEASE}" + cp --recursive \ + --archive \ + --no-target-directory \ + "${update_path}" "${CITADEL_ROOT}/.citadel-${RELEASE}" + cd "${CITADEL_ROOT}/.citadel-${RELEASE}" +fi + +# Run update scripts +echo "Running update install scripts of the new release" +cd scripts/update +UPDATE_INSTALL_SCRIPTS=$(ls *-run.sh) +for script in $UPDATE_INSTALL_SCRIPTS; do + if [[ -x $script ]]; then + echo + echo "== Begin Update Script $script ==" + ./"$script" "$RELEASE" "$CITADEL_ROOT" + echo "== End Update Script $script ==" + echo + fi +done + +# Delete cloned repo +echo "Deleting cloned repository" +[[ -d "$CITADEL_ROOT"/.citadel-"$RELEASE" ]] && rm -rf "$CITADEL_ROOT"/.citadel-"$RELEASE" + +echo "Removing lock" +rm -f "$CITADEL_ROOT"/statuses/update-in-progress + +exit 0 diff --git a/services/electrs.yml b/services/electrs.yml new file mode 100644 index 0000000..4e511c1 --- /dev/null +++ b/services/electrs.yml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +electrs: + container_name: electrs + image: ghcr.io/runcitadel/electrs:main@sha256:86705bd425b9b20d0b83d8ef5673cee261766b5a50bcfa8e95ebfec2e5adfcae + working_dir: /data + volumes: + - ${PWD}/bitcoin:/bitcoin:ro + - ${PWD}/electrs:/data + restart: on-failure + stop_grace_period: 5m + ports: + - "$ELECTRUM_PORT:$ELECTRUM_PORT" + networks: + default: + ipv4_address: $ELECTRUM_IP diff --git a/services/manage.py b/services/manage.py new file mode 100755 index 0000000..061c89a --- /dev/null +++ b/services/manage.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +import json +from typing import List +import yaml +import os +import argparse + +# Print an error if user is not root +if os.getuid() != 0: + print('This script must be run as root!') + exit(1) + +# The directory with this script +scriptDir = os.path.dirname(os.path.realpath(__file__)) +nodeRoot = os.path.join(scriptDir, "..") + +parser = argparse.ArgumentParser(description="Manage services on your Citadel") +parser.add_argument('action', help='What to do with the service.', choices=["install", "uninstall", "setup"]) +parser.add_argument('--verbose', '-v', action='store_true') +parser.add_argument( + 'app', help='The service to perform an action on.', nargs='?') +args = parser.parse_args() + +# Function to install a service +# To install it, read the service's YAML file (nodeRoot/services/name.yml) and add it to the main compose file (nodeRoot/docker-compose.yml) +def installService(name): + # Read the YAML file + with open(os.path.join(nodeRoot, "services", name + ".yml"), 'r') as stream: + service = yaml.safe_load(stream) + + # Read the main compose file + with open(os.path.join(nodeRoot, "docker-compose.yml"), 'r') as stream: + compose = yaml.safe_load(stream) + + # Add the service to the main compose file + compose['services'].update(service) + + # Write the main compose file + with open(os.path.join(nodeRoot, "docker-compose.yml"), 'w') as stream: + yaml.dump(compose, stream, sort_keys=False) + # Save the service name in nodeRoot/services/installed.json, which is a JSON file with a list of installed services + # If the file doesn't exist, put [] in it, then run the code below + try: + with open(os.path.join(nodeRoot, "services", "installed.json"), 'r') as stream: + installed = yaml.safe_load(stream) + except FileNotFoundError: + installed = [] + installed.append(name) + with open(os.path.join(nodeRoot, "services", "installed.json"), 'w') as stream: + json.dump(list(set(installed)), stream, sort_keys=False) + + +def uninstallService(name): + # First check if a service yml definition exists to avoid uninstalling something that can't be installed or isn't supposed to be removed + if not os.path.isfile(os.path.join(nodeRoot, "services", name + ".yml")): + print("Service definition not found, cannot uninstall") + exit(1) + # Read the main compose file + with open(os.path.join(nodeRoot, "docker-compose.yml"), 'r') as stream: + compose = yaml.safe_load(stream) + + # Remove the service from the main compose file + try: + del compose['services'][name] + except KeyError: + pass + + # Write the main compose file + with open(os.path.join(nodeRoot, "docker-compose.yml"), 'w') as stream: + yaml.dump(compose, stream, sort_keys=False) + # Save the service name in nodeRoot/services/installed.json, which is a JSON file with a list of installed services + try: + with open(os.path.join(nodeRoot, "services", "installed.json"), 'r') as stream: + installed = yaml.safe_load(stream) + except FileNotFoundError: + installed = [] + try: + installed.remove(name) + except ValueError: + pass + with open(os.path.join(nodeRoot, "services", "installed.json"), 'w') as stream: + json.dump(list(set(installed)), stream, sort_keys=False) + +# install all services from installed.json +def installServices(): + try: + with open(os.path.join(nodeRoot, "services", "installed.json"), 'r') as stream: + installed: List[str] = yaml.safe_load(stream) + except FileNotFoundError: + installed: List[str] = [] + for service in installed: + installService(service) + + + +if args.action == "install": + installService(args.app) +elif args.action == "uninstall": + uninstallService(args.app) +elif args.action == "setup": + installServices() + \ No newline at end of file diff --git a/setenv b/setenv new file mode 100644 index 0000000..687e804 --- /dev/null +++ b/setenv @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: 2021 Aaron Dewes +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +CITADEL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))" + +echo "Citadel root directory is ${CITADEL_ROOT}" +alias update="${CITADEL_ROOT}/scripts/update/update" +alias lncli="docker exec -it lnd lncli" +alias bitcoin-cli="docker exec -it bitcoin bitcoin-cli" +alias docker-compose="sudo docker compose" +alias docker="sudo docker" +alias debug="${CITADEL_ROOT}/scripts/debug" diff --git a/statuses/password.license b/statuses/password.license new file mode 100644 index 0000000..864d85f --- /dev/null +++ b/statuses/password.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2020 Aaron Dewes + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/statuses/update-status.json b/statuses/update-status.json new file mode 100644 index 0000000..42df7de --- /dev/null +++ b/statuses/update-status.json @@ -0,0 +1,6 @@ +{ + "state": "success", + "progress": 100, + "description": "", + "updateTo": "" +} \ No newline at end of file diff --git a/statuses/update-status.json.license b/statuses/update-status.json.license new file mode 100644 index 0000000..783617a --- /dev/null +++ b/statuses/update-status.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file diff --git a/templates/.env-sample b/templates/.env-sample new file mode 100644 index 0000000..e0a85e9 --- /dev/null +++ b/templates/.env-sample @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors. +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +#Umbrel +NETWORK_IP= +GATEWAY_IP= +NGINX_IP= +NGINX_PORT= +DASHBOARD_IP= +MANAGER_IP= +MIDDLEWARE_IP= +NEUTRINO_SWITCHER_IP= +BITCOIN_NETWORK= +BITCOIN_IP= +BITCOIN_P2P_PORT= +BITCOIN_RPC_PORT= +BITCOIN_RPC_USER='' +BITCOIN_RPC_PASS='' +BITCOIN_RPC_AUTH='' +BITCOIN_ZMQ_RAWBLOCK_PORT= +BITCOIN_ZMQ_RAWTX_PORT= +BITCOIN_ZMQ_HASHBLOCK_PORT= +LND_IP= +LND_GRPC_PORT= +LND_REST_PORT= +ELECTRUM_IP= +ELECTRUM_PORT= +TOR_PROXY_IP= +TOR_PROXY_PORT= +TOR_PASSWORD='' +TOR_HASHED_PASSWORD='' +APPS_TOR_IP= +APPS_2_TOR_IP= +APPS_3_TOR_IP= +DOCKER_BINARY= diff --git a/templates/bitcoin-sample.conf b/templates/bitcoin-sample.conf new file mode 100644 index 0000000..c86ba68 --- /dev/null +++ b/templates/bitcoin-sample.conf @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Please note: This file can't be changed, it will be overwritten. +# Tor +proxy=: +listen=1 +bind= + +# Connections +port= +rpcport= +rpcbind= +rpcbind=127.0.0.1 +rpcallowip=/16 +rpcallowip=127.0.0.1 +rpcauth= + +# Memory +dbcache=200 +maxmempool=300 + + +# zmq +zmqpubrawblock=tcp://0.0.0.0: +zmqpubrawtx=tcp://0.0.0.0: +zmqpubhashblock=tcp://0.0.0.0: + +# Indexes +txindex=1 +blockfilterindex=1 + +# SPV +peerbloomfilters=1 +peerblockfilters=1 diff --git a/templates/electrs-sample.toml b/templates/electrs-sample.toml new file mode 100644 index 0000000..8fc039a --- /dev/null +++ b/templates/electrs-sample.toml @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors. +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Please note: This file can't be changed, it will be overwritten. +# A few modifications will be kept, including alias, color, channel size limitations and more if you contact us. + +verbose = 2 +network = "bitcoin" +db_dir = "/data/db" +daemon_dir = "/bitcoin" +daemon_rpc_addr = ":" +daemon_p2p_addr = ":" +electrum_rpc_addr = "0.0.0.0:" +server_banner = "Citadel v" diff --git a/templates/lnd-sample.conf b/templates/lnd-sample.conf new file mode 100644 index 0000000..1b1eb21 --- /dev/null +++ b/templates/lnd-sample.conf @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors. +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Please note: This file can't be changed, it will be overwritten. +# A few modifications will be kept, including alias, color, channel size limitations and more if you contact us. + +[Application Options] + +listen=0.0.0.0:9735 +rpclisten=0.0.0.0: +restlisten=0.0.0.0: +accept-keysend=true +tlsextraip= +tlsextradomain=.local +tlsautorefresh=1 +tlsdisableautofill=1 + +wallet-unlock-password-file=/walletpassword +wallet-unlock-allow-create=true +gc-canceled-invoices-on-startup=true +gc-canceled-invoices-on-the-fly=true +accept-amp=true + + +[protocol] +; Allow channels larger than 0.16 BTC +protocol.wumbo-channels=true + +[Bitcoind] +bitcoind.rpchost= +bitcoind.rpcuser= +bitcoind.rpcpass= +bitcoind.zmqpubrawblock=tcp://: +bitcoind.zmqpubrawtx=tcp://: + +[Bitcoin] +bitcoin.active=1 +bitcoin.=1 +# Default to neutrino as the node is +# automatically switched to bitcoind once +# IBD is complete +bitcoin.node= +bitcoin.defaultchanconfs=2 + + + + +; Enable watchtower to watch other nodes +[watchtower] +watchtower.active=1 + +; activate watchtower client so we can get get other servers +; to make sure no one steals our money +[wtclient] +wtclient.active=1 + +[tor] +tor.active=1 +tor.control=: +tor.socks=: +tor.targetipaddress= +tor.password= +tor.v3=1 + + diff --git a/templates/nginx-sample.conf b/templates/nginx-sample.conf new file mode 100644 index 0000000..3c93f99 --- /dev/null +++ b/templates/nginx-sample.conf @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +user nginx; +worker_processes 1; + +error_log /dev/stdout info; + +events { + worker_connections 1024; +} + +http { + access_log /dev/stdout; + + proxy_read_timeout 600; + + default_type application/octet-stream; + + server { + listen 80; + + location /api/ { + proxy_pass http://:3005/; + } + + location /manager-api/ { + proxy_pass http://:3006/; + } + + location / { + proxy_pass http://:3004/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + } + } +} diff --git a/templates/torrc-core-sample b/templates/torrc-core-sample new file mode 100644 index 0000000..1da1e8a --- /dev/null +++ b/templates/torrc-core-sample @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +# Bind only to "" which is the tor IP within the container +SocksPort : +ControlPort : + +# Citadel Core Services + +# Dashboard Hidden Service +HiddenServiceDir /var/lib/tor/web +HiddenServicePort 80 :80 + +# Bitcoin Core P2P Hidden Service +HiddenServiceDir /var/lib/tor/bitcoin-p2p +HiddenServicePort : + +# Bitcoin Core RPC Hidden Service +HiddenServiceDir /var/lib/tor/bitcoin-rpc +HiddenServicePort : + +# Electrum Server (electrs) Hidden Service +HiddenServiceDir /var/lib/tor/electrum +HiddenServicePort : + +# LND REST Hidden Service +HiddenServiceDir /var/lib/tor/lnd-rest +HiddenServicePort : + +# LND gRPC Hidden Service +HiddenServiceDir /var/lib/tor/lnd-grpc +HiddenServicePort : + +HashedControlPassword + diff --git a/templates/torrc-empty b/templates/torrc-empty new file mode 100644 index 0000000..bc5ceab --- /dev/null +++ b/templates/torrc-empty @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2021 Citadel and contributors +# +# SPDX-License-Identifier: AGPL-3.0-or-later + diff --git a/walletpassword b/walletpassword new file mode 100644 index 0000000..0594d3c --- /dev/null +++ b/walletpassword @@ -0,0 +1 @@ +moneyprintergobrrr \ No newline at end of file diff --git a/walletpassword.license b/walletpassword.license new file mode 100644 index 0000000..4551d97 --- /dev/null +++ b/walletpassword.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021 Aaron Dewes + +SPDX-License-Identifier: AGPL-3.0-or-later \ No newline at end of file