initial: sovereign Mukan Network fork
Some checks are pending
/ might_release (push) Waiting to run

This commit is contained in:
Mukan Erkin TÖRÜK 2026-05-11 03:18:23 +03:00
commit 02226c4bd9
148 changed files with 19800 additions and 0 deletions

17
.github/workflows/go-unit.yml vendored Normal file
View file

@ -0,0 +1,17 @@
name: Unit tests
on:
pull_request:
jobs:
tests:
runs-on: ubuntu-latest
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "stable"
check-latest: true
- name: Tests
run: |
make test

19
.github/workflows/lint-pr.yml vendored Normal file
View file

@ -0,0 +1,19 @@
name: Lint PR
on:
pull_request_target:
types:
- opened
- edited
- synchronize
permissions:
contents: read
jobs:
lint:
permissions:
pull-requests: read
statuses: write
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5.5.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

25
.github/workflows/lint.yml vendored Normal file
View file

@ -0,0 +1,25 @@
name: Lint
on:
pull_request:
paths:
- "**/*.go"
- "go.mod"
- "go.sum"
- "**/go.mod"
- "**/go.sum"
merge_group:
permissions:
contents: read
jobs:
golangci:
name: golangci-lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "stable"
check-latest: true
- name: run linting
run: |
make lint

56
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,56 @@
# This workflow is useful if you want to automate the process of:
#
# a) Creating a new prelease when you push a new tag with a "v" prefix (version).
#
# This type of prerelease is meant to be used for production: alpha, beta, rc, etc. types of releases.
# After the prerelease is created, you need to make your changes on the release page at the relevant
# Github page and publish your release.
#
# b) Creating/updating the "latest" prerelease when you push to your default branch.
#
# This type of prelease is useful to make your bleeding-edge binaries available to advanced users.
#
# The workflow will not run if there is no tag pushed with a "v" prefix and no change pushed to your
# default branch.
on: push
jobs:
might_release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Prepare Release Variables
id: vars
uses: ignite/cli/actions/release/vars@main
- name: Issue Release Assets
uses: ignite/cli/actions/cli@main
if: ${{ steps.vars.outputs.should_release == 'true' }}
with:
args: chain build --release --release.prefix ${{ steps.vars.outputs.tarball_prefix }} -t linux:amd64 -t darwin:amd64 -t darwin:arm64 -y
env:
DO_NOT_TRACK: 1
GOFLAGS: "-buildvcs=false"
- name: Delete the "latest" Release
uses: dev-drprasad/delete-tag-and-release@v0.2.1
if: ${{ steps.vars.outputs.is_release_type_latest == 'true' }}
with:
tag_name: ${{ steps.vars.outputs.tag_name }}
delete_release: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish the Release
uses: softprops/action-gh-release@v1
if: ${{ steps.vars.outputs.should_release == 'true' }}
with:
tag_name: ${{ steps.vars.outputs.tag_name }}
files: release/*
prerelease: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

9
.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
vue/node_modules
vue/dist
release/
.idea/
.vscode/
.DS_Store
*.dot
*.log
*.ign

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/licenses/why-not-lgpl.html>.

105
Makefile Normal file
View file

@ -0,0 +1,105 @@
BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
COMMIT := $(shell git log -1 --format='%H')
APPNAME := mukan
# do not override user values
ifeq (,$(VERSION))
VERSION := $(shell git describe --exact-match 2>/dev/null)
# if VERSION is empty, then populate it with branch name and raw commit hash
ifeq (,$(VERSION))
VERSION := $(BRANCH)-$(COMMIT)
endif
endif
# Update the ldflags with the app, client & server names
ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=$(APPNAME) \
-X github.com/cosmos/cosmos-sdk/version.AppName=$(APPNAME)d \
-X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \
-X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT)
BUILD_FLAGS := -ldflags '$(ldflags)'
##############
### Test ###
##############
test-unit:
@echo Running unit tests...
@go test -mod=readonly -v -timeout 30m ./...
test-race:
@echo Running unit tests with race condition reporting...
@go test -mod=readonly -v -race -timeout 30m ./...
test-cover:
@echo Running unit tests and creating coverage report...
@go test -mod=readonly -v -timeout 30m -coverprofile=$(COVER_FILE) -covermode=atomic ./...
@go tool cover -html=$(COVER_FILE) -o $(COVER_HTML_FILE)
@rm $(COVER_FILE)
bench:
@echo Running unit tests with benchmarking...
@go test -mod=readonly -v -timeout 30m -bench=. ./...
test: govet govulncheck test-unit
.PHONY: test test-unit test-race test-cover bench
#################
### Install ###
#################
all: install
install:
@echo "--> ensure dependencies have not been modified"
@go mod verify
@echo "--> installing $(APPNAME)d"
@go install $(BUILD_FLAGS) -mod=readonly ./cmd/$(APPNAME)d
.PHONY: all install
##################
### Protobuf ###
##################
# Use this target if you do not want to use Ignite for generating proto files
proto-deps:
@echo "Installing proto deps"
@echo "Proto deps present, run 'go tool' to see them"
proto-gen:
@echo "Generating protobuf files..."
@ignite generate proto-go --yes
.PHONY: proto-gen
#################
### Linting ###
#################
lint:
@echo "--> Running linter"
@go tool github.com/golangci/golangci-lint/cmd/golangci-lint run ./... --timeout 15m
lint-fix:
@echo "--> Running linter and fixing issues"
@go tool github.com/golangci/golangci-lint/cmd/golangci-lint run ./... --fix --timeout 15m
.PHONY: lint lint-fix
###################
### Development ###
###################
govet:
@echo Running go vet...
@go vet ./...
govulncheck:
@echo Running govulncheck...
@go tool golang.org/x/vuln/cmd/govulncheck@latest
@govulncheck ./...
.PHONY: govet govulncheck

23
README.md Normal file
View file

@ -0,0 +1,23 @@
# Mukan Core
**Mukan Core** is the official node implementation (daemon) for the **Mukan Network**.
Built on top of the heavily customized [Mukan SDK](https://git.cw.tr/mukan-network/mukan-sdk), it serves as the foundational Layer-1 blockchain infrastructure emphasizing the principles of **Fair Birth**, **Zero Initial Supply**, and a unique **PoW/PoJ (Proof of Justice)** hybrid consensus.
## Vision
Mukan Network completely rejects the traditional "rich get richer" Proof of Stake genesis model. Instead, the network bootstraps with exactly **0 UMC**, relying entirely on the computational effort (PoW) and algorithmic verification (PoJ) of its early participants. Staking and governance mechanics only activate once the network achieves true decentralization through labor.
## Architecture
- **Daemon:** `mukand`
- **Framework:** Mukan SDK (A sovereign fork of the Cosmos SDK)
- **Consensus Core:** Ignite CLI scaffolded, CometBFT powered.
- **Key Modules:** `x/poj` (Proof of Justice) and `x/qpos` (Quadratic PoS).
## Getting Started
*(Documentation for building and running the `mukand` node will be added as the network matures.)*
## License
Licensed under the **GNU General Public License v3.0 (GPLv3)**.

309
app/app.go Normal file
View file

@ -0,0 +1,309 @@
package app
import (
"io"
clienthelpers "cosmossdk.io/client/v2/helpers"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
circuitkeeper "cosmossdk.io/x/circuit/keeper"
upgradekeeper "cosmossdk.io/x/upgrade/keeper"
abci "github.com/cometbft/cometbft/abci/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
icacontrollerkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/controller/keeper"
icahostkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/host/keeper"
ibctransferkeeper "github.com/cosmos/ibc-go/v10/modules/apps/transfer/keeper"
ibckeeper "github.com/cosmos/ibc-go/v10/modules/core/keeper"
"mukan/docs"
mukanmodulekeeper "mukan/x/mukan/keeper"
pojmodulekeeper "mukan/x/poj/keeper"
qposmodulekeeper "mukan/x/qpos/keeper"
)
const (
// Name is the name of the application.
Name = "mukan"
// AccountAddressPrefix is the prefix for accounts addresses.
AccountAddressPrefix = "mukan"
// ChainCoinType is the coin type of the chain.
ChainCoinType = 118
)
// DefaultNodeHome default home directories for the application daemon
var DefaultNodeHome string
var (
_ runtime.AppI = (*App)(nil)
_ servertypes.Application = (*App)(nil)
)
// App extends an ABCI application, but with most of its parameters exported.
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
type App struct {
*runtime.App
legacyAmino *codec.LegacyAmino
appCodec codec.Codec
txConfig client.TxConfig
interfaceRegistry codectypes.InterfaceRegistry
// keepers
// only keepers required by the app are exposed
// the list of all modules is available in the app_config
AuthKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
StakingKeeper *stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
UpgradeKeeper *upgradekeeper.Keeper
AuthzKeeper authzkeeper.Keeper
ConsensusParamsKeeper consensuskeeper.Keeper
CircuitBreakerKeeper circuitkeeper.Keeper
ParamsKeeper paramskeeper.Keeper
// ibc keepers
IBCKeeper *ibckeeper.Keeper
ICAControllerKeeper icacontrollerkeeper.Keeper
ICAHostKeeper icahostkeeper.Keeper
TransferKeeper ibctransferkeeper.Keeper
// simulation manager
sm *module.SimulationManager
MukanKeeper mukanmodulekeeper.Keeper
PojKeeper pojmodulekeeper.Keeper
QposKeeper qposmodulekeeper.Keeper
}
func init() {
var err error
clienthelpers.EnvPrefix = Name
DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory("." + Name)
if err != nil {
panic(err)
}
}
// AppConfig returns the default app config.
func AppConfig() depinject.Config {
return depinject.Configs(
appConfig,
depinject.Supply(
// supply custom module basics
map[string]module.AppModuleBasic{
genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
},
),
)
}
// New returns a reference to an initialized App.
func New(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
loadLatest bool,
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *App {
var (
app = &App{}
appBuilder *runtime.AppBuilder
// merge the AppConfig and other configuration in one config
appConfig = depinject.Configs(
AppConfig(),
depinject.Supply(
appOpts, // supply app options
logger, // supply logger
// Supply with IBC keeper getter for the IBC modules with App Wiring.
// The IBC Keeper cannot be passed because it has not been initiated yet.
// Passing the getter, the app IBC Keeper will always be accessible.
// This needs to be removed after IBC supports App Wiring.
app.GetIBCKeeper,
// here alternative options can be supplied to the DI container.
// those options can be used f.e to override the default behavior of some modules.
// for instance supplying a custom address codec for not using bech32 addresses.
// read the depinject documentation and depinject module wiring for more information
// on available options and how to use them.
),
)
)
var appModules map[string]appmodule.AppModule
if err := depinject.Inject(appConfig,
&appBuilder,
&appModules,
&app.appCodec,
&app.legacyAmino,
&app.txConfig,
&app.interfaceRegistry,
&app.AuthKeeper,
&app.BankKeeper,
&app.StakingKeeper,
&app.SlashingKeeper,
&app.UpgradeKeeper,
&app.AuthzKeeper,
&app.ConsensusParamsKeeper,
&app.CircuitBreakerKeeper,
&app.ParamsKeeper,
&app.MukanKeeper,
&app.PojKeeper,
&app.QposKeeper,
); err != nil {
panic(err)
}
// Stake Lock: Intercept messages to block staking during bootstrapping
// We'll use a simple approach by checking messages in a custom AnteHandler if needed,
// but for Phase 1, we can also do it in the PojKeeper's logic.
// add to default baseapp options
// enable optimistic execution
baseAppOptions = append(baseAppOptions, baseapp.SetOptimisticExecution())
// build app
app.App = appBuilder.Build(db, traceStore, baseAppOptions...)
// register legacy modules
if err := app.registerIBCModules(appOpts); err != nil {
panic(err)
}
/**** Module Options ****/
// create the simulation manager and define the order of the modules for deterministic simulations
overrideModules := map[string]module.AppModuleSimulation{
authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AuthKeeper, authsims.RandomGenesisAccounts, nil),
}
app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules)
app.sm.RegisterStoreDecoders()
// A custom InitChainer sets if extra pre-init-genesis logic is required.
// This is necessary for manually registered modules that do not support app wiring.
// Manually set the module version map as shown below.
// The upgrade module will automatically handle de-duplication of the module version map.
app.SetInitChainer(func(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) {
if err := app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()); err != nil {
return nil, err
}
return app.App.InitChainer(ctx, req)
})
if err := app.Load(loadLatest); err != nil {
panic(err)
}
return app
}
// GetSubspace returns a param subspace for a given module name.
func (app *App) GetSubspace(moduleName string) paramstypes.Subspace {
subspace, _ := app.ParamsKeeper.GetSubspace(moduleName)
return subspace
}
// LegacyAmino returns App's amino codec.
func (app *App) LegacyAmino() *codec.LegacyAmino {
return app.legacyAmino
}
// AppCodec returns App's app codec.
func (app *App) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns App's InterfaceRegistry.
func (app *App) InterfaceRegistry() codectypes.InterfaceRegistry {
return app.interfaceRegistry
}
// TxConfig returns App's TxConfig
func (app *App) TxConfig() client.TxConfig {
return app.txConfig
}
// GetKey returns the KVStoreKey for the provided store key.
func (app *App) GetKey(storeKey string) *storetypes.KVStoreKey {
kvStoreKey, ok := app.UnsafeFindStoreKey(storeKey).(*storetypes.KVStoreKey)
if !ok {
return nil
}
return kvStoreKey
}
// SimulationManager implements the SimulationApp interface
func (app *App) SimulationManager() *module.SimulationManager {
return app.sm
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
app.App.RegisterAPIRoutes(apiSvr, apiConfig)
// register swagger API in app.go so that other applications can override easily
if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil {
panic(err)
}
// register app's OpenAPI routes.
docs.RegisterOpenAPIService(Name, apiSvr.Router)
}
// GetMaccPerms returns a copy of the module account permissions
//
// NOTE: This is solely to be used for testing purposes.
func GetMaccPerms() map[string][]string {
dup := make(map[string][]string)
for _, perms := range moduleAccPerms {
dup[perms.GetAccount()] = perms.GetPermissions()
}
return dup
}
// BlockedAddresses returns all the app's blocked account addresses.
func BlockedAddresses() map[string]bool {
result := make(map[string]bool)
if len(blockAccAddrs) > 0 {
for _, addr := range blockAccAddrs {
result[addr] = true
}
} else {
for addr := range GetMaccPerms() {
result[addr] = true
}
}
return result
}

227
app/app_config.go Normal file
View file

@ -0,0 +1,227 @@
package app
import (
_ "mukan/x/mukan/module"
mukanmoduletypes "mukan/x/mukan/types"
_ "mukan/x/poj/module"
pojmoduletypes "mukan/x/poj/types"
_ "mukan/x/qpos/module"
qposmoduletypes "mukan/x/qpos/types"
"time"
runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1"
appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1"
authmodulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
authzmodulev1 "cosmossdk.io/api/cosmos/authz/module/v1"
bankmodulev1 "cosmossdk.io/api/cosmos/bank/module/v1"
circuitmodulev1 "cosmossdk.io/api/cosmos/circuit/module/v1"
consensusmodulev1 "cosmossdk.io/api/cosmos/consensus/module/v1"
evidencemodulev1 "cosmossdk.io/api/cosmos/evidence/module/v1"
feegrantmodulev1 "cosmossdk.io/api/cosmos/feegrant/module/v1"
genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
groupmodulev1 "cosmossdk.io/api/cosmos/group/module/v1"
nftmodulev1 "cosmossdk.io/api/cosmos/nft/module/v1"
paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1"
slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1"
stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1"
txconfigv1 "cosmossdk.io/api/cosmos/tx/config/v1"
upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1"
vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1"
"cosmossdk.io/depinject/appconfig"
_ "cosmossdk.io/x/circuit" // import for side-effects
circuittypes "cosmossdk.io/x/circuit/types"
_ "cosmossdk.io/x/evidence" // import for side-effects
evidencetypes "cosmossdk.io/x/evidence/types"
"cosmossdk.io/x/feegrant"
_ "cosmossdk.io/x/feegrant/module" // import for side-effects
"cosmossdk.io/x/nft"
_ "cosmossdk.io/x/nft/module" // import for side-effects
_ "cosmossdk.io/x/upgrade" // import for side-effects
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/cosmos/cosmos-sdk/runtime"
_ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" // import for side-effects
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
_ "github.com/cosmos/cosmos-sdk/x/auth/vesting" // import for side-effects
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/cosmos/cosmos-sdk/x/authz"
_ "github.com/cosmos/cosmos-sdk/x/authz/module" // import for side-effects
_ "github.com/cosmos/cosmos-sdk/x/bank" // import for side-effects
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
_ "github.com/cosmos/cosmos-sdk/x/consensus" // import for side-effects
consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/group"
_ "github.com/cosmos/cosmos-sdk/x/group/module" // import for side-effects
_ "github.com/cosmos/cosmos-sdk/x/params" // import for side-effects
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
_ "github.com/cosmos/cosmos-sdk/x/slashing" // import for side-effects
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
_ "github.com/cosmos/cosmos-sdk/x/staking" // import for side-effects
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
icatypes "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/types"
ibctransfertypes "github.com/cosmos/ibc-go/v10/modules/apps/transfer/types"
ibcexported "github.com/cosmos/ibc-go/v10/modules/core/exported"
"google.golang.org/protobuf/types/known/durationpb"
)
var (
moduleAccPerms = []*authmodulev1.ModuleAccountPermission{
{Account: authtypes.FeeCollectorName},
{Account: stakingtypes.BondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: stakingtypes.NotBondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: nft.ModuleName},
{Account: ibctransfertypes.ModuleName, Permissions: []string{authtypes.Minter, authtypes.Burner}},
{Account: icatypes.ModuleName},
{Account: pojmoduletypes.ModuleName, Permissions: []string{authtypes.Minter, authtypes.Burner, authtypes.Staking}},
{Account: qposmoduletypes.ModuleName, Permissions: []string{authtypes.Minter, authtypes.Burner, authtypes.Staking}},
}
// blocked account addresses
blockAccAddrs = []string{
authtypes.FeeCollectorName,
stakingtypes.BondedPoolName,
stakingtypes.NotBondedPoolName,
nft.ModuleName,
}
// application configuration (used by depinject)
appConfig = appconfig.Compose(&appv1alpha1.Config{
Modules: []*appv1alpha1.ModuleConfig{
{
Name: runtime.ModuleName,
Config: appconfig.WrapAny(&runtimev1alpha1.Module{
AppName: Name,
PreBlockers: []string{
upgradetypes.ModuleName,
authtypes.ModuleName,
},
BeginBlockers: []string{
slashingtypes.ModuleName,
evidencetypes.ModuleName,
stakingtypes.ModuleName,
authz.ModuleName,
ibcexported.ModuleName,
mukanmoduletypes.ModuleName,
pojmoduletypes.ModuleName,
qposmoduletypes.ModuleName,
},
EndBlockers: []string{
stakingtypes.ModuleName,
feegrant.ModuleName,
group.ModuleName,
mukanmoduletypes.ModuleName,
pojmoduletypes.ModuleName,
qposmoduletypes.ModuleName,
},
InitGenesis: []string{
consensustypes.ModuleName,
authtypes.ModuleName,
banktypes.ModuleName,
stakingtypes.ModuleName,
slashingtypes.ModuleName,
genutiltypes.ModuleName,
evidencetypes.ModuleName,
authz.ModuleName,
feegrant.ModuleName,
vestingtypes.ModuleName,
nft.ModuleName,
group.ModuleName,
upgradetypes.ModuleName,
circuittypes.ModuleName,
ibcexported.ModuleName,
ibctransfertypes.ModuleName,
icatypes.ModuleName,
mukanmoduletypes.ModuleName,
pojmoduletypes.ModuleName,
qposmoduletypes.ModuleName,
},
}),
},
{
Name: authtypes.ModuleName,
Config: appconfig.WrapAny(&authmodulev1.Module{
Bech32Prefix: AccountAddressPrefix,
ModuleAccountPermissions: moduleAccPerms,
EnableUnorderedTransactions: true,
}),
},
{
Name: vestingtypes.ModuleName,
Config: appconfig.WrapAny(&vestingmodulev1.Module{}),
},
{
Name: banktypes.ModuleName,
Config: appconfig.WrapAny(&bankmodulev1.Module{
BlockedModuleAccountsOverride: blockAccAddrs,
}),
},
{
Name: stakingtypes.ModuleName,
Config: appconfig.WrapAny(&stakingmodulev1.Module{}),
},
{
Name: slashingtypes.ModuleName,
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
},
{
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{}),
},
{
Name: genutiltypes.ModuleName,
Config: appconfig.WrapAny(&genutilmodulev1.Module{}),
},
{
Name: authz.ModuleName,
Config: appconfig.WrapAny(&authzmodulev1.Module{}),
},
{
Name: upgradetypes.ModuleName,
Config: appconfig.WrapAny(&upgrademodulev1.Module{}),
},
{
Name: evidencetypes.ModuleName,
Config: appconfig.WrapAny(&evidencemodulev1.Module{}),
},
{
Name: group.ModuleName,
Config: appconfig.WrapAny(&groupmodulev1.Module{
MaxExecutionPeriod: durationpb.New(time.Second * 1209600),
MaxMetadataLen: 255,
}),
},
{
Name: nft.ModuleName,
Config: appconfig.WrapAny(&nftmodulev1.Module{}),
},
{
Name: feegrant.ModuleName,
Config: appconfig.WrapAny(&feegrantmodulev1.Module{}),
},
{
Name: consensustypes.ModuleName,
Config: appconfig.WrapAny(&consensusmodulev1.Module{}),
},
{
Name: circuittypes.ModuleName,
Config: appconfig.WrapAny(&circuitmodulev1.Module{}),
},
{
Name: paramstypes.ModuleName,
Config: appconfig.WrapAny(&paramsmodulev1.Module{}),
},
{
Name: mukanmoduletypes.ModuleName,
Config: appconfig.WrapAny(&mukanmoduletypes.Module{}),
},
{
Name: pojmoduletypes.ModuleName,
Config: appconfig.WrapAny(&pojmoduletypes.Module{}),
},
{
Name: qposmoduletypes.ModuleName,
Config: appconfig.WrapAny(&qposmoduletypes.Module{}),
},
},
})
)

24
app/config.go Normal file
View file

@ -0,0 +1,24 @@
package app
import sdk "github.com/cosmos/cosmos-sdk/types"
func init() {
// Set bond denom
sdk.DefaultBondDenom = "stake"
// Set address prefixes
accountPubKeyPrefix := AccountAddressPrefix + "pub"
validatorAddressPrefix := AccountAddressPrefix + "valoper"
validatorPubKeyPrefix := AccountAddressPrefix + "valoperpub"
consNodeAddressPrefix := AccountAddressPrefix + "valcons"
consNodePubKeyPrefix := AccountAddressPrefix + "valconspub"
// Set and seal config
config := sdk.GetConfig()
config.SetCoinType(ChainCoinType)
config.SetBech32PrefixForAccount(AccountAddressPrefix, accountPubKeyPrefix)
config.SetBech32PrefixForValidator(validatorAddressPrefix, validatorPubKeyPrefix)
config.SetBech32PrefixForConsensusNode(consNodeAddressPrefix, consNodePubKeyPrefix)
config.Seal()
}

262
app/export.go Normal file
View file

@ -0,0 +1,262 @@
package app
import (
"encoding/json"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
storetypes "cosmossdk.io/store/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// ExportAppStateAndValidators exports the state of the application for a genesis
// file.
func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block
ctx := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()})
// We export at last height + 1, because that's the height at which
// CometBFT will start InitChain.
height := app.LastBlockHeight() + 1
if forZeroHeight {
height = 0
app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs)
}
genState, err := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport)
if err != nil {
return servertypes.ExportedApp{}, err
}
appState, err := json.MarshalIndent(genState, "", " ")
if err != nil {
return servertypes.ExportedApp{}, err
}
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
return servertypes.ExportedApp{
AppState: appState,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
}, err
}
// prepForZeroHeightGenesis prepares for fresh start at zero height
// NOTE zero height genesis is a temporary feature which will be deprecated
//
// in favor of export at a block height
func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) {
applyAllowedAddrs := false
// check if there is a allowed address list
if len(jailAllowedAddrs) > 0 {
applyAllowedAddrs = true
}
allowedAddrsMap := make(map[string]bool)
for _, addr := range jailAllowedAddrs {
_, err := app.InterfaceRegistry().SigningContext().ValidatorAddressCodec().StringToBytes(addr)
if err != nil {
panic(err)
}
allowedAddrsMap[addr] = true
}
/* Handle fee distribution state. */
/* Disabled for Mukan Network Phase 1 (no x/distribution)
// withdraw all validator commission
err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
panic(err)
}
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, valBz)
return false
})
if err != nil {
panic(err)
}
// withdraw all delegator rewards
dels, err := app.StakingKeeper.GetAllDelegations(ctx)
if err != nil {
panic(err)
}
for _, delegation := range dels {
valAddr, err := app.InterfaceRegistry().SigningContext().ValidatorAddressCodec().StringToBytes(delegation.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr, err := app.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(delegation.DelegatorAddress)
if err != nil {
panic(err)
}
_, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr)
}
// clear validator slash events
app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx)
// clear validator historical rewards
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
*/
// set context height to zero
height := ctx.BlockHeight()
ctx = ctx.WithBlockHeight(0)
// reinitialize all validators
err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
/*
valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
panic(err)
}
*/
/* Disabled for Mukan Network Phase 1 (no x/distribution)
// donate any unwithdrawn outstanding reward tokens to the community pool
rewards, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz)
if err != nil {
panic(err)
}
feePool, err := app.DistrKeeper.FeePool.Get(ctx)
if err != nil {
panic(err)
}
feePool.CommunityPool = feePool.CommunityPool.Add(rewards...)
if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil {
panic(err)
}
if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil {
panic(err)
}
*/
return false
})
if err != nil {
panic(err)
}
/* Disabled for Mukan Network Phase 1 (no x/distribution)
// reinitialize all delegations
for _, del := range dels {
valAddr, err := app.InterfaceRegistry().SigningContext().ValidatorAddressCodec().StringToBytes(del.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr, err := app.InterfaceRegistry().SigningContext().AddressCodec().StringToBytes(del.DelegatorAddress)
if err != nil {
panic(err)
}
if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil {
// never called as BeforeDelegationCreated always returns nil
panic(fmt.Errorf("error while incrementing period: %w", err))
}
if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil {
// never called as AfterDelegationModified always returns nil
panic(fmt.Errorf("error while creating a new delegation period record: %w", err))
}
}
*/
// reset context height
ctx = ctx.WithBlockHeight(height)
/* Handle staking state. */
// iterate through redelegations, reset creation height
err = app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
for i := range red.Entries {
red.Entries[i].CreationHeight = 0
}
err = app.StakingKeeper.SetRedelegation(ctx, red)
if err != nil {
panic(err)
}
return false
})
if err != nil {
panic(err)
}
// iterate through unbonding delegations, reset creation height
err = app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) {
for i := range ubd.Entries {
ubd.Entries[i].CreationHeight = 0
}
err = app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
if err != nil {
panic(err)
}
return false
})
if err != nil {
panic(err)
}
// Iterate through validators by power descending, reset bond heights, and
// update bond intra-tx counters.
store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey))
iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key()))
validator, err := app.StakingKeeper.GetValidator(ctx, addr)
if err != nil {
panic("expected validator, not found")
}
valAddr, err := app.StakingKeeper.ValidatorAddressCodec().BytesToString(addr)
if err != nil {
panic(err)
}
validator.UnbondingHeight = 0
if applyAllowedAddrs && !allowedAddrsMap[valAddr] {
validator.Jailed = true
}
if err = app.StakingKeeper.SetValidator(ctx, validator); err != nil {
panic(err)
}
}
if err := iter.Close(); err != nil {
app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err)
return
}
_, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
panic(err)
}
/* Handle slashing state. */
// reset start height on signing infos
if err := app.SlashingKeeper.IterateValidatorSigningInfos(
ctx,
func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) {
info.StartHeight = 0
_ = app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info)
return false
},
); err != nil {
panic(err)
}
}

14
app/genesis.go Normal file
View file

@ -0,0 +1,14 @@
package app
import (
"encoding/json"
)
// GenesisState of the blockchain is represented here as a map of raw json
// messages key'd by a identifier string.
// The identifier is used to determine which module genesis information belongs
// to so it may be appropriately routed during init chain.
// Within this application default genesis information is retrieved from
// the ModuleBasicManager which populates json from each BasicModule
// object provided to it during init.
type GenesisState map[string]json.RawMessage

47
app/genesis_account.go Normal file
View file

@ -0,0 +1,47 @@
package app
import (
"errors"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
var _ authtypes.GenesisAccount = (*GenesisAccount)(nil)
// GenesisAccount defines a type that implements the GenesisAccount interface
// to be used for simulation accounts in the genesis state.
type GenesisAccount struct {
*authtypes.BaseAccount
// vesting account fields
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"` // total vesting coins upon initialization
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"` // delegated vested coins at time of delegation
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"` // delegated vesting coins at time of delegation
StartTime int64 `json:"start_time" yaml:"start_time"` // vesting start time (UNIX Epoch time)
EndTime int64 `json:"end_time" yaml:"end_time"` // vesting end time (UNIX Epoch time)
// module account fields
ModuleName string `json:"module_name" yaml:"module_name"` // name of the module account
ModulePermissions []string `json:"module_permissions" yaml:"module_permissions"` // permissions of module account
}
// Validate checks for errors on the vesting and module account parameters
func (sga GenesisAccount) Validate() error {
if !sga.OriginalVesting.IsZero() {
if sga.StartTime >= sga.EndTime {
return errors.New("vesting start-time cannot be before end-time")
}
}
if sga.ModuleName != "" {
ma := authtypes.ModuleAccount{
BaseAccount: sga.BaseAccount, Name: sga.ModuleName, Permissions: sga.ModulePermissions,
}
if err := ma.Validate(); err != nil {
return err
}
}
return sga.BaseAccount.Validate()
}

171
app/ibc.go Normal file
View file

@ -0,0 +1,171 @@
package app
import (
"cosmossdk.io/core/appmodule"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/types/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
icamodule "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts"
icacontroller "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/controller"
icacontrollerkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/controller/keeper"
icacontrollertypes "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/controller/types"
icahost "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/host"
icahostkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/host/keeper"
icahosttypes "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/host/types"
icatypes "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/types"
ibctransfer "github.com/cosmos/ibc-go/v10/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v10/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v10/modules/apps/transfer/types"
ibctransferv2 "github.com/cosmos/ibc-go/v10/modules/apps/transfer/v2"
ibc "github.com/cosmos/ibc-go/v10/modules/core"
ibcclienttypes "github.com/cosmos/ibc-go/v10/modules/core/02-client/types" // nolint:staticcheck // Deprecated: params key table is needed for params migration
ibcconnectiontypes "github.com/cosmos/ibc-go/v10/modules/core/03-connection/types"
porttypes "github.com/cosmos/ibc-go/v10/modules/core/05-port/types"
ibcapi "github.com/cosmos/ibc-go/v10/modules/core/api"
ibcexported "github.com/cosmos/ibc-go/v10/modules/core/exported"
ibckeeper "github.com/cosmos/ibc-go/v10/modules/core/keeper"
solomachine "github.com/cosmos/ibc-go/v10/modules/light-clients/06-solomachine"
ibctm "github.com/cosmos/ibc-go/v10/modules/light-clients/07-tendermint"
)
// registerIBCModules register IBC keepers and non dependency inject modules.
func (app *App) registerIBCModules(appOpts servertypes.AppOptions) error {
// set up non depinject support modules store keys
if err := app.RegisterStores(
storetypes.NewKVStoreKey(ibcexported.StoreKey),
storetypes.NewKVStoreKey(ibctransfertypes.StoreKey),
storetypes.NewKVStoreKey(icahosttypes.StoreKey),
storetypes.NewKVStoreKey(icacontrollertypes.StoreKey),
); err != nil {
return err
}
// register the key tables for legacy param subspaces
keyTable := ibcclienttypes.ParamKeyTable()
keyTable.RegisterParamSet(&ibcconnectiontypes.Params{})
app.ParamsKeeper.Subspace(ibcexported.ModuleName).WithKeyTable(keyTable)
app.ParamsKeeper.Subspace(ibctransfertypes.ModuleName).WithKeyTable(ibctransfertypes.ParamKeyTable())
app.ParamsKeeper.Subspace(icacontrollertypes.SubModuleName).WithKeyTable(icacontrollertypes.ParamKeyTable())
app.ParamsKeeper.Subspace(icahosttypes.SubModuleName).WithKeyTable(icahosttypes.ParamKeyTable())
govModuleAddr, _ := app.AuthKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress(govtypes.ModuleName))
// Create IBC keeper
app.IBCKeeper = ibckeeper.NewKeeper(
app.appCodec,
runtime.NewKVStoreService(app.GetKey(ibcexported.StoreKey)),
app.GetSubspace(ibcexported.ModuleName),
app.UpgradeKeeper,
govModuleAddr,
)
// Create IBC transfer keeper
app.TransferKeeper = ibctransferkeeper.NewKeeper(
app.appCodec,
runtime.NewKVStoreService(app.GetKey(ibctransfertypes.StoreKey)),
app.GetSubspace(ibctransfertypes.ModuleName),
app.IBCKeeper.ChannelKeeper,
app.IBCKeeper.ChannelKeeper,
app.MsgServiceRouter(),
app.AuthKeeper,
app.BankKeeper,
govModuleAddr,
)
// Create interchain account keepers
app.ICAHostKeeper = icahostkeeper.NewKeeper(
app.appCodec,
runtime.NewKVStoreService(app.GetKey(icahosttypes.StoreKey)),
app.GetSubspace(icahosttypes.SubModuleName),
app.IBCKeeper.ChannelKeeper, // ICS4Wrapper
app.IBCKeeper.ChannelKeeper,
app.AuthKeeper,
app.MsgServiceRouter(),
app.GRPCQueryRouter(),
govModuleAddr,
)
app.ICAControllerKeeper = icacontrollerkeeper.NewKeeper(
app.appCodec,
runtime.NewKVStoreService(app.GetKey(icacontrollertypes.StoreKey)),
app.GetSubspace(icacontrollertypes.SubModuleName),
app.IBCKeeper.ChannelKeeper,
app.IBCKeeper.ChannelKeeper,
app.MsgServiceRouter(),
govModuleAddr,
)
// create IBC module from bottom to top of stack
var (
transferStack porttypes.IBCModule = ibctransfer.NewIBCModule(app.TransferKeeper)
transferStackV2 ibcapi.IBCModule = ibctransferv2.NewIBCModule(app.TransferKeeper)
icaControllerStack porttypes.IBCModule = icacontroller.NewIBCMiddleware(app.ICAControllerKeeper)
icaHostStack porttypes.IBCModule = icahost.NewIBCModule(app.ICAHostKeeper)
)
// create IBC v1 router, add transfer route, then set it on the keeper
ibcRouter := porttypes.NewRouter().
AddRoute(ibctransfertypes.ModuleName, transferStack).
AddRoute(icacontrollertypes.SubModuleName, icaControllerStack).
AddRoute(icahosttypes.SubModuleName, icaHostStack)
// create IBC v2 router, add transfer route, then set it on the keeper
ibcv2Router := ibcapi.NewRouter().
AddRoute(ibctransfertypes.PortID, transferStackV2)
app.IBCKeeper.SetRouter(ibcRouter)
app.IBCKeeper.SetRouterV2(ibcv2Router)
clientKeeper := app.IBCKeeper.ClientKeeper
storeProvider := clientKeeper.GetStoreProvider()
tmLightClientModule := ibctm.NewLightClientModule(app.appCodec, storeProvider)
clientKeeper.AddRoute(ibctm.ModuleName, &tmLightClientModule)
soloLightClientModule := solomachine.NewLightClientModule(app.appCodec, storeProvider)
clientKeeper.AddRoute(solomachine.ModuleName, &soloLightClientModule)
// register IBC modules
if err := app.RegisterModules(
ibc.NewAppModule(app.IBCKeeper),
ibctransfer.NewAppModule(app.TransferKeeper),
icamodule.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper),
ibctm.NewAppModule(tmLightClientModule),
solomachine.NewAppModule(soloLightClientModule),
); err != nil {
return err
}
return nil
}
// RegisterIBC Since the IBC modules don't support dependency injection,
// we need to manually register the modules on the client side.
// This needs to be removed after IBC supports App Wiring.
func RegisterIBC(cdc codec.Codec) map[string]appmodule.AppModule {
modules := map[string]appmodule.AppModule{
ibcexported.ModuleName: ibc.NewAppModule(&ibckeeper.Keeper{}),
ibctransfertypes.ModuleName: ibctransfer.NewAppModule(ibctransferkeeper.Keeper{}),
icatypes.ModuleName: icamodule.NewAppModule(&icacontrollerkeeper.Keeper{}, &icahostkeeper.Keeper{}),
ibctm.ModuleName: ibctm.NewAppModule(ibctm.NewLightClientModule(cdc, ibcclienttypes.StoreProvider{})),
solomachine.ModuleName: solomachine.NewAppModule(solomachine.NewLightClientModule(cdc, ibcclienttypes.StoreProvider{})),
}
for _, m := range modules {
if mr, ok := m.(module.AppModuleBasic); ok {
mr.RegisterInterfaces(cdc.InterfaceRegistry())
}
}
return modules
}
// GetIBCKeeper returns the IBC keeper.
// Used for supply with IBC keeper getter for the IBC modules with App Wiring.
func (app *App) GetIBCKeeper() *ibckeeper.Keeper {
return app.IBCKeeper
}

79
app/sim_bench_test.go Normal file
View file

@ -0,0 +1,79 @@
package app
import (
"os"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli"
)
// Profile with:
// `go test -benchmem -run=^$ ./app -bench ^BenchmarkFullAppSimulation$ -Commit=true -cpuprofile cpu.out`
func BenchmarkFullAppSimulation(b *testing.B) {
b.ReportAllocs()
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "goleveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if err != nil {
b.Fatalf("simulation setup failed: %s", err.Error())
}
if skip {
b.Skip("skipping benchmark application simulation")
}
defer func() {
require.NoError(b, db.Close())
require.NoError(b, os.RemoveAll(dir))
}()
appOptions := viper.New()
if FlagEnableStreamingValue {
m := make(map[string]interface{})
m["streaming.abci.keys"] = []string{"*"}
m["streaming.abci.plugin"] = "abci_v1"
m["streaming.abci.stop-node-on-err"] = true
for key, value := range m {
appOptions.SetDefault(key, value)
}
}
appOptions.SetDefault(flags.FlagHome, DefaultNodeHome)
app := New(logger, db, nil, true, appOptions, interBlockCacheOpt(), baseapp.SetChainID(SimAppChainID))
// run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
b,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.BuildSimulationOperations(app, app.AppCodec(), config, app.TxConfig()),
BlockedAddresses(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
if err = simtestutil.CheckExportSimulation(app, config, simParams); err != nil {
b.Fatal(err)
}
if simErr != nil {
b.Fatal(simErr)
}
if config.Commit {
simtestutil.PrintStats(db)
}
}

464
app/sim_test.go Normal file
View file

@ -0,0 +1,464 @@
package app
import (
"encoding/json"
"flag"
"fmt"
"math/rand"
"os"
"runtime/debug"
"strings"
"testing"
"time"
"cosmossdk.io/log"
"cosmossdk.io/store"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/feegrant"
upgradetypes "cosmossdk.io/x/upgrade/types"
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
simulationtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/simulation"
simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
const (
SimAppChainID = "mukan-simapp"
)
var FlagEnableStreamingValue bool
// Get flags every time the simulator is run
func init() {
simcli.GetSimulatorFlags()
flag.BoolVar(&FlagEnableStreamingValue, "EnableStreaming", false, "Enable streaming service")
}
// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of
// an IAVLStore for faster simulation speed.
func fauxMerkleModeOpt(bapp *baseapp.BaseApp) {
bapp.SetFauxMerkleMode()
}
// interBlockCacheOpt returns a BaseApp option function that sets the persistent
// inter-block write-through cache.
func interBlockCacheOpt() func(*baseapp.BaseApp) {
return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager())
}
// BenchmarkSimulation run the chain simulation
// Running using ignite command:
// `ignite chain simulate -v --numBlocks 200 --blockSize 50`
// Running as go benchmark test:
// `go test -benchmem -run=^$ -bench ^BenchmarkSimulation ./app -NumBlocks=200 -BlockSize 50 -Commit=true -Verbose=true -Enabled=true`
func BenchmarkSimulation(b *testing.B) {
simcli.FlagSeedValue = time.Now().Unix()
simcli.FlagVerboseValue = true
simcli.FlagCommitValue = true
simcli.FlagEnabledValue = true
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if skip {
b.Skip("skipping application simulation")
}
require.NoError(b, err, "simulation setup failed")
defer func() {
require.NoError(b, db.Close())
require.NoError(b, os.RemoveAll(dir))
}()
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = DefaultNodeHome
bApp := New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
require.Equal(b, Name, bApp.Name())
// run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
b,
os.Stdout,
bApp.BaseApp,
simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(bApp, bApp.AppCodec(), config, bApp.TxConfig()),
BlockedAddresses(),
config,
bApp.AppCodec(),
)
// export state and simParams before the simulation error is checked
err = simtestutil.CheckExportSimulation(bApp, config, simParams)
require.NoError(b, err)
require.NoError(b, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
}
func TestFullAppSimulation(t *testing.T) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if skip {
t.Skip("skipping application simulation")
}
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = DefaultNodeHome
app := New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
if !simcli.FlagSigverifyTxValue {
app.SetNotSigverifyTx()
}
require.Equal(t, "mukan", app.Name())
// run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(app, app.AppCodec(), config, app.TxConfig()),
BlockedAddresses(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
err = simtestutil.CheckExportSimulation(app, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
}
func TestAppImportExport(t *testing.T) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if skip {
t.Skip("skipping application import/export simulation")
}
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = DefaultNodeHome
bApp := New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
require.Equal(t, Name, bApp.Name())
// Run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
bApp.BaseApp,
simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(bApp, bApp.AppCodec(), config, bApp.TxConfig()),
BlockedAddresses(),
config,
bApp.AppCodec(),
)
// export state and simParams before the simulation error is checked
err = simtestutil.CheckExportSimulation(bApp, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
fmt.Printf("exporting genesis...\n")
exported, err := bApp.ExportAppStateAndValidators(false, []string{}, []string{})
require.NoError(t, err)
fmt.Printf("importing genesis...\n")
newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()
newApp := New(log.NewNopLogger(), newDB, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
require.Equal(t, Name, newApp.Name())
var genesisState GenesisState
err = json.Unmarshal(exported.AppState, &genesisState)
require.NoError(t, err)
ctxA := bApp.NewContextLegacy(true, cmtproto.Header{Height: bApp.LastBlockHeight()})
ctxB := newApp.NewContextLegacy(true, cmtproto.Header{Height: bApp.LastBlockHeight()})
_, err = newApp.ModuleManager.InitGenesis(ctxB, bApp.AppCodec(), genesisState)
if err != nil {
if strings.Contains(err.Error(), "validator set is empty after InitGenesis") {
logger.Info("Skipping simulation as all validators have been unbonded")
logger.Info("err", err, "stacktrace", string(debug.Stack()))
return
}
}
require.NoError(t, err)
err = newApp.StoreConsensusParams(ctxB, exported.ConsensusParams)
require.NoError(t, err)
fmt.Printf("comparing stores...\n")
// skip certain prefixes
skipPrefixes := map[string][][]byte{
upgradetypes.StoreKey: {
[]byte{upgradetypes.VersionMapByte},
},
stakingtypes.StoreKey: {
stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey,
stakingtypes.HistoricalInfoKey, stakingtypes.UnbondingIDKey, stakingtypes.UnbondingIndexKey,
stakingtypes.UnbondingTypeKey, stakingtypes.ValidatorUpdatesKey,
},
authzkeeper.StoreKey: {authzkeeper.GrantQueuePrefix},
feegrant.StoreKey: {feegrant.FeeAllowanceQueueKeyPrefix},
slashingtypes.StoreKey: {slashingtypes.ValidatorMissedBlockBitmapKeyPrefix},
}
storeKeys := bApp.GetStoreKeys()
require.NotEmpty(t, storeKeys)
for _, appKeyA := range storeKeys {
// only compare kvstores
if _, ok := appKeyA.(*storetypes.KVStoreKey); !ok {
continue
}
keyName := appKeyA.Name()
appKeyB := newApp.GetKey(keyName)
storeA := ctxA.KVStore(appKeyA)
storeB := ctxB.KVStore(appKeyB)
failedKVAs, failedKVBs := simtestutil.DiffKVStores(storeA, storeB, skipPrefixes[keyName])
require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare %s, key stores %s and %s", keyName, appKeyA, appKeyB)
t.Logf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), appKeyA, appKeyB)
require.Equal(t, 0, len(failedKVAs), simtestutil.GetSimulationLog(keyName, bApp.SimulationManager().StoreDecoders, failedKVAs, failedKVBs))
}
}
func TestAppSimulationAfterImport(t *testing.T) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if skip {
t.Skip("skipping application simulation after import")
}
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = DefaultNodeHome
bApp := New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
require.Equal(t, Name, bApp.Name())
// Run randomized simulation
stopEarly, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
bApp.BaseApp,
simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(bApp, bApp.AppCodec(), config, bApp.TxConfig()),
BlockedAddresses(),
config,
bApp.AppCodec(),
)
// export state and simParams before the simulation error is checked
err = simtestutil.CheckExportSimulation(bApp, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
if stopEarly {
fmt.Println("can't export or import a zero-validator genesis, exiting test...")
return
}
fmt.Printf("exporting genesis...\n")
exported, err := bApp.ExportAppStateAndValidators(true, []string{}, []string{})
require.NoError(t, err)
fmt.Printf("importing genesis...\n")
newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()
newApp := New(log.NewNopLogger(), newDB, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
require.Equal(t, Name, newApp.Name())
_, err = newApp.InitChain(&abci.RequestInitChain{
AppStateBytes: exported.AppState,
ChainId: SimAppChainID,
})
require.NoError(t, err)
_, _, err = simulation.SimulateFromSeed(
t,
os.Stdout,
newApp.BaseApp,
simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(newApp, newApp.AppCodec(), config, newApp.TxConfig()),
BlockedAddresses(),
config,
bApp.AppCodec(),
)
require.NoError(t, err)
}
func TestAppStateDeterminism(t *testing.T) {
if !simcli.FlagEnabledValue {
t.Skip("skipping application simulation")
}
config := simcli.NewConfigFromFlags()
config.InitialBlockHeight = 1
config.ExportParamsPath = ""
config.OnOperation = true
config.AllInvariants = true
config.ChainID = SimAppChainID
numSeeds := 3
numTimesToRunPerSeed := 3 // This used to be set to 5, but we've temporarily reduced it to 3 for the sake of faster CI.
appHashList := make([]json.RawMessage, numTimesToRunPerSeed)
// We will be overriding the random seed and just run a single simulation on the provided seed value
if config.Seed != simcli.DefaultSeedValue {
numSeeds = 1
}
appOptions := viper.New()
if FlagEnableStreamingValue {
m := make(map[string]interface{})
m["streaming.abci.keys"] = []string{"*"}
m["streaming.abci.plugin"] = "abci_v1"
m["streaming.abci.stop-node-on-err"] = true
for key, value := range m {
appOptions.SetDefault(key, value)
}
}
appOptions.SetDefault(flags.FlagHome, DefaultNodeHome)
if simcli.FlagVerboseValue {
appOptions.SetDefault(flags.FlagLogLevel, "debug")
}
for i := 0; i < numSeeds; i++ {
if config.Seed == simcli.DefaultSeedValue {
config.Seed = rand.Int63()
}
fmt.Println("config.Seed: ", config.Seed)
for j := 0; j < numTimesToRunPerSeed; j++ {
var logger log.Logger
if simcli.FlagVerboseValue {
logger = log.NewTestLogger(t)
} else {
logger = log.NewNopLogger()
}
db := dbm.NewMemDB()
bApp := New(
logger,
db,
nil,
true,
appOptions,
interBlockCacheOpt(),
baseapp.SetChainID(SimAppChainID),
)
fmt.Printf(
"running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n",
config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
)
_, _, err := simulation.SimulateFromSeed(
t,
os.Stdout,
bApp.BaseApp,
simtestutil.AppStateFn(
bApp.AppCodec(),
bApp.SimulationManager(),
bApp.DefaultGenesis(),
),
simulationtypes.RandomAccounts,
simtestutil.BuildSimulationOperations(bApp, bApp.AppCodec(), config, bApp.TxConfig()),
BlockedAddresses(),
config,
bApp.AppCodec(),
)
require.NoError(t, err)
if config.Commit {
simtestutil.PrintStats(db)
}
appHash := bApp.LastCommitID().Hash
appHashList[j] = appHash
if j != 0 {
require.Equal(
t, string(appHashList[0]), string(appHashList[j]),
"non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
)
}
}
}
}

24
buf.lock Normal file
View file

@ -0,0 +1,24 @@
# Generated by buf. DO NOT EDIT.
version: v2
deps:
- name: buf.build/cosmos/cosmos-proto
commit: 04467658e59e44bbb22fe568206e1f70
digest: b5:8058c0aadbee8c9af67a9cefe86492c6c0b0bd5b4526b0ec820507b91fc9b0b5efbebca97331854576d2d279b0b3f5ed6a7abb0640cb640c4186532239c48fc4
- name: buf.build/cosmos/cosmos-sdk
commit: 65fa41963e6a41dd95a35934239029df
digest: b5:45c2788f1c8ca1c0e72f643d51dba37c3b25d113ee166277cd60dfd49404e713a178e177beaa7d6d016f3853722d77f8fbf40e9444e173cd3d89754d39ca0427
- name: buf.build/cosmos/gogo-proto
commit: 88ef6483f90f478fb938c37dde52ece3
digest: b5:f0c69202c9bca9672dc72a9737ea9bc83744daaed2b3da77e3a95b0e53b86dee76b5a7405b993181d6c863fd64afaca0976a302f700d6c4912eb1692a1782c0a
- name: buf.build/cosmos/ibc
commit: 857539074f9c4dda961f9db5dcf8e462
digest: b5:35746d095f73e8b59b7430388be8a72b1e01c2d36ec49df2025ec96a983a62441f67c0843219e06675186e155bfd25624187bd7c512e59e1e355750bb5586ce2
- name: buf.build/cosmos/ics23
commit: dc427cb4519143d8996361c045a29ad7
digest: b5:8693e72e230bfaf58a88a47a4093ba99f6252c1957a45582567959b38a8563e2abd11443372283d75f4f2306a7e3cc9bf63604d284a016c11966fca4b74b7a28
- name: buf.build/googleapis/googleapis
commit: c17df5b2beca46928cc87d5656bd5343
digest: b5:648a01e0170d4512dea7d564016165decd1ed6e34bef79fe54753e51ad7e27545709ad9157d7551270147d551155c595a2fb0bf5bb33b1c83040ddbce915c604
- name: buf.build/protocolbuffers/wellknowntypes
commit: 9d16d599a978406980f6e2f081331a93
digest: b5:dd06e497a5c52f5ddf6ec02b3c7d289cc6c0432093fc2f6bf7a4fb5fae786c3e4c893e55d2759ffb6833268daf3de0bce303a406fed15725790528f2c27dc219

30
buf.yaml Normal file
View file

@ -0,0 +1,30 @@
breaking:
except:
- EXTENSION_NO_DELETE
- FIELD_SAME_DEFAULT
use:
- FILE
deps:
- buf.build/cosmos/cosmos-proto
- buf.build/cosmos/cosmos-sdk
- buf.build/cosmos/gogo-proto
- buf.build/cosmos/ics23
- buf.build/googleapis/googleapis
- buf.build/protocolbuffers/wellknowntypes
- buf.build/cosmos/ibc
lint:
disallow_comment_ignores: true
except:
- COMMENT_FIELD
- RPC_REQUEST_STANDARD_NAME
- RPC_RESPONSE_STANDARD_NAME
- SERVICE_SUFFIX
ignore:
- proto/tendermint
use:
- COMMENTS
- STANDARD
- FILE_LOWER_SNAKE_CASE
modules:
- path: proto
version: v2

163
cmd/mukand/cmd/commands.go Normal file
View file

@ -0,0 +1,163 @@
package cmd
import (
"errors"
"io"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"cosmossdk.io/log"
confixcmd "cosmossdk.io/tools/confix/cmd"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/pruning"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/client/snapshot"
"github.com/cosmos/cosmos-sdk/server"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/types/module"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"mukan/app"
)
func initRootCmd(
rootCmd *cobra.Command,
txConfig client.TxConfig,
basicManager module.BasicManager,
) {
rootCmd.AddCommand(
genutilcli.InitCmd(basicManager, app.DefaultNodeHome),
NewInPlaceTestnetCmd(),
NewTestnetMultiNodeCmd(basicManager, banktypes.GenesisBalancesIterator{}),
debug.Cmd(),
confixcmd.ConfigCommand(),
pruning.Cmd(newApp, app.DefaultNodeHome),
snapshot.Cmd(newApp),
)
server.AddCommandsWithStartCmdOptions(rootCmd, app.DefaultNodeHome, newApp, appExport, server.StartCmdOptions{
AddFlags: addModuleInitFlags,
})
// add keybase, auxiliary RPC, query, genesis, and tx child commands
rootCmd.AddCommand(
server.StatusCommand(),
genutilcli.Commands(txConfig, basicManager, app.DefaultNodeHome),
queryCommand(),
txCommand(),
keys.Commands(),
)
}
// addModuleInitFlags adds more flags to the start command.
func addModuleInitFlags(startCmd *cobra.Command) {
}
func queryCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Aliases: []string{"q"},
Short: "Querying subcommands",
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
rpc.WaitTxCmd(),
rpc.ValidatorCommand(),
server.QueryBlockCmd(),
authcmd.QueryTxsByEventsCmd(),
server.QueryBlocksCmd(),
authcmd.QueryTxCmd(),
server.QueryBlockResultsCmd(),
)
return cmd
}
func txCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "tx",
Short: "Transactions subcommands",
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetSignCommand(),
authcmd.GetSignBatchCommand(),
authcmd.GetMultiSignCommand(),
authcmd.GetMultiSignBatchCmd(),
authcmd.GetValidateSignaturesCommand(),
flags.LineBreak,
authcmd.GetBroadcastCommand(),
authcmd.GetEncodeCommand(),
authcmd.GetDecodeCommand(),
authcmd.GetSimulateCmd(),
)
return cmd
}
// newApp creates the application
func newApp(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
appOpts servertypes.AppOptions,
) servertypes.Application {
baseappOptions := server.DefaultBaseappOptions(appOpts)
return app.New(
logger, db, traceStore, true,
appOpts,
baseappOptions...,
)
}
// appExport creates a new app (optionally at a given height) and exports state.
func appExport(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
height int64,
forZeroHeight bool,
jailAllowedAddrs []string,
appOpts servertypes.AppOptions,
modulesToExport []string,
) (servertypes.ExportedApp, error) {
var bApp *app.App
// this check is necessary as we use the flag in x/upgrade.
// we can exit more gracefully by checking the flag here.
homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" {
return servertypes.ExportedApp{}, errors.New("application home not set")
}
viperAppOpts, ok := appOpts.(*viper.Viper)
if !ok {
return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper")
}
appOpts = viperAppOpts
if height != -1 {
bApp = app.New(logger, db, traceStore, false, appOpts)
if err := bApp.LoadHeight(height); err != nil {
return servertypes.ExportedApp{}, err
}
} else {
bApp = app.New(logger, db, traceStore, true, appOpts)
}
return bApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport)
}

61
cmd/mukand/cmd/config.go Normal file
View file

@ -0,0 +1,61 @@
package cmd
import (
cmtcfg "github.com/cometbft/cometbft/config"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
)
// initCometBFTConfig helps to override default CometBFT Config values.
// return cmtcfg.DefaultConfig if no custom configuration is required for the application.
func initCometBFTConfig() *cmtcfg.Config {
cfg := cmtcfg.DefaultConfig()
// these values put a higher strain on node memory
// cfg.P2P.MaxNumInboundPeers = 100
// cfg.P2P.MaxNumOutboundPeers = 40
return cfg
}
// initAppConfig helps to override default appConfig template and configs.
// return "", nil if no custom configuration is required for the application.
func initAppConfig() (string, interface{}) {
// The following code snippet is just for reference.
type CustomAppConfig struct {
serverconfig.Config `mapstructure:",squash"`
}
// Optionally allow the chain developer to overwrite the SDK's default
// server config.
srvCfg := serverconfig.DefaultConfig()
// The SDK's default minimum gas price is set to "" (empty value) inside
// app.toml. If left empty by validators, the node will halt on startup.
// However, the chain developer can set a default app.toml value for their
// validators here.
//
// In summary:
// - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their
// own app.toml config,
// - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their
// own app.toml to override, or use this default value.
//
// In tests, we set the min gas prices to 0.
// srvCfg.MinGasPrices = "0stake"
customAppConfig := CustomAppConfig{
Config: *srvCfg,
}
customAppTemplate := serverconfig.DefaultConfigTemplate
// Edit the default template file
//
// customAppTemplate := serverconfig.DefaultConfigTemplate + `
// [wasm]
// # This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries
// query_gas_limit = 300000
// # This is the number of wasm vm instances we keep cached in memory for speed-up
// # Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally
// lru_size = 0`
return customAppTemplate, customAppConfig
}

123
cmd/mukand/cmd/root.go Normal file
View file

@ -0,0 +1,123 @@
package cmd
import (
"os"
"cosmossdk.io/client/v2/autocli"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
authtxconfig "github.com/cosmos/cosmos-sdk/x/auth/tx/config"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/spf13/cobra"
"mukan/app"
)
// NewRootCmd creates a new root command for mukand. It is called once in the main function.
func NewRootCmd() *cobra.Command {
var (
autoCliOpts autocli.AppOptions
moduleBasicManager module.BasicManager
clientCtx client.Context
)
if err := depinject.Inject(
depinject.Configs(app.AppConfig(),
depinject.Supply(log.NewNopLogger()),
depinject.Provide(
ProvideClientContext,
),
),
&autoCliOpts,
&moduleBasicManager,
&clientCtx,
); err != nil {
panic(err)
}
rootCmd := &cobra.Command{
Use: app.Name + "d",
Short: "mukan node",
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// set the default command outputs
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
clientCtx = clientCtx.WithCmdContext(cmd.Context()).WithViper(app.Name)
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
clientCtx, err = config.ReadFromClientConfig(clientCtx)
if err != nil {
return err
}
if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil {
return err
}
customAppTemplate, customAppConfig := initAppConfig()
customCMTConfig := initCometBFTConfig()
return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig)
},
}
// Since the IBC modules don't support dependency injection, we need to
// manually register the modules on the client side.
// This needs to be removed after IBC supports App Wiring.
ibcModules := app.RegisterIBC(clientCtx.Codec)
for name, mod := range ibcModules {
moduleBasicManager[name] = module.CoreAppModuleBasicAdaptor(name, mod)
autoCliOpts.Modules[name] = mod
}
initRootCmd(rootCmd, clientCtx.TxConfig, moduleBasicManager)
if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil {
panic(err)
}
return rootCmd
}
// ProvideClientContext creates and provides a fully initialized client.Context,
// allowing it to be used for dependency injection and CLI operations.
func ProvideClientContext(
appCodec codec.Codec,
interfaceRegistry codectypes.InterfaceRegistry,
txConfigOpts tx.ConfigOptions,
legacyAmino *codec.LegacyAmino,
) client.Context {
clientCtx := client.Context{}.
WithCodec(appCodec).
WithInterfaceRegistry(interfaceRegistry).
WithLegacyAmino(legacyAmino).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithHomeDir(app.DefaultNodeHome).
WithViper(app.Name) // env variable prefix
// Read the config again to overwrite the default values with the values from the config file
clientCtx, _ = config.ReadFromClientConfig(clientCtx)
// textual is enabled by default, we need to re-create the tx config grpc instead of bank keeper.
txConfigOpts.TextualCoinMetadataQueryFn = authtxconfig.NewGRPCCoinMetadataQueryFn(clientCtx)
txConfig, err := tx.NewTxConfigWithOptions(clientCtx.Codec, txConfigOpts)
if err != nil {
panic(err)
}
clientCtx = clientCtx.WithTxConfig(txConfig)
return clientCtx
}

242
cmd/mukand/cmd/testnet.go Normal file
View file

@ -0,0 +1,242 @@
package cmd
import (
"errors"
"fmt"
"io"
"os"
"strings"
"cosmossdk.io/log"
"cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
"github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/libs/bytes"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/client/flags"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/server"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/spf13/cast"
"github.com/spf13/cobra"
"mukan/app"
pojmoduletypes "mukan/x/poj/types"
)
const valVotingPower int64 = 900000000000000
var flagAccountsToFund = "accounts-to-fund"
type valArgs struct {
newValAddr bytes.HexBytes
newOperatorAddress string
newValPubKey crypto.PubKey
accountsToFund []string
upgradeToTrigger string
homeDir string
}
func NewInPlaceTestnetCmd() *cobra.Command {
cmd := server.InPlaceTestnetCreator(newTestnetApp)
cmd.Short = "Updates chain's application and consensus state with provided validator info and starts the node"
cmd.Long = `The test command modifies both application and consensus stores within a local mainnet node and starts the node,
with the aim of facilitating testing procedures. This command replaces existing validator data with updated information,
thereby removing the old validator set and introducing a new set suitable for local testing purposes. By altering the state extracted from the mainnet node,
it enables developers to configure their local environments to reflect mainnet conditions more accurately.`
cmd.Example = fmt.Sprintf(`%sd in-place-testnet testing-1 cosmosvaloper1w7f3xx7e75p4l7qdym5msqem9rd4dyc4mq79dm --home $HOME/.%sd/validator1 --validator-privkey=6dq+/KHNvyiw2TToCgOpUpQKIzrLs69Rb8Az39xvmxPHNoPxY1Cil8FY+4DhT9YwD6s0tFABMlLcpaylzKKBOg== --accounts-to-fund="cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq,cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x"`, "mukan", "mukan")
cmd.Flags().String(flagAccountsToFund, "", "Comma-separated list of account addresses that will be funded for testing purposes")
return cmd
}
// newTestnetApp starts by running the normal newApp method. From there, the app interface returned is modified in order
// for a testnet to be created from the provided app.
func newTestnetApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
// Create an app and type cast to an App
newApp := newApp(logger, db, traceStore, appOpts)
testApp, ok := newApp.(*app.App)
if !ok {
panic("app created from newApp is not of type App")
}
// Get command args
args, err := getCommandArgs(appOpts)
if err != nil {
panic(err)
}
return initAppForTestnet(testApp, args)
}
func initAppForTestnet(app *app.App, args valArgs) *app.App {
// Required Changes:
//
ctx := app.App.NewUncachedContext(true, cmtproto.Header{})
pubkey := &ed25519.PubKey{Key: args.newValPubKey.Bytes()}
pubkeyAny, err := codectypes.NewAnyWithValue(pubkey)
handleErr(err)
// STAKING
//
// Create Validator struct for our new validator.
newVal := stakingtypes.Validator{
OperatorAddress: args.newOperatorAddress,
ConsensusPubkey: pubkeyAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: math.NewInt(valVotingPower),
DelegatorShares: math.LegacyMustNewDecFromStr("10000000"),
Description: stakingtypes.Description{
Moniker: "Testnet Validator",
},
Commission: stakingtypes.Commission{
CommissionRates: stakingtypes.CommissionRates{
Rate: math.LegacyMustNewDecFromStr("0.05"),
MaxRate: math.LegacyMustNewDecFromStr("0.1"),
MaxChangeRate: math.LegacyMustNewDecFromStr("0.05"),
},
},
MinSelfDelegation: math.OneInt(),
}
validator, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(newVal.GetOperator())
handleErr(err)
// Remove all validators from power store
stakingKey := app.GetKey(stakingtypes.ModuleName)
stakingStore := ctx.KVStore(stakingKey)
iterator, err := app.StakingKeeper.ValidatorsPowerStoreIterator(ctx)
handleErr(err)
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
iterator.Close()
// Remove all validators from last validators store
iterator, err = app.StakingKeeper.LastValidatorsIterator(ctx)
handleErr(err)
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
iterator.Close()
// Remove all validators from validators store
iterator = stakingStore.Iterator(stakingtypes.ValidatorsKey, storetypes.PrefixEndBytes(stakingtypes.ValidatorsKey))
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
iterator.Close()
// Remove all validators from unbonding queue
iterator = stakingStore.Iterator(stakingtypes.ValidatorQueueKey, storetypes.PrefixEndBytes(stakingtypes.ValidatorQueueKey))
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
iterator.Close()
// Add our validator to power and last validators store
handleErr(app.StakingKeeper.SetValidator(ctx, newVal))
handleErr(app.StakingKeeper.SetValidatorByConsAddr(ctx, newVal))
handleErr(app.StakingKeeper.SetValidatorByPowerIndex(ctx, newVal))
handleErr(app.StakingKeeper.SetLastValidatorPower(ctx, validator, 0))
handleErr(app.StakingKeeper.Hooks().AfterValidatorCreated(ctx, validator))
// DISTRIBUTION
//
/* Disabled for Mukan Network Phase 1 (no x/distribution)
// Initialize records for this validator across all distribution stores
handleErr(app.DistrKeeper.SetValidatorHistoricalRewards(ctx, validator, 0, distrtypes.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)))
handleErr(app.DistrKeeper.SetValidatorCurrentRewards(ctx, validator, distrtypes.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)))
handleErr(app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, validator, distrtypes.InitialValidatorAccumulatedCommission()))
handleErr(app.DistrKeeper.SetValidatorOutstandingRewards(ctx, validator, distrtypes.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}))
*/
// SLASHING
//
// Set validator signing info for our new validator.
newConsAddr := sdk.ConsAddress(args.newValAddr.Bytes())
newValidatorSigningInfo := slashingtypes.ValidatorSigningInfo{
Address: newConsAddr.String(),
StartHeight: app.App.LastBlockHeight() - 1,
Tombstoned: false,
}
_ = app.SlashingKeeper.SetValidatorSigningInfo(ctx, newConsAddr, newValidatorSigningInfo)
// BANK
//
bondDenom, err := app.StakingKeeper.BondDenom(ctx)
handleErr(err)
defaultCoins := sdk.NewCoins(sdk.NewInt64Coin(bondDenom, 1000000000))
// Fund local accounts
for _, accountStr := range args.accountsToFund {
handleErr(app.BankKeeper.MintCoins(ctx, pojmoduletypes.ModuleName, defaultCoins))
account, err := app.AuthKeeper.AddressCodec().StringToBytes(accountStr)
handleErr(err)
handleErr(app.BankKeeper.SendCoinsFromModuleToAccount(ctx, pojmoduletypes.ModuleName, account, defaultCoins))
}
return app
}
// parse the input flags and returns valArgs
func getCommandArgs(appOpts servertypes.AppOptions) (valArgs, error) {
args := valArgs{}
newValAddr, ok := appOpts.Get(server.KeyNewValAddr).(bytes.HexBytes)
if !ok {
return args, errors.New("newValAddr is not of type bytes.HexBytes")
}
args.newValAddr = newValAddr
newValPubKey, ok := appOpts.Get(server.KeyUserPubKey).(crypto.PubKey)
if !ok {
return args, errors.New("newValPubKey is not of type crypto.PubKey")
}
args.newValPubKey = newValPubKey
newOperatorAddress, ok := appOpts.Get(server.KeyNewOpAddr).(string)
if !ok {
return args, errors.New("newOperatorAddress is not of type string")
}
args.newOperatorAddress = newOperatorAddress
upgradeToTrigger, ok := appOpts.Get(server.KeyTriggerTestnetUpgrade).(string)
if !ok {
return args, errors.New("upgradeToTrigger is not of type string")
}
args.upgradeToTrigger = upgradeToTrigger
// parsing and set accounts to fund
accountsString := cast.ToString(appOpts.Get(flagAccountsToFund))
args.accountsToFund = append(args.accountsToFund, strings.Split(accountsString, ",")...)
// home dir
homeDir := cast.ToString(appOpts.Get(flags.FlagHome))
if homeDir == "" {
return args, errors.New("invalid home dir")
}
args.homeDir = homeDir
return args, nil
}
// handleErr prints the error and exits the program if the error is not nil
func handleErr(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}

View file

@ -0,0 +1,540 @@
package cmd
import (
"bufio"
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"time"
cmtconfig "github.com/cometbft/cometbft/config"
types "github.com/cometbft/cometbft/types"
tmtime "github.com/cometbft/cometbft/types/time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/server"
srvconfig "github.com/cosmos/cosmos-sdk/server/config"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
runtime "github.com/cosmos/cosmos-sdk/runtime"
)
var (
flagNodeDirPrefix = "node-dir-prefix"
flagPorts = "list-ports"
flagNumValidators = "v"
flagOutputDir = "output-dir"
flagValidatorsStakeAmount = "validators-stake-amount"
flagStartingIPAddress = "starting-ip-address"
)
const nodeDirPerm = 0o755
type initArgs struct {
algo string
chainID string
keyringBackend string
minGasPrices string
nodeDirPrefix string
numValidators int
outputDir string
startingIPAddress string
validatorsStakesAmount map[int]sdk.Coin
ports map[int]string
}
// NewTestnetMultiNodeCmd returns a cmd to initialize all files for tendermint testnet and application
func NewTestnetMultiNodeCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command {
cmd := &cobra.Command{
Use: "multi-node",
Short: "Initialize config directories & files for a multi-validator testnet running locally via separate processes (e.g. Docker Compose or similar)",
Long: `multi-node will setup "v" number of directories and populate each with
necessary files (private validator, genesis, config, etc.) for running "v" validator nodes.
Booting up a network with these validator folders is intended to be used with Docker Compose,
or a similar setup where each node has a manually configurable IP address.
Note, strict routability for addresses is turned off in the config file.
Example:
mukand multi-node --v 4 --output-dir ./.testnets --validators-stake-amount 1000000,200000,300000,400000 --list-ports 47222,50434,52851,44210
`,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
args := initArgs{}
args.outputDir, _ = cmd.Flags().GetString(flagOutputDir)
args.keyringBackend, _ = cmd.Flags().GetString(flags.FlagKeyringBackend)
args.chainID, _ = cmd.Flags().GetString(flags.FlagChainID)
args.minGasPrices, _ = cmd.Flags().GetString(server.FlagMinGasPrices)
args.nodeDirPrefix, _ = cmd.Flags().GetString(flagNodeDirPrefix)
args.startingIPAddress, _ = cmd.Flags().GetString(flagStartingIPAddress)
args.numValidators, _ = cmd.Flags().GetInt(flagNumValidators)
args.algo, _ = cmd.Flags().GetString(flags.FlagKeyType)
args.ports = map[int]string{}
args.validatorsStakesAmount = make(map[int]sdk.Coin)
top := 0
// If the flag string is invalid, the amount will default to 100000000.
if s, err := cmd.Flags().GetString(flagValidatorsStakeAmount); err == nil {
for _, amount := range strings.Split(s, ",") {
a, ok := math.NewIntFromString(amount)
if !ok {
continue
}
args.validatorsStakesAmount[top] = sdk.NewCoin(sdk.DefaultBondDenom, a)
top += 1
}
}
top = 0
if s, err := cmd.Flags().GetString(flagPorts); err == nil {
if s == "" {
for i := 0; i < args.numValidators; i++ {
args.ports[top] = strconv.Itoa(26657 - 3*i)
top += 1
}
} else {
for _, port := range strings.Split(s, ",") {
args.ports[top] = port
top += 1
}
}
}
return initTestnetFiles(clientCtx, cmd, config, mbm, genBalIterator, args)
},
}
addTestnetFlagsToCmd(cmd)
cmd.Flags().String(flagPorts, "", "Ports of nodes (default 26657,26654,26651,26648.. )")
cmd.Flags().String(flagNodeDirPrefix, "validator", "Prefix the directory name for each node with (node results in node0, node1, ...)")
cmd.Flags().String(flagValidatorsStakeAmount, "100000000,100000000,100000000,100000000", "Amount of stake for each validator")
cmd.Flags().String(flagStartingIPAddress, "localhost", "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)")
cmd.Flags().String(flags.FlagKeyringBackend, "test", "Select keyring's backend (os|file|test)")
return cmd
}
func addTestnetFlagsToCmd(cmd *cobra.Command) {
cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with")
cmd.Flags().StringP(flagOutputDir, "o", "./.testnets", "Directory to store initialization data for the testnet")
cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created")
cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.0001%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)")
cmd.Flags().String(flags.FlagKeyType, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for")
// support old flags name for backwards compatibility
cmd.Flags().SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
if name == "algo" {
name = flags.FlagKeyType
}
return pflag.NormalizedName(name)
})
}
// initTestnetFiles initializes testnet files for a testnet to be run in a separate process
func initTestnetFiles(
clientCtx client.Context,
cmd *cobra.Command,
nodeConfig *cmtconfig.Config,
mbm module.BasicManager,
genBalIterator banktypes.GenesisBalancesIterator,
args initArgs,
) error {
if args.chainID == "" {
args.chainID = "chain-" + generateRandomString(6)
}
nodeIDs := make([]string, args.numValidators)
valPubKeys := make([]cryptotypes.PubKey, args.numValidators)
appConfig := srvconfig.DefaultConfig()
appConfig.MinGasPrices = args.minGasPrices
appConfig.API.Enable = false
appConfig.BaseConfig.MinGasPrices = "0.0001" + sdk.DefaultBondDenom
appConfig.Telemetry.EnableHostnameLabel = false
appConfig.Telemetry.Enabled = false
appConfig.Telemetry.PrometheusRetentionTime = 0
var (
genAccounts []authtypes.GenesisAccount
genBalances []banktypes.Balance
genFiles []string
persistentPeers string
gentxsFiles []string
)
inBuf := bufio.NewReader(cmd.InOrStdin())
for i := 0; i < args.numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", args.nodeDirPrefix, i)
nodeDir := filepath.Join(args.outputDir, nodeDirName)
gentxsDir := filepath.Join(args.outputDir, nodeDirName, "config", "gentx")
nodeConfig.SetRoot(nodeDir)
nodeConfig.Moniker = nodeDirName
nodeConfig.RPC.ListenAddress = "tcp://0.0.0.0:" + args.ports[i]
var err error
if err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm); err != nil {
_ = os.RemoveAll(args.outputDir)
return err
}
nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(nodeConfig)
if err != nil {
_ = os.RemoveAll(args.outputDir)
return err
}
memo := fmt.Sprintf("%s@%s:"+strconv.Itoa(26656-3*i), nodeIDs[i], args.startingIPAddress)
if persistentPeers == "" {
persistentPeers = memo
} else {
persistentPeers = persistentPeers + "," + memo
}
genFiles = append(genFiles, nodeConfig.GenesisFile())
kb, err := keyring.New(sdk.KeyringServiceName(), args.keyringBackend, nodeDir, inBuf, clientCtx.Codec)
if err != nil {
return err
}
keyringAlgos, _ := kb.SupportedAlgorithms()
algo, err := keyring.NewSigningAlgoFromString(args.algo, keyringAlgos)
if err != nil {
return err
}
addr, secret, err := testutil.GenerateSaveCoinKey(kb, nodeDirName, "", true, algo)
if err != nil {
_ = os.RemoveAll(args.outputDir)
return err
}
info := map[string]string{"secret": secret}
cliPrint, err := json.Marshal(info)
if err != nil {
return err
}
// save private key seed words
file := filepath.Join(nodeDir, fmt.Sprintf("%v.json", "key_seed"))
if err := writeFile(file, nodeDir, cliPrint); err != nil {
return err
}
accTokens := sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction)
accStakingTokens := sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction)
coins := sdk.Coins{
sdk.NewCoin("testtoken", accTokens),
sdk.NewCoin(sdk.DefaultBondDenom, accStakingTokens),
}
genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: coins.Sort()})
genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0))
var valTokens sdk.Coin
valTokens, ok := args.validatorsStakesAmount[i]
if !ok {
valTokens = sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction))
}
createValMsg, err := stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(addr).String(),
valPubKeys[i],
valTokens,
stakingtypes.NewDescription(nodeDirName, "", "", "", ""),
stakingtypes.NewCommissionRates(math.LegacyOneDec(), math.LegacyOneDec(), math.LegacyOneDec()),
math.OneInt(),
)
if err != nil {
return err
}
txBuilder := clientCtx.TxConfig.NewTxBuilder()
if err := txBuilder.SetMsgs(createValMsg); err != nil {
return err
}
txBuilder.SetMemo(memo)
txFactory := tx.Factory{}
txFactory = txFactory.
WithChainID(args.chainID).
WithMemo(memo).
WithKeybase(kb).
WithTxConfig(clientCtx.TxConfig)
if err := tx.Sign(cmd.Context(), txFactory, nodeDirName, txBuilder, true); err != nil {
return err
}
txBz, err := clientCtx.TxConfig.TxJSONEncoder()(txBuilder.GetTx())
if err != nil {
return err
}
file = filepath.Join(gentxsDir, fmt.Sprintf("%v.json", "gentx-"+nodeIDs[i]))
gentxsFiles = append(gentxsFiles, file)
if err := writeFile(file, gentxsDir, txBz); err != nil {
return err
}
appConfig.GRPC.Address = args.startingIPAddress + ":" + strconv.Itoa(9090-2*i)
appConfig.API.Address = "tcp://localhost:" + strconv.Itoa(1317-i)
srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config", "app.toml"), appConfig)
}
if err := initGenFiles(clientCtx, mbm, args.chainID, genAccounts, genBalances, genFiles, args.numValidators); err != nil {
return err
}
// copy gentx file
for i := 0; i < args.numValidators; i++ {
for _, file := range gentxsFiles {
nodeDirName := fmt.Sprintf("%s%d", args.nodeDirPrefix, i)
nodeDir := filepath.Join(args.outputDir, nodeDirName)
gentxsDir := filepath.Join(nodeDir, "config", "gentx")
yes, err := isSubDir(file, gentxsDir)
if err != nil || yes {
continue
}
_, err = copyFile(file, gentxsDir)
if err != nil {
return err
}
}
}
err := collectGenFiles(
clientCtx, nodeConfig, nodeIDs, valPubKeys,
genBalIterator,
clientCtx.TxConfig.SigningContext().ValidatorAddressCodec(),
persistentPeers, args,
)
if err != nil {
return err
}
cmd.PrintErrf("Successfully initialized %d node directories\n", args.numValidators)
return nil
}
func writeFile(file, dir string, contents []byte) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("could not create directory %q: %w", dir, err)
}
if err := os.WriteFile(file, contents, 0o644); err != nil {
return err
}
return nil
}
func initGenFiles(
clientCtx client.Context, mbm module.BasicManager, chainID string,
genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance,
genFiles []string, numValidators int,
) error {
appGenState := mbm.DefaultGenesis(clientCtx.Codec)
// set the accounts in the genesis state
var authGenState authtypes.GenesisState
clientCtx.Codec.MustUnmarshalJSON(appGenState[authtypes.ModuleName], &authGenState)
accounts, err := authtypes.PackAccounts(genAccounts)
if err != nil {
return err
}
authGenState.Accounts = accounts
appGenState[authtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&authGenState)
// set the balances in the genesis state
var bankGenState banktypes.GenesisState
clientCtx.Codec.MustUnmarshalJSON(appGenState[banktypes.ModuleName], &bankGenState)
bankGenState.Balances = banktypes.SanitizeGenesisBalances(genBalances)
for _, bal := range bankGenState.Balances {
bankGenState.Supply = bankGenState.Supply.Add(bal.Coins...)
}
appGenState[banktypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&bankGenState)
appGenStateJSON, err := json.MarshalIndent(appGenState, "", " ")
if err != nil {
return err
}
genDoc := types.GenesisDoc{
ChainID: chainID,
AppState: appGenStateJSON,
Validators: nil,
}
// generate empty genesis files for each validator and save
for i := 0; i < numValidators; i++ {
if err := genDoc.SaveAs(genFiles[i]); err != nil {
return err
}
}
return nil
}
func collectGenFiles(
clientCtx client.Context, nodeConfig *cmtconfig.Config,
nodeIDs []string, valPubKeys []cryptotypes.PubKey,
genBalIterator banktypes.GenesisBalancesIterator,
valAddrCodec runtime.ValidatorAddressCodec, persistentPeers string,
args initArgs,
) error {
chainID := args.chainID
numValidators := args.numValidators
outputDir := args.outputDir
nodeDirPrefix := args.nodeDirPrefix
var appState json.RawMessage
genTime := tmtime.Now()
for i := 0; i < numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i)
nodeDir := filepath.Join(outputDir, nodeDirName)
gentxsDir := filepath.Join(nodeDir, "config", "gentx")
nodeConfig.Moniker = nodeDirName
nodeConfig.SetRoot(nodeDir)
nodeID, valPubKey := nodeIDs[i], valPubKeys[i]
initCfg := genutiltypes.NewInitConfig(chainID, gentxsDir, nodeID, valPubKey)
appGenesis, err := genutiltypes.AppGenesisFromFile(nodeConfig.GenesisFile())
if err != nil {
return err
}
nodeAppState, err := genutil.GenAppStateFromConfig(clientCtx.Codec, clientCtx.TxConfig, nodeConfig, initCfg, appGenesis, genBalIterator, genutiltypes.DefaultMessageValidator,
valAddrCodec)
if err != nil {
return err
}
nodeConfig.P2P.PersistentPeers = persistentPeers
nodeConfig.P2P.AllowDuplicateIP = true
nodeConfig.P2P.ListenAddress = "tcp://0.0.0.0:" + strconv.Itoa(26656-3*i)
nodeConfig.RPC.ListenAddress = "tcp://127.0.0.1:" + args.ports[i]
nodeConfig.BaseConfig.ProxyApp = "tcp://127.0.0.1:" + strconv.Itoa(26658-3*i)
nodeConfig.Instrumentation.PrometheusListenAddr = ":" + strconv.Itoa(26660+i)
nodeConfig.Instrumentation.Prometheus = true
cmtconfig.WriteConfigFile(filepath.Join(nodeConfig.RootDir, "config", "config.toml"), nodeConfig)
if appState == nil {
// set the canonical application state (they should not differ)
appState = nodeAppState
}
genFile := nodeConfig.GenesisFile()
// overwrite each validator's genesis file to have a canonical genesis time
if err := genutil.ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime); err != nil {
return err
}
}
return nil
}
func copyFile(src, dstDir string) (int64, error) {
// Extract the file name from the source path
fileName := filepath.Base(src)
// Create the full destination path (directory + file name)
dst := filepath.Join(dstDir, fileName)
// Open the source file
sourceFile, err := os.Open(src)
if err != nil {
return 0, err
}
defer sourceFile.Close()
// Create the destination file
destinationFile, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destinationFile.Close()
// Copy content from the source file to the destination file
bytesCopied, err := io.Copy(destinationFile, sourceFile)
if err != nil {
return 0, err
}
// Ensure the content is written to the destination file
err = destinationFile.Sync()
if err != nil {
return 0, err
}
return bytesCopied, nil
}
// isSubDir checks if dstDir is a parent directory of src
func isSubDir(src, dstDir string) (bool, error) {
// Get the absolute path of src and dstDir
absSrc, err := filepath.Abs(src)
if err != nil {
return false, err
}
absDstDir, err := filepath.Abs(dstDir)
if err != nil {
return false, err
}
// Check if absSrc is within absDstDir
relativePath, err := filepath.Rel(absDstDir, absSrc)
if err != nil {
return false, err
}
// If the relative path doesn't go up the directory tree (doesn't contain ".."), it is inside dstDir
isInside := !strings.HasPrefix(relativePath, "..") && !filepath.IsAbs(relativePath)
return isInside, nil
}
// generateRandomString generates a random string of the specified length.
func generateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}

20
cmd/mukand/main.go Normal file
View file

@ -0,0 +1,20 @@
package main
import (
"fmt"
"os"
clienthelpers "cosmossdk.io/client/v2/helpers"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"mukan/app"
"mukan/cmd/mukand/cmd"
)
func main() {
rootCmd := cmd.NewRootCmd()
if err := svrcmd.Execute(rootCmd, clienthelpers.EnvPrefix, app.DefaultNodeHome); err != nil {
fmt.Fprintln(rootCmd.OutOrStderr(), err)
os.Exit(1)
}
}

43
config.yml Normal file
View file

@ -0,0 +1,43 @@
version: 1
validation: sovereign
default_denom: umc
chain_id: mettest
accounts:
- name: mukan
coins:
- 0umc
- name: erkin
coins:
- 0umc
client:
openapi:
path: docs/static/openapi.json
faucet:
name: erkin
coins:
- 5umc
validators:
- name: mukan
bonded: 0umc
config:
rpc:
laddr: "tcp://0.0.0.0:10656"
p2p:
laddr: "tcp://0.0.0.0:10756"
instrumentation:
prometheus: true
prometheus_listen_addr: ":10875"
genesis:
app_state:
poj:
params:
blocks_per_epoch: "525600"
micro_cooldown: "1"
macro_cooldown: "5"
macro_streak_limit: "5"
base_reward: "100000000"
min_reward: "1"
mining_difficulty: "4"
mukan_address: "mukan17c09rhtsqf8unscv5scv5scv5scv5scv5scv5s"
erkin_address: "mukan18c09rhtsqf8unscv5scv5scv5scv5scv5scv5s"
toruk_address: "mukan19c09rhtsqf8unscv5scv5scv5scv5scv5s"

40
docs/docs.go Normal file
View file

@ -0,0 +1,40 @@
package docs
import (
"embed"
httptemplate "html/template"
"net/http"
"github.com/gorilla/mux"
)
const (
apiFile = "/static/openapi.json"
indexFile = "template/index.tpl"
)
//go:embed static
var Static embed.FS
//go:embed template
var template embed.FS
func RegisterOpenAPIService(appName string, rtr *mux.Router) {
rtr.Handle(apiFile, http.FileServer(http.FS(Static)))
rtr.HandleFunc("/", handler(appName))
}
// handler returns an http handler that servers OpenAPI console for an OpenAPI spec at specURL.
func handler(title string) http.HandlerFunc {
t, _ := httptemplate.ParseFS(template, indexFile)
return func(w http.ResponseWriter, req *http.Request) {
_ = t.Execute(w, struct {
Title string
URL string
}{
title,
apiFile,
})
}
}

1
docs/static/openapi.json vendored Normal file

File diff suppressed because one or more lines are too long

28
docs/template/index.tpl vendored Normal file
View file

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{{ .Title }}</title>
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3.40.0/swagger-ui.css" />
<link rel="icon" type="image/png" href="//unpkg.com/swagger-ui-dist@3.40.0/favicon-16x16.png" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="//unpkg.com/swagger-ui-dist@3.40.0/swagger-ui-bundle.js"></script>
<script>
// init Swagger for faucet's openapi.json.
window.onload = function() {
window.ui = SwaggerUIBundle({
url: {{ .URL }},
dom_id: "#swagger-ui",
deepLinking: true,
layout: "BaseLayout",
});
}
</script>
</body>
</html>
Footer
© 2022 GitHub, Inc.
Footer navigation

451
go.mod Normal file
View file

@ -0,0 +1,451 @@
module mukan
go 1.25.6
replace (
// support for go 1.26 (remove when cosmossdk.io/log is updated)
github.com/bytedance/sonic => github.com/bytedance/sonic v1.15.0
github.com/cosmos/cosmos-sdk => ../mukan-sdk
// fix upstream GHSA-h395-qcrw-5vmq vulnerability.
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.9.1
// replace broken goleveldb
github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
// replace broken vanity url
nhooyr.io/websocket => github.com/coder/websocket v1.8.7
)
require (
cosmossdk.io/api v0.9.2
cosmossdk.io/client/v2 v2.0.0-beta.11
cosmossdk.io/collections v1.3.1
cosmossdk.io/core v0.11.3
cosmossdk.io/depinject v1.2.1
cosmossdk.io/errors v1.0.2
cosmossdk.io/log v1.6.1
cosmossdk.io/math v1.5.3
cosmossdk.io/store v1.1.2
cosmossdk.io/tools/confix v0.1.2
cosmossdk.io/x/circuit v0.1.1
cosmossdk.io/x/evidence v0.1.1
cosmossdk.io/x/feegrant v0.1.1
cosmossdk.io/x/nft v0.1.0
cosmossdk.io/x/upgrade v0.2.0
github.com/cometbft/cometbft v0.38.21
github.com/cosmos/cosmos-db v1.1.3
github.com/cosmos/cosmos-proto v1.0.0-beta.5
github.com/cosmos/cosmos-sdk v0.53.6
github.com/cosmos/gogoproto v1.7.2
github.com/cosmos/ibc-go/v10 v10.4.0
github.com/golang/protobuf v1.5.4
github.com/gorilla/mux v1.8.1
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/spf13/cast v1.10.0
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.10
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
google.golang.org/genproto/googleapis/api v0.0.0-20260427160629-7cedc36a6bc4
google.golang.org/grpc v1.80.0
google.golang.org/protobuf v1.36.11
)
require (
4d63.com/gocheckcompilerdirectives v1.3.0 // indirect
4d63.com/gochecknoglobals v0.2.2 // indirect
buf.build/gen/go/bufbuild/bufplugin/protocolbuffers/go v1.36.11-20250718181942-e35f9b667443.1 // indirect
buf.build/gen/go/bufbuild/protodescriptor/protocolbuffers/go v1.36.11-20250109164928-1da0de137947.1 // indirect
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20260415201107-50325440f8f2.1 // indirect
buf.build/gen/go/bufbuild/registry/connectrpc/go v1.19.2-20260126144947-819582968857.1 // indirect
buf.build/gen/go/bufbuild/registry/protocolbuffers/go v1.36.11-20260126144947-819582968857.1 // indirect
buf.build/gen/go/pluginrpc/pluginrpc/protocolbuffers/go v1.36.11-20241007202033-cf42259fcbfc.1 // indirect
buf.build/go/app v0.2.1-0.20260407195847-833f8f978cda // indirect
buf.build/go/bufplugin v0.10.0 // indirect
buf.build/go/bufprivateusage v0.1.0 // indirect
buf.build/go/interrupt v1.1.0 // indirect
buf.build/go/protovalidate v1.2.0 // indirect
buf.build/go/protoyaml v0.6.0 // indirect
buf.build/go/spdx v0.2.0 // indirect
buf.build/go/standard v0.1.1-0.20260325175353-2b287e071df5 // indirect
cel.dev/expr v0.25.1 // indirect
cloud.google.com/go v0.120.0 // indirect
cloud.google.com/go/auth v0.16.4 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect
cloud.google.com/go/iam v1.5.2 // indirect
cloud.google.com/go/monitoring v1.24.2 // indirect
cloud.google.com/go/storage v1.50.0 // indirect
connectrpc.com/connect v1.19.2 // indirect
connectrpc.com/otelconnect v0.9.0 // indirect
cosmossdk.io/schema v1.1.0 // indirect
cosmossdk.io/x/tx v0.14.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/4meepo/tagalign v1.4.2 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/99designs/keyring v1.2.2 // indirect
github.com/Abirdcfly/dupword v0.1.3 // indirect
github.com/Antonboom/errname v1.0.0 // indirect
github.com/Antonboom/nilnil v1.0.1 // indirect
github.com/Antonboom/testifylint v1.5.2 // indirect
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c // indirect
github.com/Crocmagnon/fatcontext v0.7.1 // indirect
github.com/DataDog/datadog-go v4.8.3+incompatible // indirect
github.com/DataDog/zstd v1.5.7 // indirect
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect
github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.1 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect
github.com/Masterminds/semver/v3 v3.3.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/alecthomas/go-check-sumtype v0.3.1 // indirect
github.com/alexkohler/nakedret/v2 v2.0.5 // indirect
github.com/alexkohler/prealloc v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect
github.com/alingse/nilnesserr v0.1.2 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/ashanbrown/forbidigo v1.6.0 // indirect
github.com/ashanbrown/makezero v1.2.0 // indirect
github.com/aws/aws-sdk-go v1.49.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bgentry/speakeasy v0.2.0 // indirect
github.com/bits-and-blooms/bitset v1.24.3 // indirect
github.com/bkielbasa/cyclop v1.2.3 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v4 v4.5.0 // indirect
github.com/breml/bidichk v0.3.2 // indirect
github.com/breml/errchkjson v0.4.0 // indirect
github.com/bufbuild/buf v1.69.0 // indirect
github.com/bufbuild/protocompile v0.14.2-0.20260429155904-12ef1ef2ce91 // indirect
github.com/bufbuild/protoplugin v0.0.0-20260414125817-25d1d281b46b // indirect
github.com/butuzov/ireturn v0.3.1 // indirect
github.com/butuzov/mirror v1.3.0 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.14.2 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/catenacyber/perfsprint v0.8.2 // indirect
github.com/ccojocar/zxcvbn-go v1.0.2 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.10 // indirect
github.com/chavacava/garif v0.1.0 // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/ckaznocha/intrange v0.3.0 // indirect
github.com/cli/browser v1.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect
github.com/cockroachdb/apd/v2 v2.0.2 // indirect
github.com/cockroachdb/errors v1.12.0 // indirect
github.com/cockroachdb/fifo v0.0.0-20240616162244-4768e80dfb9a // indirect
github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect
github.com/cockroachdb/pebble v1.1.5 // indirect
github.com/cockroachdb/redact v1.1.6 // indirect
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect
github.com/cometbft/cometbft-db v0.14.1 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.18.2 // indirect
github.com/cosmos/btcutil v1.0.5 // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
github.com/cosmos/gogogateway v1.2.0 // indirect
github.com/cosmos/iavl v1.2.2 // indirect
github.com/cosmos/ics23/go v0.11.0 // indirect
github.com/cosmos/ledger-cosmos-go v1.0.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/creachadair/atomicfile v0.3.1 // indirect
github.com/creachadair/tomledit v0.0.24 // indirect
github.com/curioswitch/go-reassign v0.3.0 // indirect
github.com/daixiang0/gci v0.13.5 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/denis-tingaikin/go-header v0.5.0 // indirect
github.com/desertbit/timer v1.0.1 // indirect
github.com/dgraph-io/badger/v4 v4.2.0 // indirect
github.com/dgraph-io/ristretto v0.2.0 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/cli v29.4.1+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.6 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/dvsekhvalnov/jose2go v1.7.0 // indirect
github.com/emicklei/dot v1.6.2 // indirect
github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect
github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect
github.com/ethereum/go-ethereum v1.15.11 // indirect
github.com/ettle/strcase v0.2.0 // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/firefart/nonamedreturns v1.0.5 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/getsentry/sentry-go v0.35.0 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/ghostiam/protogetter v0.3.9 // indirect
github.com/go-critic/go-critic v0.12.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.3 // indirect
github.com/go-kit/kit v0.13.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-toolsmith/astcast v1.1.0 // indirect
github.com/go-toolsmith/astcopy v1.1.0 // indirect
github.com/go-toolsmith/astequal v1.2.0 // indirect
github.com/go-toolsmith/astfmt v1.1.0 // indirect
github.com/go-toolsmith/astp v1.1.0 // indirect
github.com/go-toolsmith/strparse v1.1.0 // indirect
github.com/go-toolsmith/typep v1.1.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/googleapis v1.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.2.5 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/snappy v0.0.5-0.20231225225746-43d5d4cd4e0e // indirect
github.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect
github.com/golangci/go-printf-func-name v0.1.0 // indirect
github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d // indirect
github.com/golangci/golangci-lint v1.64.8 // indirect
github.com/golangci/misspell v0.6.0 // indirect
github.com/golangci/plugin-module-register v0.1.1 // indirect
github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/cel-go v0.28.0 // indirect
github.com/google/flatbuffers v24.3.25+incompatible // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-containerregistry v0.21.5 // indirect
github.com/google/orderedcode v0.0.1 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect
github.com/googleapis/gax-go/v2 v2.15.0 // indirect
github.com/gordonklaus/ineffassign v0.1.0 // indirect
github.com/gorilla/handlers v1.5.2 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
github.com/gostaticanalysis/comment v1.5.0 // indirect
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
github.com/gostaticanalysis/nilerr v0.1.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-getter v1.7.8 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
github.com/hashicorp/go-metrics v0.5.4 // indirect
github.com/hashicorp/go-plugin v1.6.3 // indirect
github.com/hashicorp/go-safetemp v1.0.0 // indirect
github.com/hashicorp/go-version v1.7.0 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hashicorp/yamux v0.1.2 // indirect
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/holiman/uint256 v1.3.2 // indirect
github.com/huandu/skiplist v1.2.1 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/improbable-eng/grpc-web v0.15.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jdx/go-netrc v1.0.0 // indirect
github.com/jgautheron/goconst v1.7.1 // indirect
github.com/jingyugao/rowserrcheck v1.1.1 // indirect
github.com/jjti/go-spancheck v0.6.4 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/julz/importas v0.2.0 // indirect
github.com/karamaru-alpha/copyloopvar v1.2.1 // indirect
github.com/kisielk/errcheck v1.9.0 // indirect
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/kulti/thelper v0.6.3 // indirect
github.com/kunwardeep/paralleltest v1.0.10 // indirect
github.com/lasiar/canonicalheader v1.1.2 // indirect
github.com/ldez/exptostd v0.4.2 // indirect
github.com/ldez/gomoddirectives v0.6.1 // indirect
github.com/ldez/grignotin v0.9.0 // indirect
github.com/ldez/tagliatelle v0.7.1 // indirect
github.com/ldez/usetesting v0.4.2 // indirect
github.com/leonklingele/grouper v1.1.2 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/linxGnu/grocksdb v1.9.2 // indirect
github.com/macabu/inamedparam v0.1.3 // indirect
github.com/manifoldco/promptui v0.9.0 // indirect
github.com/maratori/testableexamples v1.0.0 // indirect
github.com/maratori/testpackage v1.1.1 // indirect
github.com/matoous/godox v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/mdp/qrterminal/v3 v3.2.1 // indirect
github.com/mgechev/revive v1.7.0 // indirect
github.com/minio/highwayhash v1.0.3 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/moby/api v1.54.2 // indirect
github.com/moby/moby/client v0.4.1 // indirect
github.com/moricho/tparallel v0.3.2 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/nishanths/exhaustive v0.12.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.19.1 // indirect
github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/polyfloyd/go-errorlint v1.7.1 // indirect
github.com/prometheus/client_golang v1.23.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.65.0 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/quasilyte/go-ruleguard v0.4.3-0.20240823090925-0fe6f58b47b1 // indirect
github.com/quasilyte/go-ruleguard/dsl v0.3.22 // indirect
github.com/quasilyte/gogrep v0.5.0 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/raeperd/recvcheck v0.2.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/rs/cors v1.11.1 // indirect
github.com/rs/zerolog v1.34.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/ryancurrah/gomodguard v1.3.5 // indirect
github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 // indirect
github.com/sasha-s/go-deadlock v0.3.5 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.28.0 // indirect
github.com/securego/gosec/v2 v2.22.2 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/sivchari/containedctx v1.0.3 // indirect
github.com/sivchari/tenv v1.12.1 // indirect
github.com/sonatard/noctx v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/sourcegraph/go-diff v0.7.0 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.2.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect
github.com/tdakkota/asciicheck v0.4.1 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tetafro/godot v1.5.0 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/tidwall/btree v1.8.1 // indirect
github.com/timakin/bodyclose v0.0.0-20241017074812-ed6a65f985e3 // indirect
github.com/timonwong/loggercheck v0.10.1 // indirect
github.com/tomarrell/wrapcheck/v2 v2.10.0 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ulikunitz/xz v0.5.11 // indirect
github.com/ultraware/funlen v0.2.0 // indirect
github.com/ultraware/whitespace v0.2.0 // indirect
github.com/uudashr/gocognit v1.2.0 // indirect
github.com/uudashr/iface v1.3.1 // indirect
github.com/vbatts/tar-split v0.12.3 // indirect
github.com/xen0n/gosmopolitan v1.2.2 // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
github.com/yeya24/promlinter v0.3.0 // indirect
github.com/ykadowak/zerologlint v0.1.5 // indirect
github.com/zondax/golem v0.27.0 // indirect
github.com/zondax/hid v0.9.2 // indirect
github.com/zondax/ledger-go v1.0.1 // indirect
gitlab.com/bosi/decorder v0.4.2 // indirect
go-simpler.org/musttag v0.13.0 // indirect
go-simpler.org/sloglint v0.9.0 // indirect
go.etcd.io/bbolt v1.4.0-alpha.1 // indirect
go.lsp.dev/jsonrpc2 v0.10.0 // indirect
go.lsp.dev/pkg v0.0.0-20210717090340-384b27a52fb2 // indirect
go.lsp.dev/protocol v0.12.0 // indirect
go.lsp.dev/uri v0.3.0 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
go.opentelemetry.io/otel/sdk v1.43.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.uber.org/automaxprocs v1.6.0 // indirect
go.uber.org/mock v0.6.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.17.0 // indirect
golang.org/x/crypto v0.50.0 // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/exp/typeparams v0.0.0-20250210185358-939b2ce775ac // indirect
golang.org/x/mod v0.35.0 // indirect
golang.org/x/net v0.53.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa // indirect
golang.org/x/term v0.42.0 // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/time v0.12.0 // indirect
golang.org/x/tools v0.44.0 // indirect
google.golang.org/api v0.247.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools/v3 v3.5.2 // indirect
honnef.co/go/tools v0.6.1 // indirect
mvdan.cc/gofumpt v0.7.0 // indirect
mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f // indirect
mvdan.cc/xurls/v2 v2.6.0 // indirect
nhooyr.io/websocket v1.8.11 // indirect
pgregory.net/rapid v1.2.0 // indirect
pluginrpc.com/pluginrpc v0.5.0 // indirect
rsc.io/qr v0.2.0 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
)
tool (
github.com/bufbuild/buf/cmd/buf
github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar
github.com/cosmos/gogoproto/protoc-gen-gocosmos
github.com/cosmos/gogoproto/protoc-gen-gogo
github.com/golangci/golangci-lint/cmd/golangci-lint
github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
golang.org/x/tools/cmd/goimports
google.golang.org/grpc/cmd/protoc-gen-go-grpc
google.golang.org/protobuf/cmd/protoc-gen-go
)

2958
go.sum Normal file

File diff suppressed because it is too large Load diff

24
proto/buf.gen.gogo.yaml Normal file
View file

@ -0,0 +1,24 @@
# This file is auto-generated by Ignite. You can edit
# the file content but do not change the file name or path.
#
# buf.gen.gogo.yaml
#
version: v2
plugins:
- local: ["go", "tool", "github.com/cosmos/gogoproto/protoc-gen-gocosmos"]
out: .
opt:
- plugins=grpc
- Mgoogle/protobuf/any.proto=github.com/cosmos/gogoproto/types/any
- Mcosmos/orm/v1/orm.proto=cosmossdk.io/orm
- Mcosmos/app/v1alpha1/module.proto=cosmossdk.io/api/cosmos/app/v1alpha1
- local:
[
"go",
"tool",
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway",
]
out: .
opt:
- logtostderr=true
- allow_colon_final_segments=true

20
proto/buf.gen.sta.yaml Normal file
View file

@ -0,0 +1,20 @@
# This file is auto-generated by Ignite. You can edit
# the file content but do not change the file name or path.
#
# buf.gen.sta.yaml
#
version: v2
plugins:
- local:
[
"go",
"tool",
"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2",
]
out: .
opt:
- logtostderr=true
- openapi_naming_strategy=simple
- ignore_comments=true
- simple_operation_ids=false
- json_names_for_fields=false

View file

@ -0,0 +1,19 @@
# This file is auto-generated by Ignite. You can edit
# the file content but do not change the file name or path.
#
# buf.gen.swagger.yaml
#
version: v2
plugins:
- local:
[
"go",
"tool",
"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2",
]
out: .
opt:
- logtostderr=true
- openapi_naming_strategy=fqn
- json_names_for_fields=false
- generate_unbound_methods=false

18
proto/buf.gen.ts.yaml Normal file
View file

@ -0,0 +1,18 @@
# This file is auto-generated by Ignite. You can edit
# the file content but do not change the file name or path.
#
# buf.gen.ts.yaml
#
version: v2
managed:
enabled: true
plugins:
- remote: buf.build/community/stephenh-ts-proto
out: .
opt:
- logtostderr=true
- allow_merge=true
- json_names_for_fields=false
- ts_proto_opt=snakeToCamel=true
- ts_proto_opt=esModuleInterop=true
- ts_proto_out=.

View file

@ -0,0 +1,15 @@
syntax = "proto3";
package mukan.mukan.module.v1;
import "cosmos/app/v1alpha1/module.proto";
option go_package = "mukan/x/mukan/types";
// Module is the config object for the module.
message Module {
option (cosmos.app.v1alpha1.module) = {go_import: "mukan/x/mukan"};
// authority defines the custom module authority.
// If not set, defaults to the governance module.
string authority = 1;
}

View file

@ -0,0 +1,17 @@
syntax = "proto3";
package mukan.mukan.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
import "mukan/mukan/v1/params.proto";
option go_package = "mukan/x/mukan/types";
// GenesisState defines the mukan module's genesis state.
message GenesisState {
// params defines all the parameters of the module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}

View file

@ -0,0 +1,13 @@
syntax = "proto3";
package mukan.mukan.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
option go_package = "mukan/x/mukan/types";
// Params defines the parameters for the module.
message Params {
option (amino.name) = "mukan/x/mukan/Params";
option (gogoproto.equal) = true;
}

View file

@ -0,0 +1,30 @@
syntax = "proto3";
package mukan.mukan.v1;
import "amino/amino.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "mukan/mukan/v1/params.proto";
option go_package = "mukan/x/mukan/types";
// Query defines the gRPC querier service.
service Query {
// Parameters queries the parameters of the module.
rpc Params(QueryParamsRequest) returns (QueryParamsResponse) {
option (google.api.http).get = "/mukan/mukan/v1/params";
}
}
// QueryParamsRequest is request type for the Query/Params RPC method.
message QueryParamsRequest {}
// QueryParamsResponse is response type for the Query/Params RPC method.
message QueryParamsResponse {
// params holds all the parameters of this module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}

View file

@ -0,0 +1,40 @@
syntax = "proto3";
package mukan.mukan.v1;
import "amino/amino.proto";
import "cosmos/msg/v1/msg.proto";
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "mukan/mukan/v1/params.proto";
option go_package = "mukan/x/mukan/types";
// Msg defines the Msg service.
service Msg {
option (cosmos.msg.v1.service) = true;
// UpdateParams defines a (governance) operation for updating the module
// parameters. The authority defaults to the x/gov module account.
rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse);
}
// MsgUpdateParams is the Msg/UpdateParams request type.
message MsgUpdateParams {
option (cosmos.msg.v1.signer) = "authority";
option (amino.name) = "mukan/x/mukan/MsgUpdateParams";
// authority is the address that controls the module (defaults to x/gov unless overwritten).
string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
// params defines the module parameters to update.
//
// NOTE: All parameters must be supplied.
Params params = 2 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}
// MsgUpdateParamsResponse defines the response structure for executing a
// MsgUpdateParams message.
message MsgUpdateParamsResponse {}

View file

@ -0,0 +1,15 @@
syntax = "proto3";
package mukan.poj.module.v1;
import "cosmos/app/v1alpha1/module.proto";
option go_package = "mukan/x/poj/types";
// Module is the config object for the module.
message Module {
option (cosmos.app.v1alpha1.module) = {go_import: "mukan/x/poj"};
// authority defines the custom module authority.
// If not set, defaults to the governance module.
string authority = 1;
}

View file

@ -0,0 +1,20 @@
syntax = "proto3";
package mukan.poj.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
import "mukan/poj/v1/miner_state.proto";
import "mukan/poj/v1/params.proto";
option go_package = "mukan/x/poj/types";
// GenesisState defines the poj module's genesis state.
message GenesisState {
// params defines all the parameters of the module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
repeated MinerState miner_states = 2 [(gogoproto.nullable) = false];
}

View file

@ -0,0 +1,12 @@
syntax = "proto3";
package mukan.poj.v1;
option go_package = "mukan/x/poj/types";
// MinerState defines the state of a miner in the PoJ module.
message MinerState {
string address = 1;
int64 consecutive_wins = 2;
int64 streak_count = 3;
int64 cooldown_until = 4;
}

View file

@ -0,0 +1,24 @@
syntax = "proto3";
package mukan.poj.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
option go_package = "mukan/x/poj/types";
// Params defines the parameters for the module.
message Params {
option (amino.name) = "mukan/x/poj/Params";
option (gogoproto.equal) = true;
int64 blocks_per_epoch = 1;
int64 micro_cooldown = 2;
int64 macro_cooldown = 3;
int64 macro_streak_limit = 4;
int64 base_reward = 5;
int64 min_reward = 6;
uint64 mining_difficulty = 7;
string mukan_address = 8;
string erkin_address = 9;
string toruk_address = 10;
}

View file

@ -0,0 +1,57 @@
syntax = "proto3";
package mukan.poj.v1;
import "amino/amino.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "mukan/poj/v1/miner_state.proto";
import "mukan/poj/v1/params.proto";
option go_package = "mukan/x/poj/types";
// Query defines the gRPC querier service.
service Query {
// Parameters queries the parameters of the module.
rpc Params(QueryParamsRequest) returns (QueryParamsResponse) {
option (google.api.http).get = "/mukan/poj/v1/params";
}
// Queries a list of MinerState items.
rpc MinerState(QueryGetMinerStateRequest) returns (QueryGetMinerStateResponse) {
option (google.api.http).get = "/mukan/poj/v1/miner_state/{address}";
}
rpc MinerStateAll(QueryAllMinerStateRequest) returns (QueryAllMinerStateResponse) {
option (google.api.http).get = "/mukan/poj/v1/miner_state";
}
}
// QueryParamsRequest is request type for the Query/Params RPC method.
message QueryParamsRequest {}
// QueryParamsResponse is response type for the Query/Params RPC method.
message QueryParamsResponse {
// params holds all the parameters of this module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}
message QueryGetMinerStateRequest {
string address = 1;
}
message QueryGetMinerStateResponse {
MinerState miner_state = 1 [(gogoproto.nullable) = false];
}
message QueryAllMinerStateRequest {
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
message QueryAllMinerStateResponse {
repeated MinerState miner_state = 1 [(gogoproto.nullable) = false];
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}

View file

@ -0,0 +1,56 @@
syntax = "proto3";
package mukan.poj.v1;
import "amino/amino.proto";
import "cosmos/msg/v1/msg.proto";
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "mukan/poj/v1/params.proto";
option go_package = "mukan/x/poj/types";
// Msg defines the Msg service.
service Msg {
option (cosmos.msg.v1.service) = true;
// UpdateParams defines a (governance) operation for updating the module
// parameters. The authority defaults to the x/gov module account.
rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse);
// Mine defines a mining operation.
rpc Mine(MsgMine) returns (MsgMineResponse);
}
// MsgMine defines a mining message.
message MsgMine {
option (cosmos.msg.v1.signer) = "miner";
string miner = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
uint64 nonce = 2;
}
// MsgMineResponse defines the response structure for MsgMine.
message MsgMineResponse {
bool success = 1;
string reward_amount = 2;
}
// MsgUpdateParams is the Msg/UpdateParams request type.
message MsgUpdateParams {
option (cosmos.msg.v1.signer) = "authority";
option (amino.name) = "mukan/x/poj/MsgUpdateParams";
// authority is the address that controls the module (defaults to x/gov unless overwritten).
string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
// params defines the module parameters to update.
//
// NOTE: All parameters must be supplied.
Params params = 2 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}
// MsgUpdateParamsResponse defines the response structure for executing a
// MsgUpdateParams message.
message MsgUpdateParamsResponse {}

View file

@ -0,0 +1,15 @@
syntax = "proto3";
package mukan.qpos.module.v1;
import "cosmos/app/v1alpha1/module.proto";
option go_package = "mukan/x/qpos/types";
// Module is the config object for the module.
message Module {
option (cosmos.app.v1alpha1.module) = {go_import: "mukan/x/qpos"};
// authority defines the custom module authority.
// If not set, defaults to the governance module.
string authority = 1;
}

View file

@ -0,0 +1,17 @@
syntax = "proto3";
package mukan.qpos.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
import "mukan/qpos/v1/params.proto";
option go_package = "mukan/x/qpos/types";
// GenesisState defines the qpos module's genesis state.
message GenesisState {
// params defines all the parameters of the module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}

View file

@ -0,0 +1,13 @@
syntax = "proto3";
package mukan.qpos.v1;
import "amino/amino.proto";
import "gogoproto/gogo.proto";
option go_package = "mukan/x/qpos/types";
// Params defines the parameters for the module.
message Params {
option (amino.name) = "mukan/x/qpos/Params";
option (gogoproto.equal) = true;
}

View file

@ -0,0 +1,30 @@
syntax = "proto3";
package mukan.qpos.v1;
import "amino/amino.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "mukan/qpos/v1/params.proto";
option go_package = "mukan/x/qpos/types";
// Query defines the gRPC querier service.
service Query {
// Parameters queries the parameters of the module.
rpc Params(QueryParamsRequest) returns (QueryParamsResponse) {
option (google.api.http).get = "/mukan/qpos/v1/params";
}
}
// QueryParamsRequest is request type for the Query/Params RPC method.
message QueryParamsRequest {}
// QueryParamsResponse is response type for the Query/Params RPC method.
message QueryParamsResponse {
// params holds all the parameters of this module.
Params params = 1 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}

View file

@ -0,0 +1,40 @@
syntax = "proto3";
package mukan.qpos.v1;
import "amino/amino.proto";
import "cosmos/msg/v1/msg.proto";
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "mukan/qpos/v1/params.proto";
option go_package = "mukan/x/qpos/types";
// Msg defines the Msg service.
service Msg {
option (cosmos.msg.v1.service) = true;
// UpdateParams defines a (governance) operation for updating the module
// parameters. The authority defaults to the x/gov module account.
rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse);
}
// MsgUpdateParams is the Msg/UpdateParams request type.
message MsgUpdateParams {
option (cosmos.msg.v1.signer) = "authority";
option (amino.name) = "mukan/x/qpos/MsgUpdateParams";
// authority is the address that controls the module (defaults to x/gov unless overwritten).
string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
// params defines the module parameters to update.
//
// NOTE: All parameters must be supplied.
Params params = 2 [
(gogoproto.nullable) = false,
(amino.dont_omitempty) = true
];
}
// MsgUpdateParamsResponse defines the response structure for executing a
// MsgUpdateParams message.
message MsgUpdateParamsResponse {}

13
testutil/sample/sample.go Normal file
View file

@ -0,0 +1,13 @@
package sample
import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// AccAddress returns a sample account address
func AccAddress() string {
pk := ed25519.GenPrivKey().PubKey()
addr := pk.Address()
return sdk.AccAddress(addr).String()
}

25
x/mukan/keeper/genesis.go Normal file
View file

@ -0,0 +1,25 @@
package keeper
import (
"context"
"mukan/x/mukan/types"
)
// InitGenesis initializes the module's state from a provided genesis state.
func (k Keeper) InitGenesis(ctx context.Context, genState types.GenesisState) error {
return k.Params.Set(ctx, genState.Params)
}
// ExportGenesis returns the module's exported genesis.
func (k Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) {
var err error
genesis := types.DefaultGenesis()
genesis.Params, err = k.Params.Get(ctx)
if err != nil {
return nil, err
}
return genesis, nil
}

View file

@ -0,0 +1,24 @@
package keeper_test
import (
"testing"
"mukan/x/mukan/types"
"github.com/stretchr/testify/require"
)
func TestGenesis(t *testing.T) {
genesisState := types.GenesisState{
Params: types.DefaultParams(),
}
f := initFixture(t)
err := f.keeper.InitGenesis(f.ctx, genesisState)
require.NoError(t, err)
got, err := f.keeper.ExportGenesis(f.ctx)
require.NoError(t, err)
require.NotNil(t, got)
require.EqualExportedValues(t, genesisState.Params, got.Params)
}

60
x/mukan/keeper/keeper.go Normal file
View file

@ -0,0 +1,60 @@
package keeper
import (
"fmt"
"cosmossdk.io/collections"
"cosmossdk.io/core/address"
corestore "cosmossdk.io/core/store"
"github.com/cosmos/cosmos-sdk/codec"
"mukan/x/mukan/types"
)
type Keeper struct {
storeService corestore.KVStoreService
cdc codec.Codec
addressCodec address.Codec
// Address capable of executing a MsgUpdateParams message.
// Typically, this should be the x/gov module account.
authority []byte
Schema collections.Schema
Params collections.Item[types.Params]
}
func NewKeeper(
storeService corestore.KVStoreService,
cdc codec.Codec,
addressCodec address.Codec,
authority []byte,
) Keeper {
if _, err := addressCodec.BytesToString(authority); err != nil {
panic(fmt.Sprintf("invalid authority address %s: %s", authority, err))
}
sb := collections.NewSchemaBuilder(storeService)
k := Keeper{
storeService: storeService,
cdc: cdc,
addressCodec: addressCodec,
authority: authority,
Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)),
}
schema, err := sb.Build()
if err != nil {
panic(err)
}
k.Schema = schema
return k
}
// GetAuthority returns the module's authority.
func (k Keeper) GetAuthority() []byte {
return k.authority
}

View file

@ -0,0 +1,56 @@
package keeper_test
import (
"context"
"testing"
"cosmossdk.io/core/address"
storetypes "cosmossdk.io/store/types"
addresscodec "github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"mukan/x/mukan/keeper"
module "mukan/x/mukan/module"
"mukan/x/mukan/types"
)
type fixture struct {
ctx context.Context
keeper keeper.Keeper
addressCodec address.Codec
}
func initFixture(t *testing.T) *fixture {
t.Helper()
encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{})
addressCodec := addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix())
storeKey := storetypes.NewKVStoreKey(types.StoreKey)
storeService := runtime.NewKVStoreService(storeKey)
ctx := testutil.DefaultContextWithDB(t, storeKey, storetypes.NewTransientStoreKey("transient_test")).Ctx
authority := authtypes.NewModuleAddress(types.GovModuleName)
k := keeper.NewKeeper(
storeService,
encCfg.Codec,
addressCodec,
authority,
)
// Initialize params
if err := k.Params.Set(ctx, types.DefaultParams()); err != nil {
t.Fatalf("failed to set params: %v", err)
}
return &fixture{
ctx: ctx,
keeper: k,
addressCodec: addressCodec,
}
}

View file

@ -0,0 +1,17 @@
package keeper
import (
"mukan/x/mukan/types"
)
type msgServer struct {
Keeper
}
// NewMsgServerImpl returns an implementation of the MsgServer interface
// for the provided Keeper.
func NewMsgServerImpl(keeper Keeper) types.MsgServer {
return &msgServer{Keeper: keeper}
}
var _ types.MsgServer = msgServer{}

View file

@ -0,0 +1,32 @@
package keeper
import (
"bytes"
"context"
errorsmod "cosmossdk.io/errors"
"mukan/x/mukan/types"
)
func (k msgServer) UpdateParams(ctx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
authority, err := k.addressCodec.StringToBytes(req.Authority)
if err != nil {
return nil, errorsmod.Wrap(err, "invalid authority address")
}
if !bytes.Equal(k.GetAuthority(), authority) {
expectedAuthorityStr, _ := k.addressCodec.BytesToString(k.GetAuthority())
return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", expectedAuthorityStr, req.Authority)
}
if err := req.Params.Validate(); err != nil {
return nil, err
}
if err := k.Params.Set(ctx, req.Params); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{}, nil
}

View file

@ -0,0 +1,68 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
"mukan/x/mukan/keeper"
"mukan/x/mukan/types"
)
func TestMsgUpdateParams(t *testing.T) {
f := initFixture(t)
ms := keeper.NewMsgServerImpl(f.keeper)
params := types.DefaultParams()
require.NoError(t, f.keeper.Params.Set(f.ctx, params))
authorityStr, err := f.addressCodec.BytesToString(f.keeper.GetAuthority())
require.NoError(t, err)
// default params
testCases := []struct {
name string
input *types.MsgUpdateParams
expErr bool
expErrMsg string
}{
{
name: "invalid authority",
input: &types.MsgUpdateParams{
Authority: "invalid",
Params: params,
},
expErr: true,
expErrMsg: "invalid authority",
},
{
name: "send enabled param",
input: &types.MsgUpdateParams{
Authority: authorityStr,
Params: types.Params{},
},
expErr: false,
},
{
name: "all good",
input: &types.MsgUpdateParams{
Authority: authorityStr,
Params: params,
},
expErr: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, err := ms.UpdateParams(f.ctx, tc.input)
if tc.expErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.expErrMsg)
} else {
require.NoError(t, err)
}
})
}
}

17
x/mukan/keeper/query.go Normal file
View file

@ -0,0 +1,17 @@
package keeper
import (
"mukan/x/mukan/types"
)
var _ types.QueryServer = queryServer{}
// NewQueryServerImpl returns an implementation of the QueryServer interface
// for the provided Keeper.
func NewQueryServerImpl(k Keeper) types.QueryServer {
return queryServer{k}
}
type queryServer struct {
k Keeper
}

View file

@ -0,0 +1,26 @@
package keeper
import (
"context"
"errors"
"cosmossdk.io/collections"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"mukan/x/mukan/types"
)
func (q queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid request")
}
params, err := q.k.Params.Get(ctx)
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return nil, status.Error(codes.Internal, "internal error")
}
return &types.QueryParamsResponse{Params: params}, nil
}

View file

@ -0,0 +1,22 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
"mukan/x/mukan/keeper"
"mukan/x/mukan/types"
)
func TestParamsQuery(t *testing.T) {
f := initFixture(t)
qs := keeper.NewQueryServerImpl(f.keeper)
params := types.DefaultParams()
require.NoError(t, f.keeper.Params.Set(f.ctx, params))
response, err := qs.Params(f.ctx, &types.QueryParamsRequest{})
require.NoError(t, err)
require.Equal(t, &types.QueryParamsResponse{Params: params}, response)
}

33
x/mukan/module/autocli.go Normal file
View file

@ -0,0 +1,33 @@
package mukan
import (
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
"mukan/x/mukan/types"
)
// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface.
func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
return &autocliv1.ModuleOptions{
Query: &autocliv1.ServiceCommandDescriptor{
Service: types.Query_serviceDesc.ServiceName,
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "Params",
Use: "params",
Short: "Shows the parameters of the module",
},
},
},
Tx: &autocliv1.ServiceCommandDescriptor{
Service: types.Msg_serviceDesc.ServiceName,
EnhanceCustomCommand: true, // only required if you want to use the custom command
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "UpdateParams",
Skip: true, // skipped because authority gated
},
},
},
}
}

View file

@ -0,0 +1,62 @@
package mukan
import (
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
"github.com/cosmos/cosmos-sdk/codec"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"mukan/x/mukan/keeper"
"mukan/x/mukan/types"
)
var _ depinject.OnePerModuleType = AppModule{}
// IsOnePerModuleType implements the depinject.OnePerModuleType interface.
func (AppModule) IsOnePerModuleType() {}
func init() {
appconfig.Register(
&types.Module{},
appconfig.Provide(ProvideModule),
)
}
type ModuleInputs struct {
depinject.In
Config *types.Module
StoreService store.KVStoreService
Cdc codec.Codec
AddressCodec address.Codec
AuthKeeper types.AuthKeeper
BankKeeper types.BankKeeper
}
type ModuleOutputs struct {
depinject.Out
MukanKeeper keeper.Keeper
Module appmodule.AppModule
}
func ProvideModule(in ModuleInputs) ModuleOutputs {
// default to governance authority if not provided
authority := authtypes.NewModuleAddress(types.GovModuleName)
if in.Config.Authority != "" {
authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority)
}
k := keeper.NewKeeper(
in.StoreService,
in.Cdc,
in.AddressCodec,
authority,
)
m := NewAppModule(in.Cdc, k, in.AuthKeeper, in.BankKeeper)
return ModuleOutputs{MukanKeeper: k, Module: m}
}

143
x/mukan/module/module.go Normal file
View file

@ -0,0 +1,143 @@
package mukan
import (
"context"
"encoding/json"
"fmt"
"cosmossdk.io/core/appmodule"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
"mukan/x/mukan/keeper"
"mukan/x/mukan/types"
)
var (
_ module.AppModuleBasic = (*AppModule)(nil)
_ module.AppModule = (*AppModule)(nil)
_ module.HasGenesis = (*AppModule)(nil)
_ appmodule.AppModule = (*AppModule)(nil)
_ appmodule.HasBeginBlocker = (*AppModule)(nil)
_ appmodule.HasEndBlocker = (*AppModule)(nil)
)
// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement
type AppModule struct {
cdc codec.Codec
keeper keeper.Keeper
authKeeper types.AuthKeeper
bankKeeper types.BankKeeper
}
func NewAppModule(
cdc codec.Codec,
keeper keeper.Keeper,
authKeeper types.AuthKeeper,
bankKeeper types.BankKeeper,
) AppModule {
return AppModule{
cdc: cdc,
keeper: keeper,
authKeeper: authKeeper,
bankKeeper: bankKeeper,
}
}
// IsAppModule implements the appmodule.AppModule interface.
func (AppModule) IsAppModule() {}
// Name returns the name of the module as a string.
func (AppModule) Name() string {
return types.ModuleName
}
// RegisterLegacyAminoCodec registers the amino codec
func (AppModule) RegisterLegacyAminoCodec(*codec.LegacyAmino) {}
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module.
func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) {
if err := types.RegisterQueryHandlerClient(clientCtx.CmdContext, mux, types.NewQueryClient(clientCtx)); err != nil {
panic(err)
}
}
// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message.
func (AppModule) RegisterInterfaces(registrar codectypes.InterfaceRegistry) {
types.RegisterInterfaces(registrar)
}
// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries
func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error {
types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper))
types.RegisterQueryServer(registrar, keeper.NewQueryServerImpl(am.keeper))
return nil
}
// DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage.
// The default GenesisState need to be defined by the module developer and is primarily used for testing.
func (am AppModule) DefaultGenesis(codec.JSONCodec) json.RawMessage {
return am.cdc.MustMarshalJSON(types.DefaultGenesis())
}
// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form.
func (am AppModule) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error {
var genState types.GenesisState
if err := am.cdc.UnmarshalJSON(bz, &genState); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return genState.Validate()
}
// InitGenesis performs the module's genesis initialization. It returns no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, _ codec.JSONCodec, gs json.RawMessage) {
var genState types.GenesisState
// Initialize global index to index in genesis state
if err := am.cdc.UnmarshalJSON(gs, &genState); err != nil {
panic(fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err))
}
if err := am.keeper.InitGenesis(ctx, genState); err != nil {
panic(fmt.Errorf("failed to initialize %s genesis state: %w", types.ModuleName, err))
}
}
// ExportGenesis returns the module's exported genesis state as raw JSON bytes.
func (am AppModule) ExportGenesis(ctx sdk.Context, _ codec.JSONCodec) json.RawMessage {
genState, err := am.keeper.ExportGenesis(ctx)
if err != nil {
panic(fmt.Errorf("failed to export %s genesis state: %w", types.ModuleName, err))
}
bz, err := am.cdc.MarshalJSON(genState)
if err != nil {
panic(fmt.Errorf("failed to marshal %s genesis state: %w", types.ModuleName, err))
}
return bz
}
// ConsensusVersion is a sequence number for state-breaking change of the module.
// It should be incremented on each consensus-breaking change introduced by the module.
// To avoid wrong/empty versions, the initial version should be set to 1.
func (AppModule) ConsensusVersion() uint64 { return 1 }
// BeginBlock contains the logic that is automatically triggered at the beginning of each block.
// The begin block implementation is optional.
func (am AppModule) BeginBlock(_ context.Context) error {
return nil
}
// EndBlock contains the logic that is automatically triggered at the end of each block.
// The end block implementation is optional.
func (am AppModule) EndBlock(_ context.Context) error {
return nil
}

View file

@ -0,0 +1,34 @@
package mukan
import (
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"mukan/x/mukan/types"
)
// GenerateGenesisState creates a randomized GenState of the module.
func (AppModule) GenerateGenesisState(simState *module.SimulationState) {
accs := make([]string, len(simState.Accounts))
for i, acc := range simState.Accounts {
accs[i] = acc.Address.String()
}
mukanGenesis := types.GenesisState{
Params: types.DefaultParams(),
}
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&mukanGenesis)
}
// RegisterStoreDecoder registers a decoder.
func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {}
// WeightedOperations returns the all the gov module operations with their respective weights.
func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation {
operations := make([]simtypes.WeightedOperation, 0)
return operations
}
// ProposalMsgs returns msgs used for governance proposals for simulations.
func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg {
return []simtypes.WeightedProposalMsg{}
}

14
x/mukan/types/codec.go Normal file
View file

@ -0,0 +1,14 @@
package types
import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
func RegisterInterfaces(registrar codectypes.InterfaceRegistry) {
registrar.RegisterImplementations((*sdk.Msg)(nil),
&MsgUpdateParams{},
)
msgservice.RegisterMsgServiceDesc(registrar, &_Msg_serviceDesc)
}

12
x/mukan/types/errors.go Normal file
View file

@ -0,0 +1,12 @@
package types
// DONTCOVER
import (
"cosmossdk.io/errors"
)
// x/mukan module sentinel errors
var (
ErrInvalidSigner = errors.Register(ModuleName, 1100, "expected gov account as only signer for proposal message")
)

View file

@ -0,0 +1,27 @@
package types
import (
"context"
"cosmossdk.io/core/address"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// AuthKeeper defines the expected interface for the Auth module.
type AuthKeeper interface {
AddressCodec() address.Codec
GetAccount(context.Context, sdk.AccAddress) sdk.AccountI // only used for simulation
// Methods imported from account should be defined here
}
// BankKeeper defines the expected interface for the Bank module.
type BankKeeper interface {
SpendableCoins(context.Context, sdk.AccAddress) sdk.Coins
// Methods imported from bank should be defined here
}
// ParamSubspace defines the expected Subspace interface for parameters.
type ParamSubspace interface {
Get(context.Context, []byte, interface{})
Set(context.Context, []byte, interface{})
}

14
x/mukan/types/genesis.go Normal file
View file

@ -0,0 +1,14 @@
package types
// DefaultGenesis returns the default genesis state
func DefaultGenesis() *GenesisState {
return &GenesisState{
Params: DefaultParams(),
}
}
// Validate performs basic genesis state validation returning an error upon any
// failure.
func (gs GenesisState) Validate() error {
return gs.Params.Validate()
}

322
x/mukan/types/genesis.pb.go Normal file
View file

@ -0,0 +1,322 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: mukan/mukan/v1/genesis.proto
package types
import (
fmt "fmt"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// GenesisState defines the mukan module's genesis state.
type GenesisState struct {
// params defines all the parameters of the module.
Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"`
}
func (m *GenesisState) Reset() { *m = GenesisState{} }
func (m *GenesisState) String() string { return proto.CompactTextString(m) }
func (*GenesisState) ProtoMessage() {}
func (*GenesisState) Descriptor() ([]byte, []int) {
return fileDescriptor_7b4829eabece5563, []int{0}
}
func (m *GenesisState) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GenesisState) XXX_Merge(src proto.Message) {
xxx_messageInfo_GenesisState.Merge(m, src)
}
func (m *GenesisState) XXX_Size() int {
return m.Size()
}
func (m *GenesisState) XXX_DiscardUnknown() {
xxx_messageInfo_GenesisState.DiscardUnknown(m)
}
var xxx_messageInfo_GenesisState proto.InternalMessageInfo
func (m *GenesisState) GetParams() Params {
if m != nil {
return m.Params
}
return Params{}
}
func init() {
proto.RegisterType((*GenesisState)(nil), "mukan.mukan.v1.GenesisState")
}
func init() { proto.RegisterFile("mukan/mukan/v1/genesis.proto", fileDescriptor_7b4829eabece5563) }
var fileDescriptor_7b4829eabece5563 = []byte{
// 185 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xc9, 0x2d, 0xcd, 0x4e,
0xcc, 0xd3, 0x87, 0x90, 0x65, 0x86, 0xfa, 0xe9, 0xa9, 0x79, 0xa9, 0xc5, 0x99, 0xc5, 0x7a, 0x05,
0x45, 0xf9, 0x25, 0xf9, 0x42, 0x7c, 0x60, 0x71, 0x3d, 0x08, 0x59, 0x66, 0x28, 0x25, 0x98, 0x98,
0x9b, 0x99, 0x97, 0xaf, 0x0f, 0x26, 0x21, 0x4a, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x4c,
0x7d, 0x10, 0x0b, 0x2a, 0x2a, 0x8d, 0x66, 0x6c, 0x41, 0x62, 0x51, 0x62, 0x2e, 0xd4, 0x54, 0x25,
0x4f, 0x2e, 0x1e, 0x77, 0x88, 0x35, 0xc1, 0x25, 0x89, 0x25, 0xa9, 0x42, 0x96, 0x5c, 0x6c, 0x10,
0x79, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x31, 0x3d, 0x54, 0x6b, 0xf5, 0x02, 0xc0, 0xb2,
0x4e, 0x9c, 0x27, 0xee, 0xc9, 0x33, 0xac, 0x78, 0xbe, 0x41, 0x8b, 0x31, 0x08, 0xaa, 0xc1, 0x49,
0xf7, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58,
0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0x84, 0x21, 0x76, 0x57, 0x40,
0xdd, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x76, 0x80, 0x31, 0x20, 0x00, 0x00, 0xff,
0xff, 0x56, 0x6e, 0xf9, 0x59, 0xf6, 0x00, 0x00, 0x00,
}
func (m *GenesisState) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int {
offset -= sovGenesis(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *GenesisState) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Params.Size()
n += 1 + l + sovGenesis(uint64(l))
return n
}
func sovGenesis(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozGenesis(x uint64) (n int) {
return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *GenesisState) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GenesisState: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenesis(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenesis
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipGenesis(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthGenesis
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupGenesis
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthGenesis
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group")
)

View file

@ -0,0 +1,38 @@
package types_test
import (
"testing"
"mukan/x/mukan/types"
"github.com/stretchr/testify/require"
)
func TestGenesisState_Validate(t *testing.T) {
tests := []struct {
desc string
genState *types.GenesisState
valid bool
}{
{
desc: "default is valid",
genState: types.DefaultGenesis(),
valid: true,
},
{
desc: "valid genesis state",
genState: &types.GenesisState{},
valid: true,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
err := tc.genState.Validate()
if tc.valid {
require.NoError(t, err)
} else {
require.Error(t, err)
}
})
}
}

19
x/mukan/types/keys.go Normal file
View file

@ -0,0 +1,19 @@
package types
import "cosmossdk.io/collections"
const (
// ModuleName defines the module name
ModuleName = "mukan"
// StoreKey defines the primary module store key
StoreKey = ModuleName
// GovModuleName duplicates the gov module's name to avoid a dependency with x/gov.
// It should be synced with the gov module's name if it is ever changed.
// See: https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/x/gov/types/keys.go#L9
GovModuleName = "gov"
)
// ParamsKey is the prefix to retrieve all Params
var ParamsKey = collections.NewPrefix("p_mukan")

321
x/mukan/types/module.pb.go Normal file
View file

@ -0,0 +1,321 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: mukan/mukan/module/v1/module.proto
package types
import (
_ "cosmossdk.io/api/cosmos/app/v1alpha1"
fmt "fmt"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// Module is the config object for the module.
type Module struct {
// authority defines the custom module authority.
// If not set, defaults to the governance module.
Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"`
}
func (m *Module) Reset() { *m = Module{} }
func (m *Module) String() string { return proto.CompactTextString(m) }
func (*Module) ProtoMessage() {}
func (*Module) Descriptor() ([]byte, []int) {
return fileDescriptor_328c43394c9407ad, []int{0}
}
func (m *Module) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Module.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Module) XXX_Merge(src proto.Message) {
xxx_messageInfo_Module.Merge(m, src)
}
func (m *Module) XXX_Size() int {
return m.Size()
}
func (m *Module) XXX_DiscardUnknown() {
xxx_messageInfo_Module.DiscardUnknown(m)
}
var xxx_messageInfo_Module proto.InternalMessageInfo
func (m *Module) GetAuthority() string {
if m != nil {
return m.Authority
}
return ""
}
func init() {
proto.RegisterType((*Module)(nil), "mukan.mukan.module.v1.Module")
}
func init() {
proto.RegisterFile("mukan/mukan/module/v1/module.proto", fileDescriptor_328c43394c9407ad)
}
var fileDescriptor_328c43394c9407ad = []byte{
// 169 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x2d, 0xcd, 0x4e,
0xcc, 0xd3, 0x87, 0x92, 0xf9, 0x29, 0xa5, 0x39, 0xa9, 0xfa, 0x65, 0x86, 0x50, 0x96, 0x5e, 0x41,
0x51, 0x7e, 0x49, 0xbe, 0x90, 0x28, 0x58, 0x56, 0x0f, 0x4a, 0x42, 0x64, 0xca, 0x0c, 0xa5, 0x14,
0x92, 0xf3, 0x8b, 0x73, 0xf3, 0x8b, 0xf5, 0x13, 0x0b, 0x0a, 0xf4, 0xcb, 0x0c, 0x13, 0x73, 0x0a,
0x32, 0x12, 0x51, 0x35, 0x2a, 0xd9, 0x72, 0xb1, 0xf9, 0x82, 0xf9, 0x42, 0x32, 0x5c, 0x9c, 0x89,
0xa5, 0x25, 0x19, 0xf9, 0x45, 0x99, 0x25, 0x95, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x08,
0x01, 0x2b, 0xd1, 0x5d, 0x07, 0xa6, 0xdd, 0x62, 0xe4, 0xe7, 0xe2, 0x85, 0x38, 0xa3, 0x02, 0xe2,
0x1c, 0x27, 0xdd, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71,
0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x12, 0x46, 0x51,
0xa8, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0xb6, 0xd4, 0x18, 0x10, 0x00, 0x00, 0xff,
0xff, 0xa8, 0xcc, 0x4d, 0x9a, 0xd3, 0x00, 0x00, 0x00,
}
func (m *Module) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Module) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Authority) > 0 {
i -= len(m.Authority)
copy(dAtA[i:], m.Authority)
i = encodeVarintModule(dAtA, i, uint64(len(m.Authority)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintModule(dAtA []byte, offset int, v uint64) int {
offset -= sovModule(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Module) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Authority)
if l > 0 {
n += 1 + l + sovModule(uint64(l))
}
return n
}
func sovModule(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozModule(x uint64) (n int) {
return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Module) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowModule
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Module: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowModule
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthModule
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthModule
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Authority = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipModule(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthModule
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipModule(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowModule
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowModule
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowModule
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthModule
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupModule
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthModule
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowModule = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group")
)

17
x/mukan/types/params.go Normal file
View file

@ -0,0 +1,17 @@
package types
// NewParams creates a new Params instance.
func NewParams() Params {
return Params{}
}
// DefaultParams returns a default set of parameters.
func DefaultParams() Params {
return NewParams()
}
// Validate validates the set of params.
func (p Params) Validate() error {
return nil
}

287
x/mukan/types/params.pb.go Normal file
View file

@ -0,0 +1,287 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: mukan/mukan/v1/params.proto
package types
import (
fmt "fmt"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// Params defines the parameters for the module.
type Params struct {
}
func (m *Params) Reset() { *m = Params{} }
func (m *Params) String() string { return proto.CompactTextString(m) }
func (*Params) ProtoMessage() {}
func (*Params) Descriptor() ([]byte, []int) {
return fileDescriptor_ae4499392a53f5d2, []int{0}
}
func (m *Params) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Params.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Params) XXX_Merge(src proto.Message) {
xxx_messageInfo_Params.Merge(m, src)
}
func (m *Params) XXX_Size() int {
return m.Size()
}
func (m *Params) XXX_DiscardUnknown() {
xxx_messageInfo_Params.DiscardUnknown(m)
}
var xxx_messageInfo_Params proto.InternalMessageInfo
func init() {
proto.RegisterType((*Params)(nil), "mukan.mukan.v1.Params")
}
func init() { proto.RegisterFile("mukan/mukan/v1/params.proto", fileDescriptor_ae4499392a53f5d2) }
var fileDescriptor_ae4499392a53f5d2 = []byte{
// 149 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xce, 0x2d, 0xcd, 0x4e,
0xcc, 0xd3, 0x87, 0x90, 0x65, 0x86, 0xfa, 0x05, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x7a, 0x05, 0x45,
0xf9, 0x25, 0xf9, 0x42, 0x7c, 0x60, 0x61, 0x3d, 0x08, 0x59, 0x66, 0x28, 0x25, 0x98, 0x98, 0x9b,
0x99, 0x97, 0xaf, 0x0f, 0x26, 0x21, 0x4a, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x4c, 0x7d,
0x10, 0x0b, 0x22, 0xaa, 0xa4, 0xce, 0xc5, 0x16, 0x00, 0x36, 0xc8, 0x4a, 0xf6, 0xc5, 0x02, 0x79,
0xc6, 0xae, 0xe7, 0x1b, 0xb4, 0x44, 0x20, 0x56, 0x54, 0x40, 0xad, 0x82, 0x48, 0x3b, 0xe9, 0x9e,
0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31,
0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x30, 0xaa, 0xfa, 0x92, 0xca, 0x82,
0xd4, 0xe2, 0x24, 0x36, 0xb0, 0xf1, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf3, 0xc4, 0xbd,
0x83, 0xb6, 0x00, 0x00, 0x00,
}
func (this *Params) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Params)
if !ok {
that2, ok := that.(Params)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
return true
}
func (m *Params) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Params) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func encodeVarintParams(dAtA []byte, offset int, v uint64) int {
offset -= sovParams(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Params) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func sovParams(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozParams(x uint64) (n int) {
return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Params) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Params: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipParams(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthParams
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupParams
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthParams
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowParams = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group")
)

539
x/mukan/types/query.pb.go Normal file
View file

@ -0,0 +1,539 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: mukan/mukan/v1/query.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-sdk/types/query"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// QueryParamsRequest is request type for the Query/Params RPC method.
type QueryParamsRequest struct {
}
func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} }
func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) }
func (*QueryParamsRequest) ProtoMessage() {}
func (*QueryParamsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e4814f1c06fcd927, []int{0}
}
func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsRequest.Merge(m, src)
}
func (m *QueryParamsRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo
// QueryParamsResponse is response type for the Query/Params RPC method.
type QueryParamsResponse struct {
// params holds all the parameters of this module.
Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"`
}
func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} }
func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) }
func (*QueryParamsResponse) ProtoMessage() {}
func (*QueryParamsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e4814f1c06fcd927, []int{1}
}
func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsResponse.Merge(m, src)
}
func (m *QueryParamsResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo
func (m *QueryParamsResponse) GetParams() Params {
if m != nil {
return m.Params
}
return Params{}
}
func init() {
proto.RegisterType((*QueryParamsRequest)(nil), "mukan.mukan.v1.QueryParamsRequest")
proto.RegisterType((*QueryParamsResponse)(nil), "mukan.mukan.v1.QueryParamsResponse")
}
func init() { proto.RegisterFile("mukan/mukan/v1/query.proto", fileDescriptor_e4814f1c06fcd927) }
var fileDescriptor_e4814f1c06fcd927 = []byte{
// 295 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xca, 0x2d, 0xcd, 0x4e,
0xcc, 0xd3, 0x87, 0x90, 0x65, 0x86, 0xfa, 0x85, 0xa5, 0xa9, 0x45, 0x95, 0x7a, 0x05, 0x45, 0xf9,
0x25, 0xf9, 0x42, 0x7c, 0x60, 0x51, 0x3d, 0x08, 0x59, 0x66, 0x28, 0x25, 0x98, 0x98, 0x9b, 0x99,
0x97, 0xaf, 0x0f, 0x26, 0x21, 0x4a, 0xa4, 0xb4, 0x92, 0xf3, 0x8b, 0x73, 0xf3, 0x8b, 0xf5, 0x93,
0x12, 0x8b, 0x53, 0x21, 0x7a, 0xf5, 0xcb, 0x0c, 0x93, 0x52, 0x4b, 0x12, 0x0d, 0xf5, 0x0b, 0x12,
0xd3, 0x33, 0xf3, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0xa0, 0x6a, 0x45, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1,
0x4c, 0x7d, 0x10, 0x0b, 0x2a, 0x2a, 0x93, 0x9e, 0x9f, 0x9f, 0x9e, 0x93, 0xaa, 0x9f, 0x58, 0x90,
0xa9, 0x9f, 0x98, 0x97, 0x97, 0x5f, 0x02, 0xd6, 0x52, 0x0c, 0x95, 0x95, 0x46, 0x73, 0x5e, 0x41,
0x62, 0x51, 0x62, 0x2e, 0x54, 0x52, 0x49, 0x84, 0x4b, 0x28, 0x10, 0x64, 0x65, 0x00, 0x58, 0x30,
0x28, 0xb5, 0xb0, 0x34, 0xb5, 0xb8, 0x44, 0x29, 0x80, 0x4b, 0x18, 0x45, 0xb4, 0xb8, 0x20, 0x3f,
0xaf, 0x38, 0x55, 0xc8, 0x92, 0x8b, 0x0d, 0xa2, 0x59, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x48,
0x4c, 0x0f, 0xd5, 0x77, 0x7a, 0x10, 0xf5, 0x4e, 0x9c, 0x27, 0xee, 0xc9, 0x33, 0xac, 0x78, 0xbe,
0x41, 0x8b, 0x31, 0x08, 0xaa, 0xc1, 0xa8, 0x8a, 0x8b, 0x15, 0x6c, 0xa2, 0x50, 0x21, 0x17, 0x1b,
0x44, 0x95, 0x90, 0x12, 0xba, 0x6e, 0x4c, 0x87, 0x48, 0x29, 0xe3, 0x55, 0x03, 0x71, 0x96, 0x92,
0x5c, 0xd3, 0xe5, 0x27, 0x93, 0x99, 0x24, 0x84, 0xc4, 0xf4, 0xb1, 0xfa, 0xd4, 0x49, 0xf7, 0xc4,
0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1,
0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0x84, 0x21, 0x4a, 0x2b, 0xa0, 0x5a, 0x4a,
0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x21, 0x63, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xb1,
0x38, 0x79, 0x41, 0xd7, 0x01, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// QueryClient is the client API for Query service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type QueryClient interface {
// Parameters queries the parameters of the module.
Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) {
out := new(QueryParamsResponse)
err := c.cc.Invoke(ctx, "/mukan.mukan.v1.Query/Params", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
// Parameters queries the parameters of the module.
Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Params not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryParamsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Params(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/mukan.mukan.v1.Query/Params",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest))
}
return interceptor(ctx, in, info, handler)
}
var Query_serviceDesc = _Query_serviceDesc
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "mukan.mukan.v1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Params",
Handler: _Query_Params_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "mukan/mukan/v1/query.proto",
}
func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func encodeVarintQuery(dAtA []byte, offset int, v uint64) int {
offset -= sovQuery(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *QueryParamsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryParamsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Params.Size()
n += 1 + l + sovQuery(uint64(l))
return n
}
func sovQuery(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozQuery(x uint64) (n int) {
return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipQuery(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthQuery
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupQuery
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthQuery
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group")
)

View file

@ -0,0 +1,153 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: mukan/mukan/v1/query.proto
/*
Package types is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package types
import (
"context"
"io"
"net/http"
"github.com/golang/protobuf/descriptor"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = descriptor.ForMessage
var _ = metadata.Join
func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryParamsRequest
var metadata runtime.ServerMetadata
msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryParamsRequest
var metadata runtime.ServerMetadata
msg, err := server.Params(ctx, &protoReq)
return msg, metadata, err
}
// RegisterQueryHandlerServer registers the http handlers for service Query to "mux".
// UnaryRPC :call QueryServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead.
func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error {
mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterQueryHandler(ctx, mux, conn)
}
// RegisterQueryHandler registers the http handlers for service Query to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn))
}
// RegisterQueryHandlerClient registers the http handlers for service Query
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "QueryClient" to call the correct interceptors.
func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error {
mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 0, 2, 1, 2, 2}, []string{"mukan", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false)))
)
var (
forward_Query_Params_0 = runtime.ForwardResponseMessage
)

597
x/mukan/types/tx.pb.go Normal file
View file

@ -0,0 +1,597 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: mukan/mukan/v1/tx.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/types/msgservice"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// MsgUpdateParams is the Msg/UpdateParams request type.
type MsgUpdateParams struct {
// authority is the address that controls the module (defaults to x/gov unless overwritten).
Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"`
// params defines the module parameters to update.
//
// NOTE: All parameters must be supplied.
Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"`
}
func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} }
func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) }
func (*MsgUpdateParams) ProtoMessage() {}
func (*MsgUpdateParams) Descriptor() ([]byte, []int) {
return fileDescriptor_ed1d3dff0225a285, []int{0}
}
func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgUpdateParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgUpdateParams.Merge(m, src)
}
func (m *MsgUpdateParams) XXX_Size() int {
return m.Size()
}
func (m *MsgUpdateParams) XXX_DiscardUnknown() {
xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m)
}
var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo
func (m *MsgUpdateParams) GetAuthority() string {
if m != nil {
return m.Authority
}
return ""
}
func (m *MsgUpdateParams) GetParams() Params {
if m != nil {
return m.Params
}
return Params{}
}
// MsgUpdateParamsResponse defines the response structure for executing a
// MsgUpdateParams message.
type MsgUpdateParamsResponse struct {
}
func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} }
func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) }
func (*MsgUpdateParamsResponse) ProtoMessage() {}
func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_ed1d3dff0225a285, []int{1}
}
func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src)
}
func (m *MsgUpdateParamsResponse) XXX_Size() int {
return m.Size()
}
func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*MsgUpdateParams)(nil), "mukan.mukan.v1.MsgUpdateParams")
proto.RegisterType((*MsgUpdateParamsResponse)(nil), "mukan.mukan.v1.MsgUpdateParamsResponse")
}
func init() { proto.RegisterFile("mukan/mukan/v1/tx.proto", fileDescriptor_ed1d3dff0225a285) }
var fileDescriptor_ed1d3dff0225a285 = []byte{
// 319 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xcf, 0x2d, 0xcd, 0x4e,
0xcc, 0xd3, 0x87, 0x90, 0x65, 0x86, 0xfa, 0x25, 0x15, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42,
0x7c, 0x60, 0x21, 0x3d, 0x08, 0x59, 0x66, 0x28, 0x25, 0x98, 0x98, 0x9b, 0x99, 0x97, 0xaf, 0x0f,
0x26, 0x21, 0x4a, 0xa4, 0xc4, 0x93, 0xf3, 0x8b, 0x73, 0xf3, 0x8b, 0xf5, 0x73, 0x8b, 0xd3, 0x41,
0x5a, 0x73, 0x8b, 0xd3, 0xa1, 0x12, 0x92, 0x10, 0x89, 0x78, 0x30, 0x4f, 0x1f, 0xc2, 0x81, 0x4a,
0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x43, 0xc4, 0x41, 0x2c, 0xa8, 0xa8, 0x34, 0x9a, 0x2b, 0x0a, 0x12,
0x8b, 0x12, 0x73, 0xa1, 0x5a, 0x94, 0xb6, 0x31, 0x72, 0xf1, 0xfb, 0x16, 0xa7, 0x87, 0x16, 0xa4,
0x24, 0x96, 0xa4, 0x06, 0x80, 0x65, 0x84, 0xcc, 0xb8, 0x38, 0x13, 0x4b, 0x4b, 0x32, 0xf2, 0x8b,
0x32, 0x4b, 0x2a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x9d, 0x24, 0x2e, 0x6d, 0xd1, 0x15, 0x81,
0xda, 0xe5, 0x98, 0x92, 0x52, 0x94, 0x5a, 0x5c, 0x1c, 0x5c, 0x52, 0x94, 0x99, 0x97, 0x1e, 0x84,
0x50, 0x2a, 0x64, 0xc9, 0xc5, 0x06, 0x31, 0x5b, 0x82, 0x49, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x4c,
0x0f, 0xd5, 0x9b, 0x7a, 0x10, 0xf3, 0x9d, 0x38, 0x4f, 0xdc, 0x93, 0x67, 0x58, 0xf1, 0x7c, 0x83,
0x16, 0x63, 0x10, 0x54, 0x83, 0x95, 0x41, 0xd3, 0xf3, 0x0d, 0x5a, 0x08, 0xa3, 0xba, 0x9e, 0x6f,
0xd0, 0x92, 0x85, 0x38, 0xb8, 0x02, 0xea, 0x70, 0x34, 0x47, 0x2a, 0x49, 0x72, 0x89, 0xa3, 0x09,
0x05, 0xa5, 0x16, 0x17, 0xe4, 0xe7, 0x15, 0xa7, 0x1a, 0xa5, 0x71, 0x31, 0xfb, 0x16, 0xa7, 0x0b,
0x45, 0x70, 0xf1, 0xa0, 0x78, 0x4b, 0x1e, 0xdd, 0x39, 0x68, 0xfa, 0xa5, 0xd4, 0x09, 0x28, 0x80,
0x59, 0x20, 0xc5, 0xda, 0x00, 0x72, 0xbc, 0x93, 0xee, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9,
0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e,
0xcb, 0x31, 0x44, 0x09, 0xa3, 0xba, 0xbd, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0xe2,
0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x36, 0x19, 0x49, 0x9d, 0x16, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// MsgClient is the client API for Msg service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MsgClient interface {
// UpdateParams defines a (governance) operation for updating the module
// parameters. The authority defaults to the x/gov module account.
UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error)
}
type msgClient struct {
cc grpc1.ClientConn
}
func NewMsgClient(cc grpc1.ClientConn) MsgClient {
return &msgClient{cc}
}
func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) {
out := new(MsgUpdateParamsResponse)
err := c.cc.Invoke(ctx, "/mukan.mukan.v1.Msg/UpdateParams", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// MsgServer is the server API for Msg service.
type MsgServer interface {
// UpdateParams defines a (governance) operation for updating the module
// parameters. The authority defaults to the x/gov module account.
UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error)
}
// UnimplementedMsgServer can be embedded to have forward compatible implementations.
type UnimplementedMsgServer struct {
}
func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented")
}
func RegisterMsgServer(s grpc1.Server, srv MsgServer) {
s.RegisterService(&_Msg_serviceDesc, srv)
}
func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MsgUpdateParams)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MsgServer).UpdateParams(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/mukan.mukan.v1.Msg/UpdateParams",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams))
}
return interceptor(ctx, in, info, handler)
}
var Msg_serviceDesc = _Msg_serviceDesc
var _Msg_serviceDesc = grpc.ServiceDesc{
ServiceName: "mukan.mukan.v1.Msg",
HandlerType: (*MsgServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "UpdateParams",
Handler: _Msg_UpdateParams_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "mukan/mukan/v1/tx.proto",
}
func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTx(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Authority) > 0 {
i -= len(m.Authority)
copy(dAtA[i:], m.Authority)
i = encodeVarintTx(dAtA, i, uint64(len(m.Authority)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func encodeVarintTx(dAtA []byte, offset int, v uint64) int {
offset -= sovTx(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *MsgUpdateParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Authority)
if l > 0 {
n += 1 + l + sovTx(uint64(l))
}
l = m.Params.Size()
n += 1 + l + sovTx(uint64(l))
return n
}
func (m *MsgUpdateParamsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func sovTx(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozTx(x uint64) (n int) {
return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Authority = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipTx(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthTx
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupTx
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthTx
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowTx = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group")
)

1
x/mukan/types/types.go Normal file
View file

@ -0,0 +1 @@
package types

24
x/poj/client/cli/tx.go Normal file
View file

@ -0,0 +1,24 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"mukan/x/poj/types"
)
// GetTxCmd returns the transaction commands for this module
func GetTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(CmdMine())
return cmd
}

View file

@ -0,0 +1,43 @@
package cli
import (
"strconv"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/spf13/cobra"
"mukan/x/poj/types"
)
func CmdMine() *cobra.Command {
cmd := &cobra.Command{
Use: "mine [nonce]",
Short: "Submit a PoW mining solution",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
nonce, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgMine(
clientCtx.GetFromAddress().String(),
nonce,
)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}

64
x/poj/keeper/arbiter.go Normal file
View file

@ -0,0 +1,64 @@
package keeper
import (
"context"
"mukan/x/poj/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// ProcessBlockReward applies the PoJ logic (Micro/Macro Fren) for a miner.
// Returns true if the miner is allowed to receive a reward for this block.
func (k Keeper) ProcessBlockReward(ctx context.Context, minerAddr string) bool {
sdkCtx := sdk.UnwrapSDKContext(ctx)
// 0. Bootstrap check: No automatic proposer rewards in Phase 1
if k.IsBootstrapping(ctx) {
return false
}
state, found := k.GetMinerState(ctx, minerAddr)
if !found {
state = types.MinerState{
Address: minerAddr,
ConsecutiveWins: 0,
StreakCount: 0,
CooldownUntil: 0,
}
}
currentBlock := sdkCtx.BlockHeight()
params, _ := k.Params.Get(ctx)
// 1. Cooldown check
if state.CooldownUntil >= currentBlock {
// Solution rejected - no reward produced.
return false
}
// 2. Consecutive wins increment
state.ConsecutiveWins++
if state.ConsecutiveWins < 2 {
// No streak yet, award reward
k.SetMinerState(ctx, state)
return true
}
// 3. Micro Fren: 2nd consecutive win
state.StreakCount++
state.ConsecutiveWins = 0
if state.StreakCount >= params.MacroStreakLimit {
// 4. Macro Fren: 5th streak -> Big Break
state.CooldownUntil = currentBlock + params.MacroCooldown
state.StreakCount = 0 // RESET - penalty served, clean slate
} else {
// Micro Fren: 1 block wait
state.CooldownUntil = currentBlock + params.MicroCooldown
}
k.SetMinerState(ctx, state)
return true // Current block reward is given, cooldown affects the next one
}

View file

@ -0,0 +1,73 @@
package keeper_test
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"mukan/x/poj/types"
)
func TestProcessBlockReward(t *testing.T) {
f := initFixture(t)
miner := "mukan1miner"
// Initial block height 1
ctx := sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(1)
// 1st Win
allowed := f.keeper.ProcessBlockReward(ctx, miner)
require.True(t, allowed)
state, found := f.keeper.GetMinerState(ctx, miner)
require.True(t, found)
require.Equal(t, int64(1), state.ConsecutiveWins)
require.Equal(t, int64(0), state.StreakCount)
require.Equal(t, int64(0), state.CooldownUntil)
// 2nd Win (at same height or next, doesn't matter for logic, but usually next)
ctx = ctx.WithBlockHeight(2)
allowed = f.keeper.ProcessBlockReward(ctx, miner)
require.True(t, allowed)
state, _ = f.keeper.GetMinerState(ctx, miner)
require.Equal(t, int64(0), state.ConsecutiveWins)
require.Equal(t, int64(1), state.StreakCount)
require.Equal(t, int64(3), state.CooldownUntil) // current (2) + micro_cooldown (1)
// Win at block 3 (should be rejected due to cooldown)
ctx = ctx.WithBlockHeight(3)
allowed = f.keeper.ProcessBlockReward(ctx, miner)
require.False(t, allowed)
// Win at block 4 (cooldown expired)
ctx = ctx.WithBlockHeight(4)
allowed = f.keeper.ProcessBlockReward(ctx, miner)
require.True(t, allowed)
}
func TestMacroFren(t *testing.T) {
f := initFixture(t)
miner := "mukan1miner"
// Set macro limit to 2 for faster testing
params := types.DefaultParams()
params.MacroStreakLimit = 2
f.keeper.Params.Set(f.ctx, params)
// Streak 1 (wins at 1 and 2)
f.keeper.ProcessBlockReward(sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(1), miner)
f.keeper.ProcessBlockReward(sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(2), miner)
state, _ := f.keeper.GetMinerState(f.ctx, miner)
require.Equal(t, int64(1), state.StreakCount)
require.Equal(t, int64(3), state.CooldownUntil)
// Streak 2 (wins at 4 and 5)
f.keeper.ProcessBlockReward(sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(4), miner)
f.keeper.ProcessBlockReward(sdk.UnwrapSDKContext(f.ctx).WithBlockHeight(5), miner)
state, _ = f.keeper.GetMinerState(f.ctx, miner)
require.Equal(t, int64(0), state.StreakCount) // Reset after Macro
require.Equal(t, int64(10), state.CooldownUntil) // 5 + 5 (macro_cooldown)
}

33
x/poj/keeper/emission.go Normal file
View file

@ -0,0 +1,33 @@
package keeper
import (
"context"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// GetBlockReward calculates the block reward based on the current epoch.
func (k Keeper) GetBlockReward(ctx context.Context) sdk.Coin {
sdkCtx := sdk.UnwrapSDKContext(ctx)
currentBlock := sdkCtx.BlockHeight()
params, _ := k.Params.Get(ctx)
// Calculate epoch
// Each epoch has blocks_per_epoch (default 525,600)
epoch := currentBlock / params.BlocksPerEpoch
// Reward drops 10x every epoch
baseReward := sdkmath.NewInt(params.BaseReward)
minReward := sdkmath.NewInt(params.MinReward)
for i := int64(0); i < epoch; i++ {
baseReward = baseReward.Quo(sdkmath.NewInt(10))
if baseReward.LT(minReward) {
baseReward = minReward
break
}
}
return sdk.NewCoin("umc", baseReward)
}

25
x/poj/keeper/genesis.go Normal file
View file

@ -0,0 +1,25 @@
package keeper
import (
"context"
"mukan/x/poj/types"
)
// InitGenesis initializes the module's state from a provided genesis state.
func (k Keeper) InitGenesis(ctx context.Context, genState types.GenesisState) error {
return k.Params.Set(ctx, genState.Params)
}
// ExportGenesis returns the module's exported genesis.
func (k Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) {
var err error
genesis := types.DefaultGenesis()
genesis.Params, err = k.Params.Get(ctx)
if err != nil {
return nil, err
}
return genesis, nil
}

View file

@ -0,0 +1,24 @@
package keeper_test
import (
"testing"
"mukan/x/poj/types"
"github.com/stretchr/testify/require"
)
func TestGenesis(t *testing.T) {
genesisState := types.GenesisState{
Params: types.DefaultParams(),
}
f := initFixture(t)
err := f.keeper.InitGenesis(f.ctx, genesisState)
require.NoError(t, err)
got, err := f.keeper.ExportGenesis(f.ctx)
require.NoError(t, err)
require.NotNil(t, got)
require.EqualExportedValues(t, genesisState.Params, got.Params)
}

91
x/poj/keeper/keeper.go Normal file
View file

@ -0,0 +1,91 @@
package keeper
import (
"fmt"
"cosmossdk.io/collections"
"cosmossdk.io/core/address"
corestore "cosmossdk.io/core/store"
"github.com/cosmos/cosmos-sdk/codec"
"mukan/x/poj/types"
)
type Keeper struct {
storeService corestore.KVStoreService
cdc codec.Codec
addressCodec address.Codec
// Address capable of executing a MsgUpdateParams message.
// Typically, this should be the x/gov module account.
authority []byte
Schema collections.Schema
Params collections.Item[types.Params]
MinerStates collections.Map[string, types.MinerState]
BlockWinners collections.Map[int64, string]
bankKeeper types.BankKeeper
authKeeper types.AuthKeeper
stakingKeeper types.StakingKeeper
}
func NewKeeper(
storeService corestore.KVStoreService,
cdc codec.Codec,
addressCodec address.Codec,
authority []byte,
bankKeeper types.BankKeeper,
authKeeper types.AuthKeeper,
stakingKeeper types.StakingKeeper,
) Keeper {
if _, err := addressCodec.BytesToString(authority); err != nil {
panic(fmt.Sprintf("invalid authority address %s: %s", authority, err))
}
sb := collections.NewSchemaBuilder(storeService)
k := Keeper{
storeService: storeService,
cdc: cdc,
addressCodec: addressCodec,
authority: authority,
bankKeeper: bankKeeper,
authKeeper: authKeeper,
stakingKeeper: stakingKeeper,
Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)),
MinerStates: collections.NewMap(
sb,
types.MinerStateKeyPrefix,
"miner_states",
collections.StringKey,
codec.CollValue[types.MinerState](cdc),
),
BlockWinners: collections.NewMap(
sb,
types.BlockWinnerKeyPrefix,
"block_winners",
collections.Int64Key,
collections.StringValue,
),
}
schema, err := sb.Build()
if err != nil {
panic(err)
}
k.Schema = schema
return k
}
// GetAuthority returns the module's authority.
func (k Keeper) GetAuthority() []byte {
return k.authority
}
// GetAddressCodec returns the module's address codec.
func (k Keeper) GetAddressCodec() address.Codec {
return k.addressCodec
}

View file

@ -0,0 +1,58 @@
package keeper_test
import (
"context"
"testing"
"cosmossdk.io/core/address"
storetypes "cosmossdk.io/store/types"
addresscodec "github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"mukan/x/poj/keeper"
module "mukan/x/poj/module"
"mukan/x/poj/types"
)
type fixture struct {
ctx context.Context
keeper keeper.Keeper
addressCodec address.Codec
}
func initFixture(t *testing.T) *fixture {
t.Helper()
encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{})
addressCodec := addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix())
storeKey := storetypes.NewKVStoreKey(types.StoreKey)
storeService := runtime.NewKVStoreService(storeKey)
ctx := testutil.DefaultContextWithDB(t, storeKey, storetypes.NewTransientStoreKey("transient_test")).Ctx
authority := authtypes.NewModuleAddress(types.GovModuleName)
k := keeper.NewKeeper(
storeService,
encCfg.Codec,
addressCodec,
authority,
nil,
nil,
)
// Initialize params
if err := k.Params.Set(ctx, types.DefaultParams()); err != nil {
t.Fatalf("failed to set params: %v", err)
}
return &fixture{
ctx: ctx,
keeper: k,
addressCodec: addressCodec,
}
}

32
x/poj/keeper/logic.go Normal file
View file

@ -0,0 +1,32 @@
package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
"mukan/x/poj/types"
)
func (k Keeper) IsBootstrapping(ctx context.Context) bool {
sdkCtx := sdk.UnwrapSDKContext(ctx)
supply := k.bankKeeper.GetSupply(sdkCtx, "umc").Amount.Int64()
return supply < 100000000000
}
func (k Keeper) GetBankKeeper() types.BankKeeper {
return k.bankKeeper
}
func (k Keeper) GetParams(ctx context.Context) types.Params {
params, _ := k.Params.Get(ctx)
return params
}
func (k Keeper) HasBlockWinner(ctx context.Context, height int64) bool {
has, _ := k.BlockWinners.Has(ctx, height)
return has
}
func (k Keeper) SetBlockWinner(ctx context.Context, height int64, miner string) {
k.BlockWinners.Set(ctx, height, miner)
}

View file

@ -0,0 +1,44 @@
package keeper
import (
"context"
"mukan/x/poj/types"
)
// SetMinerState sets a specific minerState in the store
func (k Keeper) SetMinerState(ctx context.Context, state types.MinerState) {
k.MinerStates.Set(ctx, state.Address, state)
}
// GetMinerState returns a minerState from its address
func (k Keeper) GetMinerState(ctx context.Context, address string) (val types.MinerState, found bool) {
state, err := k.MinerStates.Get(ctx, address)
if err != nil {
return types.MinerState{Address: address}, false
}
return state, true
}
// RemoveMinerState removes a minerState from the store
func (k Keeper) RemoveMinerState(ctx context.Context, address string) {
k.MinerStates.Remove(ctx, address)
}
// GetAllMinerState returns all minerState
func (k Keeper) GetAllMinerState(ctx context.Context) (list []types.MinerState) {
iter, err := k.MinerStates.Iterate(ctx, nil)
if err != nil {
return
}
defer iter.Close()
for ; iter.Valid(); iter.Next() {
val, err := iter.Value()
if err != nil {
continue
}
list = append(list, val)
}
return
}

View file

@ -0,0 +1,17 @@
package keeper
import (
"mukan/x/poj/types"
)
type msgServer struct {
Keeper
}
// NewMsgServerImpl returns an implementation of the MsgServer interface
// for the provided Keeper.
func NewMsgServerImpl(keeper Keeper) types.MsgServer {
return &msgServer{Keeper: keeper}
}
var _ types.MsgServer = msgServer{}

View file

@ -0,0 +1,95 @@
package keeper
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"mukan/x/poj/types"
)
func (k msgServer) Mine(goCtx context.Context, msg *types.MsgMine) (*types.MsgMineResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
// 1. Verify Miner Address
minerAddr, err := sdk.AccAddressFromBech32(msg.Miner)
if err != nil {
return nil, err
}
// 2. Block Winner Check: Has someone already won this block?
// We use a simple store key to track the winner of the current height.
hasWinner := k.HasBlockWinner(ctx, ctx.BlockHeight())
if hasWinner {
return nil, fmt.Errorf("block %d already has a winner", ctx.BlockHeight())
}
// 3. PoJ Check: Is the miner in cooldown?
minerState, found := k.GetMinerState(ctx, msg.Miner)
if found && minerState.CooldownUntil > ctx.BlockHeight() {
// IN THE SAFU MODEL: If the first miner is in cooldown, we REJECT them
// and leave the 'winner' slot empty for the next valid miner in this block.
return nil, fmt.Errorf("miner %s is in cooldown, skipping to next candidate", msg.Miner)
}
// 4. PoW Verification
params := k.GetParams(ctx)
lastBlockHash := ctx.BlockHeader().LastBlockId.Hash
// Data to hash: MinerAddress + Nonce + LastBlockHash
data := fmt.Sprintf("%s%d%x", msg.Miner, msg.Nonce, lastBlockHash)
hash := sha256.Sum256([]byte(data))
hashStr := hex.EncodeToString(hash[:])
// Check for leading zeros (Difficulty)
requiredPrefix := strings.Repeat("0", int(params.MiningDifficulty))
if !strings.HasPrefix(hashStr, requiredPrefix) {
return &types.MsgMineResponse{Success: false}, fmt.Errorf("invalid hash for difficulty %d", params.MiningDifficulty)
}
// 5. Mark Winner immediately to prevent double-wins in the same block
k.SetBlockWinner(ctx, ctx.BlockHeight(), msg.Miner)
// 6. Reward Calculation
reward := k.GetBlockReward(ctx)
// 5. Mint and Send Reward
err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(reward))
if err != nil {
return nil, err
}
err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, minerAddr, sdk.NewCoins(reward))
if err != nil {
return nil, err
}
// 6. Update Miner State (PoJ logic)
// We increment consecutive wins and apply cooldown if needed.
if !found {
minerState = types.MinerState{
Address: msg.Miner,
}
}
minerState.ConsecutiveWins++
if minerState.ConsecutiveWins >= 2 { // Mikro Fren: 2 wins = 1 block cooldown
minerState.CooldownUntil = ctx.BlockHeight() + params.MicroCooldown + 1
minerState.ConsecutiveWins = 0
minerState.StreakCount++
}
if minerState.StreakCount >= params.MacroStreakLimit { // Makro Fren
minerState.CooldownUntil = ctx.BlockHeight() + params.MacroCooldown + 1
minerState.StreakCount = 0
}
k.SetMinerState(ctx, minerState)
return &types.MsgMineResponse{
Success: true,
RewardAmount: reward.String(),
}, nil
}

View file

@ -0,0 +1,32 @@
package keeper
import (
"bytes"
"context"
errorsmod "cosmossdk.io/errors"
"mukan/x/poj/types"
)
func (k msgServer) UpdateParams(ctx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
authority, err := k.addressCodec.StringToBytes(req.Authority)
if err != nil {
return nil, errorsmod.Wrap(err, "invalid authority address")
}
if !bytes.Equal(k.GetAuthority(), authority) {
expectedAuthorityStr, _ := k.addressCodec.BytesToString(k.GetAuthority())
return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", expectedAuthorityStr, req.Authority)
}
if err := req.Params.Validate(); err != nil {
return nil, err
}
if err := k.Params.Set(ctx, req.Params); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{}, nil
}

View file

@ -0,0 +1,68 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
"mukan/x/poj/keeper"
"mukan/x/poj/types"
)
func TestMsgUpdateParams(t *testing.T) {
f := initFixture(t)
ms := keeper.NewMsgServerImpl(f.keeper)
params := types.DefaultParams()
require.NoError(t, f.keeper.Params.Set(f.ctx, params))
authorityStr, err := f.addressCodec.BytesToString(f.keeper.GetAuthority())
require.NoError(t, err)
// default params
testCases := []struct {
name string
input *types.MsgUpdateParams
expErr bool
expErrMsg string
}{
{
name: "invalid authority",
input: &types.MsgUpdateParams{
Authority: "invalid",
Params: params,
},
expErr: true,
expErrMsg: "invalid authority",
},
{
name: "send enabled param",
input: &types.MsgUpdateParams{
Authority: authorityStr,
Params: types.Params{},
},
expErr: false,
},
{
name: "all good",
input: &types.MsgUpdateParams{
Authority: authorityStr,
Params: params,
},
expErr: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, err := ms.UpdateParams(f.ctx, tc.input)
if tc.expErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.expErrMsg)
} else {
require.NoError(t, err)
}
})
}
}

17
x/poj/keeper/query.go Normal file
View file

@ -0,0 +1,17 @@
package keeper
import (
"mukan/x/poj/types"
)
var _ types.QueryServer = queryServer{}
// NewQueryServerImpl returns an implementation of the QueryServer interface
// for the provided Keeper.
func NewQueryServerImpl(k Keeper) types.QueryServer {
return queryServer{k}
}
type queryServer struct {
k Keeper
}

View file

@ -0,0 +1,39 @@
package keeper
import (
"context"
"github.com/cosmos/cosmos-sdk/types/query"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"mukan/x/poj/types"
)
func (q queryServer) MinerState(ctx context.Context, req *types.QueryGetMinerStateRequest) (*types.QueryGetMinerStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid request")
}
val, found := q.k.GetMinerState(ctx, req.Address)
if !found {
return nil, status.Error(codes.NotFound, "not found")
}
return &types.QueryGetMinerStateResponse{MinerState: val}, nil
}
func (q queryServer) MinerStateAll(ctx context.Context, req *types.QueryAllMinerStateRequest) (*types.QueryAllMinerStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid request")
}
minerStates, pageRes, err := query.CollectionPaginate(ctx, q.k.MinerStates, req.Pagination, func(key string, value types.MinerState) (types.MinerState, error) {
return value, nil
})
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryAllMinerStateResponse{MinerState: minerStates, Pagination: pageRes}, nil
}

View file

@ -0,0 +1,26 @@
package keeper
import (
"context"
"errors"
"cosmossdk.io/collections"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"mukan/x/poj/types"
)
func (q queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid request")
}
params, err := q.k.Params.Get(ctx)
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return nil, status.Error(codes.Internal, "internal error")
}
return &types.QueryParamsResponse{Params: params}, nil
}

View file

@ -0,0 +1,22 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
"mukan/x/poj/keeper"
"mukan/x/poj/types"
)
func TestParamsQuery(t *testing.T) {
f := initFixture(t)
qs := keeper.NewQueryServerImpl(f.keeper)
params := types.DefaultParams()
require.NoError(t, f.keeper.Params.Set(f.ctx, params))
response, err := qs.Params(f.ctx, &types.QueryParamsRequest{})
require.NoError(t, err)
require.Equal(t, &types.QueryParamsResponse{Params: params}, response)
}

33
x/poj/module/autocli.go Normal file
View file

@ -0,0 +1,33 @@
package poj
import (
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
"mukan/x/poj/types"
)
// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface.
func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
return &autocliv1.ModuleOptions{
Query: &autocliv1.ServiceCommandDescriptor{
Service: types.Query_serviceDesc.ServiceName,
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "Params",
Use: "params",
Short: "Shows the parameters of the module",
},
},
},
Tx: &autocliv1.ServiceCommandDescriptor{
Service: types.Msg_serviceDesc.ServiceName,
EnhanceCustomCommand: true, // only required if you want to use the custom command
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "UpdateParams",
Skip: true, // skipped because authority gated
},
},
},
}
}

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