All downhill from here

This commit is contained in:
Oscar Mira 2022-02-06 21:30:14 +01:00
commit 90909a9816
161 changed files with 7904 additions and 0 deletions

8
.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
*.iml
.gradle
.idea
build
captures
.externalNativeBuild
.cxx
local.properties

12
.gitmodules vendored Normal file
View File

@ -0,0 +1,12 @@
[submodule "vendor/monero"]
path = vendor/monero
url = https://github.com/mollyim/monero.git
[submodule "vendor/boringssl"]
path = vendor/boringssl
url = https://boringssl.googlesource.com/boringssl
[submodule "vendor/unbound"]
path = vendor/unbound
url = https://github.com/NLnetLabs/unbound.git
[submodule "vendor/libsodium"]
path = vendor/libsodium
url = https://github.com/jedisct1/libsodium.git

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/philosophy/why-not-lgpl.html>.

28
build.gradle Normal file
View File

@ -0,0 +1,28 @@
plugins {
id('com.android.application') version '7.4.0' apply false
id('com.android.library') version '7.4.0' apply false
id('org.jetbrains.kotlin.android') version '1.8.0' apply false
id('org.jetbrains.kotlin.plugin.parcelize') version '1.8.0' apply false
id('com.google.devtools.ksp') version '1.8.0-1.0.9' apply false
id('com.google.protobuf') version '0.8.19' apply false
}
wrapper {
distributionType = Wrapper.DistributionType.ALL
}
allprojects {
group = 'im.molly'
ext {
gitVersion = gitVersion()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
static def gitVersion() {
return 'git describe --tags --always --first-parent'.execute().text.trim()
}

91
demo/android/build.gradle Normal file
View File

@ -0,0 +1,91 @@
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
apply plugin: 'com.google.devtools.ksp'
ext {
composeVersion = '1.4.0-alpha04'
composeCompilerVersion = '1.4.0'
lifecycleVersion = '2.6.0-alpha04'
roomVersion = '2.5.0'
}
android {
compileSdk 33
defaultConfig {
applicationId "im.molly.monero.demo"
minSdk 26
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion composeCompilerVersion
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation "androidx.core:core-ktx:1.9.0"
implementation "androidx.compose.ui:ui:$composeVersion"
implementation "androidx.compose.material3:material3:1.1.0-alpha04"
implementation "androidx.compose.ui:ui-tooling-preview:$composeVersion"
implementation "com.google.accompanist:accompanist-systemuicontroller:0.28.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-runtime-compose:$lifecycleVersion"
implementation "androidx.activity:activity-compose:1.6.1"
implementation "androidx.room:room-runtime:$roomVersion"
implementation "androidx.room:room-ktx:$roomVersion"
implementation "androidx.navigation:navigation-runtime-ktx:2.5.3"
implementation "androidx.navigation:navigation-compose:2.5.3"
implementation 'androidx.lifecycle:lifecycle-service:2.5.1'
implementation 'androidx.lifecycle:lifecycle-process:2.5.1'
ksp "androidx.room:room-compiler:$roomVersion"
implementation project(':lib')
testImplementation "junit:junit:4.13.2"
androidTestImplementation "androidx.test.ext:junit:1.1.5"
androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1"
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$composeVersion"
debugImplementation "androidx.compose.ui:ui-tooling:$composeVersion"
debugImplementation "androidx.compose.ui:ui-test-manifest:$composeVersion"
}

21
demo/android/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,179 @@
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "8e728fa24771d06bb2988df1356e07ec",
"entities": [
{
"tableName": "wallets",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `public_address` TEXT NOT NULL, `name` TEXT NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "publicAddress",
"columnName": "public_address",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallets_public_address",
"unique": true,
"columnNames": [
"public_address"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_wallets_public_address` ON `${TABLE_NAME}` (`public_address`)"
}
],
"foreignKeys": []
},
{
"tableName": "remote_nodes",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `net_type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `user` TEXT NOT NULL, `pwd` TEXT NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "networkId",
"columnName": "net_type",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "username",
"columnName": "user",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "password",
"columnName": "pwd",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_remote_nodes_net_type",
"unique": false,
"columnNames": [
"net_type"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_remote_nodes_net_type` ON `${TABLE_NAME}` (`net_type`)"
}
],
"foreignKeys": []
},
{
"tableName": "wallet_remote_nodes",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet_id` INTEGER NOT NULL, `remote_node_id` INTEGER NOT NULL, PRIMARY KEY(`wallet_id`, `remote_node_id`), FOREIGN KEY(`wallet_id`) REFERENCES `wallets`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`remote_node_id`) REFERENCES `remote_nodes`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "walletId",
"columnName": "wallet_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteNodeId",
"columnName": "remote_node_id",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"wallet_id",
"remote_node_id"
]
},
"indices": [
{
"name": "index_wallet_remote_nodes_wallet_id",
"unique": false,
"columnNames": [
"wallet_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallet_remote_nodes_wallet_id` ON `${TABLE_NAME}` (`wallet_id`)"
},
{
"name": "index_wallet_remote_nodes_remote_node_id",
"unique": false,
"columnNames": [
"remote_node_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallet_remote_nodes_remote_node_id` ON `${TABLE_NAME}` (`remote_node_id`)"
}
],
"foreignKeys": [
{
"table": "wallets",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallet_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "remote_nodes",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"remote_node_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8e728fa24771d06bb2988df1356e07ec')"
]
}
}

View File

@ -0,0 +1,24 @@
package im.molly.monero.demo
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("im.molly.monero.demo", appContext.packageName)
}
}

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="im.molly.monero.demo">
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Demo">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.Demo"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".service.SyncService"
android:exported="false" />
</application>
</manifest>

View File

@ -0,0 +1,51 @@
package im.molly.monero.demo
import android.app.Application
import androidx.room.Room
import im.molly.monero.demo.data.*
import okhttp3.OkHttpClient
/**
* Naive container of global instances.
*
* A complex app should use Koin or Hilt for dependencies.
*/
object AppModule {
lateinit var application: Application
private val applicationScope = kotlinx.coroutines.MainScope()
private val database: AppDatabase by lazy {
Room.databaseBuilder(
application, AppDatabase::class.java, "monero-demo.db"
).build()
}
private val walletHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder().build()
}
private val walletDataSource: WalletDataSource by lazy {
WalletDataSource(database.walletDao())
}
private val walletDataFileStorage: WalletDataFileStorage by lazy {
AppWalletDataFileStorage(application)
}
private val moneroSdkClient: MoneroSdkClient by lazy {
MoneroSdkClient(application, walletDataFileStorage, walletHttpClient)
}
val remoteNodeRepository: RemoteNodeRepository by lazy {
RemoteNodeRepository(database.remoteNodeDao())
}
val walletRepository: WalletRepository by lazy {
WalletRepository(moneroSdkClient, walletDataSource, applicationScope)
}
fun provide(application: Application) {
this.application = application
}
}

View File

@ -0,0 +1,71 @@
package im.molly.monero.demo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import im.molly.monero.demo.service.SyncService
import im.molly.monero.demo.ui.DemoApp
import im.molly.monero.demo.ui.theme.AppTheme
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
val systemUiController = rememberSystemUiController()
val darkTheme = isSystemInDarkTheme()
DisposableEffect(systemUiController, darkTheme) {
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = !darkTheme,
)
onDispose {}
}
AppTheme(
darkTheme = darkTheme,
) {
DemoApp()
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun connectToSyncService(): SyncService.LocalBinder =
suspendCancellableCoroutine { continuation ->
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as SyncService.LocalBinder
continuation.resume(binder) {
unbindService(this)
}
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
Intent(this@MainActivity, SyncService::class.java).also { intent ->
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
}

View File

@ -0,0 +1,23 @@
package im.molly.monero.demo
import android.app.Application
import android.os.StrictMode
import im.molly.monero.demo.service.SyncService
import im.molly.monero.isIsolatedProcess
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder(StrictMode.getVmPolicy())
.detectLeakedClosableObjects()
.build()
)
if (isIsolatedProcess()) {
return
}
AppModule.provide(this)
SyncService.start(this)
}
}

View File

@ -0,0 +1,21 @@
package im.molly.monero.demo.common
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
sealed interface Result<out T> {
data class Success<T>(val data: T) : Result<T>
data class Error(val exception: Throwable? = null) : Result<Nothing>
object Loading : Result<Nothing>
}
fun <T> Flow<T>.asResult(): Flow<Result<T>> {
return this
.map<T, Result<T>> {
Result.Success(it)
}
.onStart { emit(Result.Loading) }
.catch { emit(Result.Error(it)) }
}

View File

@ -0,0 +1,26 @@
package im.molly.monero.demo.data
import androidx.room.Database
import androidx.room.RoomDatabase
import im.molly.monero.demo.data.dao.RemoteNodeDao
import im.molly.monero.demo.data.dao.WalletDao
import im.molly.monero.demo.data.entity.RemoteNodeEntity
import im.molly.monero.demo.data.entity.WalletEntity
import im.molly.monero.demo.data.entity.WalletRemoteNodeXRef
private const val DATABASE_VERSION = 1
@Database(
entities = [
WalletEntity::class,
RemoteNodeEntity::class,
WalletRemoteNodeXRef::class,
// TransactionEntity::class,
],
version = DATABASE_VERSION,
exportSchema = true,
)
abstract class AppDatabase : RoomDatabase() {
abstract fun remoteNodeDao(): RemoteNodeDao
abstract fun walletDao(): WalletDao
}

View File

@ -0,0 +1,44 @@
package im.molly.monero.demo.data
import android.content.Context
import im.molly.monero.*
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
class MoneroSdkClient(
private val context: Context,
private val walletDataFileStorage: WalletDataFileStorage,
private val httpClient: OkHttpClient,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
suspend fun createWallet(moneroNetwork: MoneroNetwork): MoneroWallet =
withContext(ioDispatcher) {
val walletClient = WalletClient.forNetwork(
context = context,
network = moneroNetwork,
)
val wallet = walletClient.createNewWallet()
walletDataFileStorage.tryWriteData(wallet.publicAddress, false) { output ->
walletClient.saveWallet(wallet, output)
}
wallet
}
suspend fun openWallet(
publicAddress: String,
remoteNodeSelector: RemoteNodeSelector?,
): MoneroWallet =
withContext(ioDispatcher) {
val walletClient = WalletClient.forNetwork(
context = context,
network = MoneroNetwork.of(publicAddress),
nodeSelector = remoteNodeSelector,
httpClient = httpClient,
)
walletDataFileStorage.readData(publicAddress).use { input ->
walletClient.openWallet(input)
}
}
}

View File

@ -0,0 +1,30 @@
package im.molly.monero.demo.data
import im.molly.monero.demo.data.dao.RemoteNodeDao
import im.molly.monero.demo.data.entity.*
import im.molly.monero.demo.data.model.RemoteNode
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class RemoteNodeRepository(
private val remoteNodeDao: RemoteNodeDao,
) {
fun getRemoteNode(remoteNodeId: Long): Flow<RemoteNode> =
remoteNodeDao.findById(remoteNodeId).map { it.asExternalModel() }
fun getRemoteNodes(remoteNodeIds: List<Long>): Flow<List<RemoteNode>> =
remoteNodeDao.findByIds(remoteNodeIds).map { it.map(RemoteNodeEntity::asExternalModel) }
fun getAllRemoteNodes(filterNetworkIds: Set<Int> = emptySet()): Flow<List<RemoteNode>> =
if (filterNetworkIds.isEmpty()) {
remoteNodeDao.findAll()
} else {
remoteNodeDao.findByNetworkIds(filterNetworkIds)
}.map { it.map(RemoteNodeEntity::asExternalModel) }
suspend fun addOrUpdateRemoteNode(remoteNode: RemoteNode) =
remoteNodeDao.upsert(remoteNode.asEntity())
suspend fun deleteRemoteNode(remoteNode: RemoteNode) =
remoteNodeDao.delete(remoteNode.asEntity())
}

View File

@ -0,0 +1,59 @@
package im.molly.monero.demo.data
import android.content.Context
import android.util.AtomicFile
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
interface WalletDataFileStorage {
fun tryWriteData(
publicAddress: String,
canOverwrite: Boolean = true,
block: (FileOutputStream) -> Unit,
)
fun readData(publicAddress: String): FileInputStream
}
class AppWalletDataFileStorage(context: Context) : WalletDataFileStorage {
private val filesDir = context.filesDir
override fun tryWriteData(
publicAddress: String,
canOverwrite: Boolean,
block: (FileOutputStream) -> Unit,
) {
val file = getBackingFile(publicAddress)
if (!(canOverwrite || file.baseFile.createNewFile())) {
throw IOException("Data file already exists: ${file.baseFile.path}")
}
val output = file.startWrite()
try {
block(output)
file.finishWrite(output)
} catch (ioe: IOException) {
file.failWrite(output)
throw ioe
}
}
override fun readData(publicAddress: String): FileInputStream {
val file = getBackingFile(publicAddress)
return file.openRead()
}
private fun getBackingFile(publicAddress: String): AtomicFile {
val uniqueFilename = publicAddress.substring(0, 11) + ".wallet"
return AtomicFile(File(getOrCreateWalletDataDir(), uniqueFilename))
}
private fun getOrCreateWalletDataDir(): File {
val walletDataDir = File(filesDir, "wallet_data")
if (walletDataDir.exists() || walletDataDir.mkdir()) {
return walletDataDir
}
throw IOException("Cannot create wallet data directory: ${walletDataDir.path}")
}
}

View File

@ -0,0 +1,39 @@
package im.molly.monero.demo.data
import im.molly.monero.demo.data.dao.WalletDao
import im.molly.monero.demo.data.entity.WalletEntity
import im.molly.monero.demo.data.entity.WalletRemoteNodeXRef
import im.molly.monero.demo.data.entity.asExternalModel
import im.molly.monero.demo.data.model.WalletConfig
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class WalletDataSource(
private val walletDao: WalletDao,
) {
fun getWalletIdList(): Flow<List<Long>> = walletDao.findAllIds()
fun loadWalletConfig(walletId: Long): Flow<WalletConfig> =
walletDao.findById(walletId).map { it.asExternalModel() }
suspend fun storeWalletConfig(
publicAddress: String,
name: String,
remoteNodeIds: List<Long>,
): Long {
val walletId = walletDao.insert(
WalletEntity(
publicAddress = publicAddress,
name = name,
)
)
val walletRemoteNodeXRef = remoteNodeIds.map { remoteNodeId ->
WalletRemoteNodeXRef(
walletId = walletId,
remoteNodeId = remoteNodeId
)
}
walletDao.insertRemoteNodeXRefEntities(walletRemoteNodeXRef)
return walletId
}
}

View File

@ -0,0 +1,67 @@
package im.molly.monero.demo.data
import im.molly.monero.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
class WalletRepository(
private val moneroSdkClient: MoneroSdkClient,
private val walletDataSource: WalletDataSource,
private val externalScope: CoroutineScope,
) {
private val walletIdMap = ConcurrentHashMap<Long, Deferred<MoneroWallet>>()
suspend fun getWallet(walletId: Long): MoneroWallet {
return walletIdMap.computeIfAbsent(walletId) {
externalScope.async {
val config = getWalletConfig(walletId).first()
val wallet = moneroSdkClient.openWallet(
publicAddress = config.publicAddress,
remoteNodeSelector = object : RemoteNodeSelector {
override fun select(): RemoteNode? {
return config.remoteNodes.firstOrNull()?.let {
RemoteNode(
uri = it.uri,
username = it.username,
password = it.password,
)
}
}
override fun connectFailed(remoteNode: RemoteNode, ioe: IOException) {
TODO("Not yet implemented")
}
}
)
wallet
}
}.await()
}
fun getWalletIdList() = walletDataSource.getWalletIdList()
fun getWalletConfig(walletId: Long) = walletDataSource.loadWalletConfig(walletId)
fun getLedger(walletId: Long): Flow<Ledger> = flow {
emitAll(getWallet(walletId).ledger())
}
suspend fun addWallet(
moneroNetwork: MoneroNetwork,
name: String,
remoteNodeIds: List<Long>,
): Pair<Long, IWallet> {
val wallet = moneroSdkClient.createWallet(moneroNetwork)
val walletId = walletDataSource.storeWalletConfig(
publicAddress = wallet.publicAddress,
name = name,
remoteNodeIds = remoteNodeIds,
)
return walletId to wallet
}
}

View File

@ -0,0 +1,45 @@
package im.molly.monero.demo.data.dao
import androidx.room.*
import im.molly.monero.demo.data.entity.RemoteNodeEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface RemoteNodeDao {
@Query(
value = """
SELECT * FROM remote_nodes
"""
)
fun findAll(): Flow<List<RemoteNodeEntity>>
@Query(
value = """
SELECT * FROM remote_nodes
WHERE id = :id
"""
)
fun findById(id: Long): Flow<RemoteNodeEntity>
@Query(
value = """
SELECT * FROM remote_nodes
WHERE id IN (:ids)
"""
)
fun findByIds(ids: List<Long>): Flow<List<RemoteNodeEntity>>
@Query(
value = """
SELECT * FROM remote_nodes
WHERE net_type IN (:networkIds)
"""
)
fun findByNetworkIds(networkIds: Set<Int>): Flow<List<RemoteNodeEntity>>
@Upsert
suspend fun upsert(vararg remoteNodes: RemoteNodeEntity)
@Delete
suspend fun delete(vararg remoteNodes: RemoteNodeEntity)
}

View File

@ -0,0 +1,35 @@
package im.molly.monero.demo.data.dao
import androidx.room.*
import im.molly.monero.demo.data.entity.PopulatedWallet
import im.molly.monero.demo.data.entity.WalletEntity
import im.molly.monero.demo.data.entity.WalletRemoteNodeXRef
import kotlinx.coroutines.flow.Flow
@Dao
interface WalletDao {
@Transaction
@Query(
value = """
SELECT * FROM wallets
WHERE id = :id
"""
)
fun findById(id: Long): Flow<PopulatedWallet>
@Query(
value = """
SELECT id FROM wallets
"""
)
fun findAllIds(): Flow<List<Long>>
@Insert(onConflict = OnConflictStrategy.ABORT)
suspend fun insert(wallet: WalletEntity): Long
@Insert(onConflict = OnConflictStrategy.ABORT)
suspend fun insertRemoteNodeXRefEntities(walletRemoteNodeXRefs: List<WalletRemoteNodeXRef>)
@Delete
suspend fun delete(wallet: WalletEntity)
}

View File

@ -0,0 +1,25 @@
package im.molly.monero.demo.data.entity
import androidx.room.Embedded
import androidx.room.Junction
import androidx.room.Relation
data class PopulatedWallet(
@Embedded
val wallet: WalletEntity,
@Relation(
parentColumn = "id",
entityColumn = "id",
associateBy = Junction(
value = WalletRemoteNodeXRef::class,
parentColumn = "wallet_id",
entityColumn = "remote_node_id",
)
)
val remoteNodes: Set<RemoteNodeEntity>,
)
fun PopulatedWallet.asExternalModel() = wallet.asExternalModel().copy(
remoteNodes = remoteNodes.map(RemoteNodeEntity::asExternalModel).toSet()
)

View File

@ -0,0 +1,49 @@
package im.molly.monero.demo.data.entity
import android.net.Uri
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import im.molly.monero.MoneroNetwork
import im.molly.monero.demo.data.model.RemoteNode
@Entity(
tableName = "remote_nodes",
indices = [
Index("net_type")
]
)
data class RemoteNodeEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Long = 0,
@ColumnInfo(name = "net_type")
val networkId: Int,
@ColumnInfo(name = "uri")
val uri: String,
@ColumnInfo(name = "user")
val username: String,
@ColumnInfo(name = "pwd")
val password: String,
)
fun RemoteNodeEntity.asExternalModel() = RemoteNode(
id = id,
network = MoneroNetwork.fromId(networkId),
uri = Uri.parse(uri),
username = username,
password = password,
)
fun RemoteNode.asEntity() = RemoteNodeEntity(
id = id ?: 0,
networkId = network.id,
uri = uri.toString(),
username = username,
password = password,
)

View File

@ -0,0 +1,32 @@
package im.molly.monero.demo.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import im.molly.monero.demo.data.model.WalletConfig
@Entity(
tableName = "wallets",
indices = [
Index(value = ["public_address"], unique = true)
],
)
data class WalletEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Long = 0,
@ColumnInfo(name = "public_address")
val publicAddress: String,
@ColumnInfo(name = "name")
val name: String = "",
)
fun WalletEntity.asExternalModel() = WalletConfig(
id = id,
publicAddress = publicAddress,
name = name,
remoteNodes = setOf(),
)

View File

@ -0,0 +1,36 @@
package im.molly.monero.demo.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
@Entity(
tableName = "wallet_remote_nodes",
primaryKeys = ["wallet_id", "remote_node_id"],
foreignKeys = [
ForeignKey(
entity = WalletEntity::class,
parentColumns = ["id"],
childColumns = ["wallet_id"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = RemoteNodeEntity::class,
parentColumns = ["id"],
childColumns = ["remote_node_id"],
onDelete = ForeignKey.CASCADE
),
],
indices = [
Index(value = ["wallet_id"]),
Index(value = ["remote_node_id"]),
],
)
data class WalletRemoteNodeXRef(
@ColumnInfo(name = "wallet_id")
val walletId: Long,
@ColumnInfo(name = "remote_node_id")
val remoteNodeId: Long,
)

View File

@ -0,0 +1,18 @@
package im.molly.monero.demo.data.model
import android.net.Uri
import im.molly.monero.MoneroNetwork
data class RemoteNode(
val id: Long? = null,
val network: MoneroNetwork,
val uri: Uri,
val username: String = "",
val password: String = "",
) {
companion object {
val EMPTY = RemoteNode(network = DefaultMoneroNetwork, uri = Uri.EMPTY)
}
}
val DefaultMoneroNetwork = MoneroNetwork.Mainnet

View File

@ -0,0 +1,9 @@
package im.molly.monero.demo.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Transaction(
@PrimaryKey val uid: Int,
)

View File

@ -0,0 +1,11 @@
package im.molly.monero.demo.data.model
import im.molly.monero.MoneroNetwork
data class WalletConfig(
val id: Long,
val publicAddress: String,
val network: MoneroNetwork = MoneroNetwork.of(publicAddress),
val name: String,
val remoteNodes: Set<RemoteNode>,
)

View File

@ -0,0 +1,62 @@
package im.molly.monero.demo.service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import im.molly.monero.demo.AppModule
import im.molly.monero.demo.data.WalletRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds
class SyncService(
private val walletRepository: WalletRepository = AppModule.walletRepository,
) : LifecycleService() {
private val binder: IBinder = LocalBinder()
inner class LocalBinder : Binder() {
val service: SyncService
get() = this@SyncService
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
return binder
}
override fun onCreate() {
super.onCreate()
lifecycleScope.launch {
val syncedWalletIds = mutableSetOf<Long>()
walletRepository.getWalletIdList().collect {
val idSet = it.toSet()
val toSync = idSet subtract syncedWalletIds
toSync.forEach { walletId ->
val wallet = walletRepository.getWallet(walletId)
lifecycleScope.launch {
while (isActive) {
val result = wallet.awaitRefresh();
if (result.isError()) {
break;
}
delay(10.seconds)
}
}
}
syncedWalletIds.addAll(toSync)
}
}
}
companion object {
fun start(context: Context) {
val intent = Intent(context, SyncService::class.java)
context.startService(intent)
}
}
}

View File

@ -0,0 +1,58 @@
package im.molly.monero.demo.ui
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import im.molly.monero.MoneroNetwork
import im.molly.monero.demo.AppModule
import im.molly.monero.demo.data.RemoteNodeRepository
import im.molly.monero.demo.data.WalletRepository
import im.molly.monero.demo.data.model.DefaultMoneroNetwork
import im.molly.monero.demo.data.model.RemoteNode
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
class AddWalletViewModel(
private val remoteNodeRepository: RemoteNodeRepository = AppModule.remoteNodeRepository,
private val walletRepository: WalletRepository = AppModule.walletRepository,
) : ViewModel() {
var network by mutableStateOf(DefaultMoneroNetwork)
private set
var walletName by mutableStateOf("")
private set
val currentRemoteNodes: StateFlow<List<RemoteNode>> =
snapshotFlow { network }
.flatMapLatest {
remoteNodeRepository.getAllRemoteNodes(
filterNetworkIds = setOf(network.id),
)
}
.stateIn(
scope = viewModelScope,
started = WhileSubscribed(5000),
initialValue = listOf(RemoteNode.EMPTY),
)
val selectedRemoteNodes = mutableStateMapOf<Long?, Boolean>()
private fun getSelectedRemoteNodeIds() =
selectedRemoteNodes.filterValues { checked -> checked }.keys.filterNotNull()
fun toggleSelectedNetwork(network: MoneroNetwork) {
this.network = network
}
fun updateWalletName(name: String) {
this.walletName = name
}
fun createWallet() = viewModelScope.launch {
walletRepository.addWallet(network, walletName, getSelectedRemoteNodeIds())
}
}

View File

@ -0,0 +1,230 @@
package im.molly.monero.demo.ui
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import im.molly.monero.MoneroNetwork
import im.molly.monero.demo.R
import im.molly.monero.demo.data.model.DefaultMoneroNetwork
import im.molly.monero.demo.data.model.RemoteNode
import im.molly.monero.demo.ui.component.SelectListBox
import im.molly.monero.demo.ui.component.Toolbar
import im.molly.monero.demo.ui.theme.AppIcons
import im.molly.monero.demo.ui.theme.AppTheme
@Composable
fun AddWalletFirstStepRoute(
onBackClick: () -> Unit,
onNavigateToCreateWallet: () -> Unit,
onNavigateToRestoreWallet: () -> Unit,
modifier: Modifier = Modifier,
) {
FirstStepScreen(
onBackClick = onBackClick,
onCreateClick = onNavigateToCreateWallet,
onRestoreClick = onNavigateToRestoreWallet,
modifier = modifier,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun FirstStepScreen(
onBackClick: () -> Unit,
onCreateClick: () -> Unit,
onRestoreClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Scaffold(
topBar = {
Toolbar(
titleRes = R.string.add_wallet,
navigationIcon = {
IconButton(onClick = onBackClick) {
Icon(
imageVector = AppIcons.ArrowBack,
contentDescription = stringResource(R.string.back),
)
}
}
)
}
) { padding ->
Column(
modifier = modifier
.fillMaxSize()
.padding(padding),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = onCreateClick,
) {
Text(stringResource(R.string.create_a_new_wallet))
}
OutlinedButton(
onClick = {}, // TODO: onRestoreClick,
modifier = Modifier.padding(top = 8.dp),
) {
Text(stringResource(R.string.i_already_have_a_wallet))
}
}
}
}
@Composable
fun AddWalletSecondStepRoute(
showRestoreOptions: Boolean,
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
onNavigateToHome: () -> Unit,
viewModel: AddWalletViewModel = viewModel(),
) {
val remoteNodes by viewModel.currentRemoteNodes.collectAsStateWithLifecycle()
SecondStepScreen(
showRestoreOptions = showRestoreOptions,
modifier = modifier,
onBackClick = onBackClick,
onCreateClick = {
viewModel.createWallet()
onNavigateToHome()
},
walletName = viewModel.walletName,
network = viewModel.network,
onWalletNameChanged = { name -> viewModel.updateWalletName(name) },
onNetworkChanged = { network -> viewModel.toggleSelectedNetwork(network) },
remoteNodes = remoteNodes,
selectedRemoteNodeIds = viewModel.selectedRemoteNodes,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SecondStepScreen(
showRestoreOptions: Boolean,
modifier: Modifier = Modifier,
onBackClick: () -> Unit,
onCreateClick: () -> Unit,
walletName: String,
network: MoneroNetwork,
onWalletNameChanged: (String) -> Unit,
onNetworkChanged: (MoneroNetwork) -> Unit,
remoteNodes: List<RemoteNode>,
selectedRemoteNodeIds: MutableMap<Long?, Boolean> = mutableMapOf(),
) {
Scaffold(
topBar = {
val title = if (showRestoreOptions) R.string.restore_wallet else R.string.new_wallet
Toolbar(
titleRes = title,
navigationIcon = {
IconButton(onClick = onBackClick) {
Icon(
imageVector = AppIcons.ArrowBack,
contentDescription = stringResource(R.string.back),
)
}
}
)
}
) { padding ->
Column(
modifier = modifier
.padding(padding)
.verticalScroll(rememberScrollState()),
) {
OutlinedTextField(
value = walletName,
label = { Text(stringResource(R.string.wallet_name)) },
onValueChange = onWalletNameChanged,
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
)
SelectListBox(
labelRes = R.string.network,
options = MoneroNetwork.values().map { it.name },
selectedOption = network.name,
onOptionClick = {
onNetworkChanged(MoneroNetwork.valueOf(it))
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
)
Text(
text = stringResource(R.string.remote_node_selection),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.padding(16.dp),
)
MultiSelectRemoteNodeList(
remoteNodes = remoteNodes,
selectedIds = selectedRemoteNodeIds,
modifier = Modifier
.padding(start = 16.dp),
)
Column(
modifier = Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = onCreateClick,
modifier = Modifier
.padding(16.dp),
) {
Text(stringResource(R.string.finish))
}
}
}
}
}
@Preview
@Composable
private fun CreateWalletScreenPreview() {
AppTheme {
SecondStepScreen(
showRestoreOptions = false,
onBackClick = {},
onCreateClick = {},
walletName = "Personal",
network = DefaultMoneroNetwork,
onWalletNameChanged = {},
onNetworkChanged = {},
remoteNodes = listOf(RemoteNode.EMPTY),
selectedRemoteNodeIds = mutableMapOf(),
)
}
}
@Preview
@Composable
private fun RestoreWalletScreenPreview() {
AppTheme {
SecondStepScreen(
showRestoreOptions = true,
onBackClick = {},
onCreateClick = {},
walletName = "Personal",
network = DefaultMoneroNetwork,
onWalletNameChanged = {},
onNetworkChanged = {},
remoteNodes = listOf(RemoteNode.EMPTY),
selectedRemoteNodeIds = mutableMapOf(),
)
}
}

View File

@ -0,0 +1,89 @@
package im.molly.monero.demo.ui
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import im.molly.monero.demo.ui.navigation.*
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun DemoApp(
appState: DemoAppState = rememberDemoAppState(),
) {
Background {
Scaffold(
bottomBar = {
BottomBar(
destinations = appState.topLevelDestinations,
onNavigateToDestination = appState::navigateToTopLevelDestination,
currentDestination = appState.currentDestination,
modifier = Modifier,
)
},
) { padding ->
Row(
Modifier
.fillMaxSize()
.padding(padding)
.consumeWindowInsets(padding)
.windowInsetsPadding(
WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)
)
) {
Column(Modifier.fillMaxSize()) {
NavGraph(
navController = appState.navController,
onBackClick = appState::onBackClick,
)
}
}
}
}
}
@Composable
private fun Background(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Surface(
modifier = modifier.fillMaxSize(),
) {
content()
}
}
@Composable
private fun BottomBar(
destinations: List<TopLevelDestination>,
onNavigateToDestination: (TopLevelDestination) -> Unit,
currentDestination: NavDestination?,
modifier: Modifier = Modifier,
) {
NavigationBar(
modifier = modifier,
) {
destinations.forEach { destination ->
val selected = currentDestination.isTopLevelDestinationInHierarchy(destination)
val icon = if (selected) destination.selectedIcon else destination.unselectedIcon
val text = stringResource(destination.iconTextRes)
NavigationBarItem(
onClick = { onNavigateToDestination(destination) },
selected = selected,
icon = { Icon(imageVector = icon, contentDescription = text) },
label = { Text(text) },
alwaysShowLabel = true,
)
}
}
}
private fun NavDestination?.isTopLevelDestinationInHierarchy(destination: TopLevelDestination): Boolean {
return this?.hierarchy?.any {
it.route?.startsWith(destination.name, true) ?: false
} ?: false
}

View File

@ -0,0 +1,52 @@
package im.molly.monero.demo.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navOptions
import im.molly.monero.demo.ui.navigation.*
@Composable
fun rememberDemoAppState(
navController: NavHostController = rememberNavController(),
): DemoAppState {
return remember(navController) {
DemoAppState(navController)
}
}
@Stable
class DemoAppState(
val navController: NavHostController,
) {
val currentDestination: NavDestination?
@Composable get() = navController
.currentBackStackEntryAsState().value?.destination
val topLevelDestinations = TopLevelDestination.values().asList()
fun navigateToTopLevelDestination(topLevelDestination: TopLevelDestination) {
val topLevelNavOptions = navOptions {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
when (topLevelDestination) {
TopLevelDestination.HOME -> navController.navigateToHome(topLevelNavOptions)
TopLevelDestination.HISTORY -> navController.navigateToHistory(topLevelNavOptions)
TopLevelDestination.SETTINGS -> navController.navigateToSettings(topLevelNavOptions)
}
}
fun onBackClick() {
navController.popBackStack()
}
}

View File

@ -0,0 +1,151 @@
package im.molly.monero.demo.ui
import android.net.Uri
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import im.molly.monero.MoneroNetwork
import im.molly.monero.demo.R
import im.molly.monero.demo.data.model.RemoteNode
import im.molly.monero.demo.ui.component.SelectListBox
import im.molly.monero.demo.ui.theme.AppTheme
import kotlinx.coroutines.flow.first
@Composable
fun EditRemoteNodeRoute(
remoteNodeId: Long?,
onBackClick: () -> Unit,
viewModel: SettingsViewModel = viewModel(),
) {
var remoteNode by remember { mutableStateOf(RemoteNode.EMPTY) }
remoteNodeId?.let {
LaunchedEffect(it) {
remoteNode = viewModel.remoteNode(it).first()
}
}
EditRemoteNodeDialog(
remoteNode = remoteNode,
showError = !viewModel.isRemoteNodeCorrect(remoteNode),
onRemoteNodeChange = { remoteNode = it },
onSaveRequest = {
viewModel.saveRemoteNodeDetails(remoteNode)
onBackClick()
},
onDismissRequest = onBackClick,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun EditRemoteNodeDialog(
remoteNode: RemoteNode,
showError: Boolean,
onRemoteNodeChange: (RemoteNode) -> Unit,
onSaveRequest: () -> Unit,
onDismissRequest: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismissRequest,
text = {
Column(
Modifier.verticalScroll(rememberScrollState()),
) {
Text(
text = stringResource(R.string.enter_your_monero_node_information_below),
modifier = Modifier.padding(vertical = 16.dp),
)
SelectListBox(
labelRes = R.string.network,
options = MoneroNetwork.values().map { it.name },
selectedOption = remoteNode.network.name,
onOptionClick = {
onRemoteNodeChange(remoteNode.copy(network = MoneroNetwork.valueOf(it)))
}
)
Column {
OutlinedTextField(
value = remoteNode.uri.toString(),
onValueChange = { input ->
onRemoteNodeChange(remoteNode.copy(uri = Uri.parse(input)))
},
label = {
Text(stringResource(R.string.url))
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
isError = showError,
)
Text(
text = stringResource(R.string.protocol_is_required_http_or_https),
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
)
}
OutlinedTextField(
value = remoteNode.username,
onValueChange = { input ->
onRemoteNodeChange(remoteNode.copy(username = input))
},
label = {
Text(stringResource(R.string.username))
},
singleLine = true,
)
OutlinedTextField(
value = remoteNode.password,
onValueChange = { input ->
onRemoteNodeChange(remoteNode.copy(password = input))
},
label = {
Text(stringResource(R.string.password))
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
visualTransformation = PasswordVisualTransformation(),
)
}
},
confirmButton = {
TextButton(
onClick = onSaveRequest,
enabled = !showError,
) {
Text(stringResource(R.string.save))
}
},
dismissButton = {
TextButton(
onClick = onDismissRequest,
) {
Text(stringResource(android.R.string.cancel))
}
},
)
}
@Preview
@Composable
private fun EditRemoteNodeDialogPreview() {
AppTheme {
EditRemoteNodeDialog(
remoteNode = RemoteNode.EMPTY,
showError = false,
onRemoteNodeChange = {},
onSaveRequest = {},
onDismissRequest = {},
)
}
}

View File

@ -0,0 +1,20 @@
package im.molly.monero.demo.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun HistoryRoute(
modifier: Modifier = Modifier,
) {
HistoryScreen(
modifier = modifier,
)
}
@Composable
private fun HistoryScreen(
modifier: Modifier = Modifier,
) {
}

View File

@ -0,0 +1,76 @@
package im.molly.monero.demo.ui
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import im.molly.monero.demo.R
import im.molly.monero.demo.ui.component.Toolbar
@Composable
fun HomeRoute(
navigateToAddWalletWizard: () -> Unit,
viewModel: HomeViewModel = viewModel(),
) {
val walletListUiState: WalletListUiState by viewModel.walletListUiState.collectAsStateWithLifecycle()
HomeScreen(
walletListUiState = walletListUiState,
onAddWalletClick = navigateToAddWalletWizard,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeScreen(
walletListUiState: WalletListUiState,
onAddWalletClick: () -> Unit,
) {
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
Toolbar(
titleRes = R.string.monero_wallets,
scrollBehavior = scrollBehavior,
)
},
floatingActionButton = {
ExtendedFloatingActionButton(onClick = onAddWalletClick) {
Text(stringResource(R.string.add_wallet))
}
},
) { padding ->
val listState = rememberLazyListState()
LazyColumn(
state = listState,
modifier = Modifier
.fillMaxSize()
.padding(padding))
{
walletCards(walletListUiState)
}
}
}
private fun LazyListScope.walletCards(
walletListUiState: WalletListUiState,
) {
when (walletListUiState) {
WalletListUiState.Loading -> item {
Text(text = "Loading wallet list...") // TODO
}
is WalletListUiState.Success -> {
walletCardsItems(walletListUiState.ids)
}
}
}

View File

@ -0,0 +1,36 @@
package im.molly.monero.demo.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import im.molly.monero.demo.AppModule
import im.molly.monero.demo.data.WalletRepository
import kotlinx.coroutines.flow.*
class HomeViewModel(
private val walletRepository: WalletRepository = AppModule.walletRepository,
) : ViewModel() {
val walletListUiState: StateFlow<WalletListUiState> = walletRepository.getWalletIdList()
.map { WalletListUiState.Success(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = WalletListUiState.Loading,
)
}
sealed interface HomeUiState {
object Loading : HomeUiState
// data class Ready(
// val wallets: List<WalletDetails>
// ) : HomeUiState
object Empty : HomeUiState
}
sealed interface WalletListUiState {
data class Success(val ids: List<Long>) : WalletListUiState
object Loading : WalletListUiState
}

View File

@ -0,0 +1,133 @@
package im.molly.monero.demo.ui
import android.net.Uri
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import im.molly.monero.demo.R
import im.molly.monero.demo.data.model.RemoteNode
import im.molly.monero.demo.ui.theme.AppIcons
@Composable
fun MultiSelectRemoteNodeList(
remoteNodes: List<RemoteNode>,
selectedIds: MutableMap<Long?, Boolean>,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
) {
remoteNodes.forEach { remoteNode ->
RemoteNodeItem(
remoteNode,
checked = selectedIds[remoteNode.id] ?: false,
showCheckbox = true,
onCheckedChange = { checked ->
selectedIds[remoteNode.id] = checked
},
)
}
}
}
@Composable
fun RemoteNodeEditableList(
remoteNodes: List<RemoteNode>,
onEditRemoteNode: (RemoteNode) -> Unit,
onDeleteRemoteNode: (RemoteNode) -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
) {
remoteNodes.forEach { remoteNode ->
RemoteNodeItem(
remoteNode,
showMenu = true,
onEditClick = onEditRemoteNode,
onDeleteClick = onDeleteRemoteNode,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun RemoteNodeItem(
remoteNode: RemoteNode,
checked: Boolean = false,
showCheckbox: Boolean = false,
showMenu: Boolean = false,
onCheckedChange: (Boolean) -> Unit = {},
onEditClick: (RemoteNode) -> Unit = {},
onDeleteClick: (RemoteNode) -> Unit = {},
) {
ListItem(
headlineText = { Text(remoteNode.uri.toString()) },
overlineText = { Text(remoteNode.network.name.uppercase()) },
trailingContent = {
Row {
if (showCheckbox) {
Checkbox(
checked = checked,
onCheckedChange = onCheckedChange,
)
}
if (showMenu) {
KebabMenu(
onEditClick = { onEditClick(remoteNode) },
onDeleteClick = { onDeleteClick(remoteNode) },
)
}
}
},
)
}
@Composable
private fun KebabMenu(
onEditClick: () -> Unit,
onDeleteClick: () -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
IconButton(onClick = { expanded = true }) {
Icon(
imageVector = AppIcons.MoreVert,
contentDescription = stringResource(R.string.open_menu),
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.edit)) },
onClick = {
onEditClick()
expanded = false
},
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
onDeleteClick()
expanded = false
},
)
}
}
@Preview
@Composable
private fun MultiSelectRemoteNodeListPreview() {
val aNode = RemoteNode.EMPTY.copy(uri = Uri.parse("http://node.monero"))
MultiSelectRemoteNodeList(
remoteNodes = listOf(aNode),
selectedIds = mutableMapOf(),
)
}

View File

@ -0,0 +1,82 @@
package im.molly.monero.demo.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import im.molly.monero.demo.R
import im.molly.monero.demo.data.model.RemoteNode
import im.molly.monero.demo.ui.theme.AppTheme
@Composable
fun SettingsRoute(
modifier: Modifier = Modifier,
viewModel: SettingsViewModel = viewModel(),
navigateToEditRemoteNode: (Long?) -> Unit,
) {
val remoteNodes by viewModel.remoteNodes.collectAsStateWithLifecycle()
SettingsScreen(
remoteNodes = remoteNodes,
modifier = modifier,
onAddRemoteNode = { navigateToEditRemoteNode(RemoteNode.EMPTY.id) },
onEditRemoteNode = { navigateToEditRemoteNode(it.id) },
onDeleteRemoteNode = { viewModel.forgetRemoteNodeDetails(it) },
)
}
@Composable
private fun SettingsScreen(
remoteNodes: List<RemoteNode>,
modifier: Modifier = Modifier,
onAddRemoteNode: () -> Unit = {},
onEditRemoteNode: (RemoteNode) -> Unit = {},
onDeleteRemoteNode: (RemoteNode) -> Unit = {},
) {
Column(
modifier = modifier
.verticalScroll(rememberScrollState())
.padding(all = 24.dp)
) {
Divider()
SettingsSectionTitle(R.string.remote_nodes)
TextButton(onClick = onAddRemoteNode) {
Text(stringResource(R.string.add_remote_node))
}
RemoteNodeEditableList(
remoteNodes = remoteNodes,
onEditRemoteNode = onEditRemoteNode,
onDeleteRemoteNode = onDeleteRemoteNode,
)
// Divider()
}
}
@Composable
private fun SettingsSectionTitle(@StringRes titleRes: Int) {
Text(
text = stringResource(titleRes),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
)
}
@Preview
@Composable
private fun SettingsScreenPreview() {
AppTheme {
SettingsScreen(
remoteNodes = emptyList(),
)
}
}

View File

@ -0,0 +1,41 @@
package im.molly.monero.demo.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import im.molly.monero.demo.AppModule
import im.molly.monero.demo.data.RemoteNodeRepository
import im.molly.monero.demo.data.model.RemoteNode
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class SettingsViewModel(
private val remoteNodeRepository: RemoteNodeRepository = AppModule.remoteNodeRepository,
) : ViewModel() {
val remoteNodes: StateFlow<List<RemoteNode>> =
remoteNodeRepository.getAllRemoteNodes()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = listOf(RemoteNode.EMPTY),
)
fun remoteNode(remoteNodeId: Long): Flow<RemoteNode> =
remoteNodeRepository.getRemoteNode(remoteNodeId)
fun isRemoteNodeCorrect(remoteNode: RemoteNode): Boolean {
return remoteNode.uri.host?.isEmpty() == false
}
fun saveRemoteNodeDetails(remoteNode: RemoteNode) {
viewModelScope.launch {
remoteNodeRepository.addOrUpdateRemoteNode(remoteNode)
}
}
fun forgetRemoteNodeDetails(remoteNode: RemoteNode) {
viewModelScope.launch {
remoteNodeRepository.deleteRemoteNode(remoteNode)
}
}
}

View File

@ -0,0 +1,50 @@
package im.molly.monero.demo.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun WalletCard(
walletId: Long,
modifier: Modifier = Modifier,
viewModel: WalletViewModel = viewModel(
factory = WalletViewModel.factory(walletId),
key = walletId.toString(),
),
) {
val walletUiState: WalletUiState by viewModel.walletUiState.collectAsStateWithLifecycle()
Card(
modifier = modifier
.padding(8.dp)
) {
Column {
when (walletUiState) {
WalletUiState.Error -> {
Text(text = "Error") // TODO
}
WalletUiState.Loading -> {
Text(text = "Loading wallet...") // TODO
}
is WalletUiState.Success -> {
val state = walletUiState as WalletUiState.Success
Row {
Text(text = "Name: ${state.config.name}")
}
Row {
Text(text = "Ledger: ${state.ledger}")
}
}
}
}
}
}

View File

@ -0,0 +1,19 @@
package im.molly.monero.demo.ui
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.ui.Modifier
fun LazyListScope.walletCardsItems(
items: List<Long>,
itemModifier: Modifier = Modifier,
) = items(
items = items,
key = { it },
itemContent = {
WalletCard(
walletId = it,
modifier = itemModifier,
)
},
)

View File

@ -0,0 +1,69 @@
package im.molly.monero.demo.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import im.molly.monero.Ledger
import im.molly.monero.demo.AppModule
import im.molly.monero.demo.common.Result
import im.molly.monero.demo.common.asResult
import im.molly.monero.demo.data.WalletRepository
import im.molly.monero.demo.data.model.WalletConfig
import kotlinx.coroutines.flow.*
class WalletViewModel(
private val walletId: Long,
private val walletRepository: WalletRepository = AppModule.walletRepository,
) : ViewModel() {
val walletUiState: StateFlow<WalletUiState> = walletUiState(
walletId = walletId,
walletRepository = walletRepository,
).stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = WalletUiState.Loading
)
companion object {
fun factory(walletId: Long) = viewModelFactory {
initializer {
WalletViewModel(walletId)
}
}
}
}
private fun walletUiState(
walletId: Long,
walletRepository: WalletRepository,
): Flow<WalletUiState> {
return combine(
walletRepository.getWalletConfig(walletId),
walletRepository.getLedger(walletId),
::Pair,
).asResult().map { result ->
when (result) {
is Result.Success -> {
WalletUiState.Success(result.data.first, result.data.second)
}
is Result.Loading -> {
WalletUiState.Loading
}
is Result.Error -> {
WalletUiState.Error
}
}
}
}
sealed interface WalletUiState {
data class Success(
val config: WalletConfig,
val ledger: Ledger,
) : WalletUiState
object Error : WalletUiState
object Loading : WalletUiState
}

View File

@ -0,0 +1,48 @@
package im.molly.monero.demo.ui.component
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
@Composable
fun RadioButtons(
radioOptions: List<String>,
selectedOption: String,
onOptionSelected: (String) -> Unit,
modifier: Modifier = Modifier,
) {
Column(modifier.selectableGroup()) {
radioOptions.forEach { text ->
Row(
Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = (text == selectedOption),
onClick = { onOptionSelected(text) },
role = Role.RadioButton,
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = (text == selectedOption),
onClick = null,
)
Text(
text = text,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(start = 16.dp),
)
}
}
}
}

View File

@ -0,0 +1,63 @@
package im.molly.monero.demo.ui.component
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SelectListBox(
@StringRes labelRes: Int,
options: List<String>,
selectedOption: String,
onOptionClick: (String) -> Unit,
modifier: Modifier = Modifier,
) {
var expanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
},
modifier = modifier,
) {
OutlinedTextField(
readOnly = true,
value = selectedOption,
onValueChange = { },
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
label = { Text(stringResource(labelRes)) },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded
)
},
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),
)
DropdownMenu(
expanded = expanded,
onDismissRequest = {
expanded = false
},
modifier = Modifier.exposedDropdownSize(),
) {
options.forEach { selectionOption ->
DropdownMenuItem(
text = {
Text(selectionOption)
},
onClick = {
onOptionClick(selectionOption)
expanded = false
},
)
}
}
}
}

View File

@ -0,0 +1,29 @@
package im.molly.monero.demo.ui.component
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Toolbar(
@StringRes titleRes: Int,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
scrollBehavior: TopAppBarScrollBehavior? = null,
) {
CenterAlignedTopAppBar(
title = { Text(stringResource(id = titleRes), ) },
modifier = modifier,
navigationIcon = navigationIcon,
actions = actions,
scrollBehavior = scrollBehavior,
)
}

View File

@ -0,0 +1,19 @@
package im.molly.monero.demo.ui.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import im.molly.monero.demo.ui.HistoryRoute
const val historyNavRoute = "history"
fun NavController.navigateToHistory(navOptions: NavOptions? = null) {
navigate(historyNavRoute, navOptions)
}
fun NavGraphBuilder.historyScreen() {
composable(route = historyNavRoute) {
HistoryRoute()
}
}

View File

@ -0,0 +1,23 @@
package im.molly.monero.demo.ui.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import im.molly.monero.demo.ui.HomeRoute
const val homeNavRoute = "home"
fun NavController.navigateToHome(navOptions: NavOptions? = null) {
navigate(homeNavRoute, navOptions)
}
fun NavGraphBuilder.homeScreen(
navigateToAddWalletWizard: () -> Unit,
) {
composable(route = homeNavRoute) {
HomeRoute(
navigateToAddWalletWizard = navigateToAddWalletWizard,
)
}
}

View File

@ -0,0 +1,39 @@
package im.molly.monero.demo.ui.navigation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
@Composable
fun NavGraph(
navController: NavHostController,
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
startDestination: String = homeNavRoute,
) {
NavHost(
navController,
startDestination,
modifier,
) {
homeScreen(
navigateToAddWalletWizard = {
navController.navigateToAddWalletWizardGraph()
},
)
historyScreen()
settingsScreen(
navigateToEditRemoteNode = { remoteNodeId ->
navController.navigateToEditRemoteNode(remoteNodeId)
},
)
editRemoteNodeDialog(
onBackClick = onBackClick,
)
addWalletWizardGraph(
navController = navController,
onBackClick = onBackClick,
)
}
}

View File

@ -0,0 +1,56 @@
package im.molly.monero.demo.ui.navigation
import androidx.navigation.*
import androidx.navigation.compose.composable
import androidx.navigation.compose.dialog
import im.molly.monero.demo.ui.EditRemoteNodeRoute
import im.molly.monero.demo.ui.SettingsRoute
const val settingsNavRoute = "settings"
const val settingsRemoteNodeNavRoute = "$settingsNavRoute/remote_node"
private const val idArg = "id"
fun NavController.navigateToSettings(navOptions: NavOptions? = null) {
navigate(settingsNavRoute, navOptions)
}
fun NavController.navigateToEditRemoteNode(remoteNodeId: Long?) {
val route = if (remoteNodeId != null) {
"$settingsRemoteNodeNavRoute?$idArg=$remoteNodeId"
} else {
settingsRemoteNodeNavRoute
}
this.navigate(route)
}
fun NavGraphBuilder.settingsScreen(
navigateToEditRemoteNode: (Long?) -> Unit,
) {
composable(route = settingsNavRoute) {
SettingsRoute(
navigateToEditRemoteNode = navigateToEditRemoteNode,
)
}
}
fun NavGraphBuilder.editRemoteNodeDialog(
onBackClick: () -> Unit,
) {
dialog(
route = "$settingsRemoteNodeNavRoute?$idArg={$idArg}",
arguments = listOf(
navArgument(idArg) {
type = NavType.StringType
nullable = true
}
)
) {
val arguments = requireNotNull(it.arguments)
val remoteNodeId = arguments.getString(idArg)?.toLongOrNull()
EditRemoteNodeRoute(
remoteNodeId = remoteNodeId,
onBackClick = onBackClick,
)
}
}

View File

@ -0,0 +1,28 @@
package im.molly.monero.demo.ui.navigation
import androidx.annotation.StringRes
import androidx.compose.ui.graphics.vector.ImageVector
import im.molly.monero.demo.R
import im.molly.monero.demo.ui.theme.AppIcons
enum class TopLevelDestination(
val selectedIcon: ImageVector,
val unselectedIcon: ImageVector,
@StringRes val iconTextRes: Int,
) {
HOME(
selectedIcon = AppIcons.Home,
unselectedIcon = AppIcons.HomeOutlined,
iconTextRes = R.string.home,
),
HISTORY(
selectedIcon = AppIcons.History,
unselectedIcon = AppIcons.HistoryOutlined,
iconTextRes = R.string.history,
),
SETTINGS(
selectedIcon = AppIcons.History,
unselectedIcon = AppIcons.HistoryOutlined,
iconTextRes = R.string.settings,
)
}

View File

@ -0,0 +1,59 @@
package im.molly.monero.demo.ui.navigation
import androidx.navigation.*
import androidx.navigation.compose.composable
import im.molly.monero.demo.ui.AddWalletFirstStepRoute
import im.molly.monero.demo.ui.AddWalletSecondStepRoute
const val addWalletWizardNavRoute = "home/add_wallet_wizard"
private const val startNavRoute = "$addWalletWizardNavRoute/start"
private const val createNavRoute = "$addWalletWizardNavRoute/create"
private const val restoreNavRoute = "$addWalletWizardNavRoute/restore"
fun NavController.navigateToAddWalletWizardGraph(navOptions: NavOptions? = null) {
navigate(addWalletWizardNavRoute, navOptions)
}
fun NavController.navigateToAddWalletSecondStep(restoreWallet: Boolean) {
when (restoreWallet) {
true -> navigate(restoreNavRoute)
false -> navigate(createNavRoute)
}
}
fun NavGraphBuilder.addWalletWizardGraph(
navController: NavHostController,
onBackClick: () -> Unit,
) {
navigation(
route = addWalletWizardNavRoute,
startDestination = startNavRoute,
) {
composable(route = startNavRoute) {
AddWalletFirstStepRoute(
onBackClick = onBackClick,
onNavigateToCreateWallet = {
navController.navigateToAddWalletSecondStep(restoreWallet = false)
},
onNavigateToRestoreWallet = {
navController.navigateToAddWalletSecondStep(restoreWallet = true)
},
)
}
composable(route = createNavRoute) {
AddWalletSecondStepRoute(
showRestoreOptions = false,
onBackClick = onBackClick,
onNavigateToHome = { navController.navigateToHome() },
)
}
composable(route = restoreNavRoute) {
AddWalletSecondStepRoute(
showRestoreOptions = true,
onBackClick = onBackClick,
onNavigateToHome = { navController.navigateToHome() },
)
}
}
}

View File

@ -0,0 +1,11 @@
package im.molly.monero.demo.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)

View File

@ -0,0 +1,19 @@
package im.molly.monero.demo.ui.theme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.List
import androidx.compose.material.icons.outlined.Settings
object AppIcons {
val ArrowBack = Icons.Filled.ArrowBack
val MoreVert = Icons.Filled.MoreVert
val Home = Icons.Filled.Home
val HomeOutlined = Icons.Outlined.Home
val History = Icons.Filled.List
val HistoryOutlined = Icons.Outlined.List
val Settings = Icons.Filled.Settings
val SettingsOutlined = Icons.Outlined.Settings
val AddWallet = Icons.Filled.Add
}

View File

@ -0,0 +1,61 @@
package im.molly.monero.demo.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40,
/* Other default colors to override
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = pickColorScheme(dynamicColor, darkTheme)
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@Composable
private fun pickColorScheme(
dynamicColor: Boolean,
darkTheme: Boolean
) = when {
dynamicColor && Build.VERSION.SDK_INT >= 31 -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}

View File

@ -0,0 +1,34 @@
package im.molly.monero.demo.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)

View File

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@ -0,0 +1,30 @@
<resources>
<string name="app_name">Monero SDK Demo</string>
<string name="home">Home</string>
<string name="history">History</string>
<string name="monero_wallets">Monero wallets</string>
<string name="create_a_new_wallet">Create a new wallet</string>
<string name="i_already_have_a_wallet">I already have a wallet</string>
<string name="back">Back</string>
<string name="finish">Finish</string>
<string name="new_wallet">New wallet</string>
<string name="restore_wallet">Restore wallet</string>
<string name="settings">Settings</string>
<string name="add_remote_node">Add remote node</string>
<string name="edit">Edit</string>
<string name="open_menu">Open menu</string>
<string name="delete">Delete</string>
<string name="save">Save</string>
<string name="description">Description</string>
<string name="url">URL</string>
<string name="password">Password</string>
<string name="username">Username</string>
<string name="monero_node">Monero node</string>
<string name="enter_your_monero_node_information_below">Enter your Monero node information below.</string>
<string name="protocol_is_required_http_or_https">Protocol is required (http:// or https://)</string>
<string name="network">Network</string>
<string name="remote_nodes">Remote nodes</string>
<string name="add_wallet">Add wallet</string>
<string name="wallet_name">Wallet name</string>
<string name="remote_node_selection">Remote node selection</string>
</resources>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Demo" parent="android:Theme.Material.Light.NoActionBar" />
</resources>

View File

@ -0,0 +1,17 @@
package im.molly.monero.demo
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

4
gradle.properties Normal file
View File

@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.enableJetifier=true
android.native.buildOutput=verbose

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=db9c8211ed63f61f60292c69e80d89196f9eb36665e369e7f00ac4cc841c2219
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
gradlew vendored Executable file
View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

91
gradlew.bat vendored Normal file
View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

135
lib/android/build.gradle Normal file
View File

@ -0,0 +1,135 @@
apply plugin: 'com.android.library'
apply plugin: 'org.jetbrains.kotlin.android'
apply plugin: 'org.jetbrains.kotlin.plugin.parcelize'
apply plugin: 'com.google.protobuf'
//apply from: 'deploy.gradle' // FIXME
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.20.1'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
kotlin {
option "lite"
}
}
}
}
}
android {
buildToolsVersion '33.0.1'
compileSdk 33
ndkVersion '23.1.7779620'
defaultConfig {
minSdk 26
targetSdk 33
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
consumerProguardFiles 'consumer-rules.pro'
externalNativeBuild {
cmake {
arguments "-DVENDOR_DIR=${rootDir}/vendor"
arguments "-DDOWNLOAD_CACHE=${buildDir}/downloads"
cppFlags ''
}
}
ndk {
// abiFilters /*'armeabi-v7a', 'arm64-v8a',*/ 'x86_64' // FIXME
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.22.1'
}
}
// testOptions {
// managedDevices {
// devices {
// // run with ../gradlew nexusOneApi30DebugAndroidTest
// nexusOneApi30(ManagedVirtualDevice) {
// // A lower resolution device is used here for better emulator performance
// device = "Nexus One"
// apiLevel = 30
// // Also use the AOSP ATD image for better emulator performance
// systemImageSource = "aosp-atd"
// }
// }
// }
// }
}
dependencies {
api 'com.squareup.okhttp3:okhttp:3.12.13'
implementation 'androidx.core:core-ktx:1.9.0'
// implementation 'androidx.appcompat:appcompat:1.3.0'
// implementation 'com.google.android.material:material:1.4.0'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
implementation 'com.google.protobuf:protobuf-kotlin-lite:3.20.1'
implementation 'androidx.datastore:datastore-core:1.0.0'
implementation 'androidx.lifecycle:lifecycle-service:2.5.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
testImplementation 'junit:junit:4.13.2'
testImplementation "com.google.truth:truth:1.1.3"
testImplementation "io.mockk:mockk:1.12.5"
// androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// To use the androidx.test.core APIs
androidTestImplementation "androidx.test:core:1.4.0"
// Kotlin extensions for androidx.test.core
androidTestImplementation "androidx.test:core-ktx:1.4.0"
// To use the androidx.test.espresso
// androidTestImplementation "androidx.test:espresso:espresso-core:3.4.0"
// To use the JUnit Extension APIs
androidTestImplementation "androidx.test.ext:junit:1.1.3"
// Kotlin extensions for androidx.test.ext.junit
androidTestImplementation "androidx.test.ext:junit-ktx:1.1.3"
// To use the Truth Extension APIs
androidTestImplementation "androidx.test.ext:truth:1.4.0"
// To use the androidx.test.runner APIs
androidTestImplementation "androidx.test:runner:1.4.0"
// To use android test orchestrator
// androidTestUtil "androidx.test:orchestrator:1.4.1"
androidTestImplementation "androidx.test:rules:1.4.0"
androidTestImplementation "io.mockk:mockk-android:1.12.5"
}

View File

26
lib/android/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,26 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Keeps methods that are invoked by JNI.
-keepclassmembers class * {
@im.molly.monero.UsedByNative *;
}

View File

@ -0,0 +1,9 @@
package im.molly.monero
fun CharSequence.parseHex(): ByteArray {
check(length % 2 == 0) { "Must have an even length" }
return ByteArray(length / 2) {
Integer.parseInt(substring(it * 2, (it + 1) * 2), 16).toByte()
}
}

View File

@ -0,0 +1,24 @@
package im.molly.monero
import android.os.Parcel
import com.google.common.truth.Truth
import org.junit.Test
import kotlin.random.Random
class SecretKeyParcelableTest {
@Test
fun testParcel() {
val secret = Random.nextBytes(32)
val originalKey = SecretKey(secret)
val parcel = Parcel.obtain()
originalKey.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
val key = SecretKey.create(parcel)
Truth.assertThat(key == originalKey).isTrue()
}
}

View File

@ -0,0 +1,27 @@
package im.molly.monero
import android.content.Intent
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ServiceTestRule
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
class WalletNativeServiceTest {
@get:Rule
val serviceRule = ServiceTestRule()
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
// private val resources by lazy { context.resources }
@Test
fun testBind() {
assertThat(bindService()).isNotNull()
}
private fun bindService(): IWalletService {
val binder = serviceRule.bindService(Intent(context, WalletService::class.java))
return IWalletService.Stub.asInterface(binder)
}
}

View File

@ -0,0 +1,58 @@
package im.molly.monero
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class WalletNativeTest {
@LargeTest
@Test
fun keyGenerationIsDeterministic() {
assertThat(
WalletNative.fullNode(MoneroNetwork.Mainnet.id) {
secretSpendKey(SecretKey("d2ca26e22489bd9871c910c58dee3ab08e66b9d566825a064c8c0af061cd8706".parseHex()))
}.publicAddress
).isEqualTo("4AYjQM9HoAFNUeC3cvSfgeAN89oMMpMqiByvunzSzhn97cj726rJj3x8hCbH58UnMqQJShczCxbpWRiCJQ3HCUDHLiKuo4T")
assertThat(
WalletNative.fullNode(MoneroNetwork.Testnet.id) {
secretSpendKey(SecretKey("48a35268bc33227eea43ac1ecfd144d51efc023c115c26ca68a01cc6201e9900".parseHex()))
}.publicAddress
).isEqualTo("A1v6gVUcGgGE87c1uFRWB1KfPVik2qLLDJiZT3rhZ8qjF3BGA6oHzeDboD23dH8rFaFFcysyqwF6DBj8WUTBWwEhESB7nZz")
assertThat(
WalletNative.fullNode(MoneroNetwork.Stagenet.id) {
secretSpendKey(SecretKey("561a8d4e121ffca7321a7dc6af79679ceb4cdc8c0dcb0ef588b574586c5fac04".parseHex()))
}.publicAddress
).isEqualTo("54kPaUhYgGNBT72N8Bv2DFMqstLGJCEcWg1EAjwpxABkKL3uBtBLAh4VAPKvhWBdaD4ZpiftA8YWFLAxnWL4aQ9TD4vhY4W")
}
@LargeTest
@Test
fun publicAddressesAreDistinct() {
val publicAddress =
WalletNative.fullNode(MoneroNetwork.Mainnet.id) {
secretSpendKey(randomSecretKey())
}.publicAddress
val anotherPublicAddress =
WalletNative.fullNode(MoneroNetwork.Mainnet.id) {
secretSpendKey(randomSecretKey())
}.publicAddress
assertThat(publicAddress).isNotEqualTo(anotherPublicAddress)
}
@Test
fun atGenesisBalanceIsZero() {
with(
WalletNative.fullNode(MoneroNetwork.Mainnet.id) {
secretSpendKey(randomSecretKey())
}.currentBalance
) {
assertThat(totalAmount).isEqualTo(0.toAtomicAmount())
assertThat(totalAmountUnlockedAt(1)).isEqualTo(0.toAtomicAmount())
}
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="im.molly.monero">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application android:usesCleartextTraffic="true">
<service
android:name=".WalletService"
android:exported="false" />
<!-- android:isolatedProcess="true" />-->
</application>
</manifest>

View File

@ -0,0 +1,3 @@
package im.molly.monero;
parcelable HttpResponse;

View File

@ -0,0 +1,8 @@
package im.molly.monero;
import im.molly.monero.OwnedTxOut;
oneway interface IBalanceListener {
void onBalanceChanged(in List<OwnedTxOut> txOuts, long checkedAtBlockHeight);
void onRefresh(long blockchainHeight);
}

View File

@ -0,0 +1,5 @@
package im.molly.monero;
oneway interface IRefreshCallback {
void onResult(long blockHeight, int status);
}

View File

@ -0,0 +1,9 @@
package im.molly.monero;
import im.molly.monero.HttpResponse;
import im.molly.monero.RemoteNode;
interface IRemoteNodeClient {
// RemoteNode getRemoteNode();
HttpResponse makeRequest(String method, String path, String header, in byte[] body);
}

View File

@ -0,0 +1,16 @@
package im.molly.monero;
import im.molly.monero.IBalanceListener;
import im.molly.monero.IRefreshCallback;
import im.molly.monero.PublicAddress;
interface IWallet {
String getPrimaryAccountAddress();
void addBalanceListener(in IBalanceListener listener);
void removeBalanceListener(in IBalanceListener listener);
void save(in ParcelFileDescriptor destination);
oneway void restartRefresh(boolean skipCoinbaseOutputs, in IRefreshCallback callback);
oneway void stopRefresh();
void setRefreshSince(long heightOrTimestamp);
void close();
}

View File

@ -0,0 +1,8 @@
package im.molly.monero;
import im.molly.monero.IRemoteNodeClient;
interface IWalletClient {
int getNetworkId();
IRemoteNodeClient getRemoteNodeClient();
}

View File

@ -0,0 +1,14 @@
package im.molly.monero;
import im.molly.monero.IRemoteNodeClient;
import im.molly.monero.IWallet;
import im.molly.monero.IWalletServiceListener;
import im.molly.monero.SecretKey;
import im.molly.monero.WalletConfig;
interface IWalletService {
IWallet createWallet(in WalletConfig config, in IRemoteNodeClient client);
IWallet restoreWallet(in WalletConfig config, in IRemoteNodeClient client, in SecretKey spendSecretKey, long accountCreationTimestamp);
IWallet openWallet(in WalletConfig config, in IRemoteNodeClient client, in ParcelFileDescriptor source);
void setListener(in IWalletServiceListener listener);
}

View File

@ -0,0 +1,5 @@
package im.molly.monero;
oneway interface IWalletServiceListener {
void onLogMessage(int priority, String tag, String msg, String cause);
}

View File

@ -0,0 +1,3 @@
package im.molly.monero;
parcelable OwnedTxOut;

View File

@ -0,0 +1,3 @@
package im.molly.monero;
parcelable PublicAddress;

View File

@ -0,0 +1,3 @@
package im.molly.monero;
parcelable RemoteNode;

View File

@ -0,0 +1,3 @@
package im.molly.monero;
parcelable SecretKey;

Some files were not shown because too many files have changed in this diff Show More