commit 2e61688eb3b5b13e9d32f4051a29b9ae46d4614c Author: loki5512344 Date: Fri Nov 13 12:28:48 2026 +0100 Initial import: ICE-NET research docs and Rust workspace (v0.4) - Rust workspace: 7 library crates, icenetd CLI, icenet-city (Slint GUI) - Sim: fix false Delivered after a route cut, derive traffic class from payload size, per-link airtime slots (link capacity, queueing) - Docs: single docs/STATUS.md for all figures, remove v0.2/egui leftovers, drop unimplemented seed claims, uncheck store-and-forward - License: LGPL-3.0-or-later (LICENSE, LICENSES/GPL-3.0.txt) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b476bdb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: rust-ci +on: + push: + pull_request: +jobs: + checks: + runs-on: ubuntu-latest + defaults: + run: + working-directory: workspace + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: '1.95.0' + components: rustfmt, clippy + - run: python3 tools/check_layout.py + - run: cargo fmt --all -- --check + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo test --workspace diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/LICENSES/GPL-3.0.txt b/LICENSES/GPL-3.0.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSES/GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..527cdbb --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# ICE-NET · Research + Rust Workspace · v0.4 + +> **Статус: архитектура + стартовый код для локальных экспериментов.** Не развёрнутый +> сетевой протокол, не готовая криптосистема и не проверенная RF-симуляция. +> Срез исследования: **13 ноября 2026 года**. Язык документации: русский; +> публичные Rust API и технические комментарии — на английском. +> Актуальные цифры и состояние: [docs/STATUS.md](docs/STATUS.md). + +> **Вдохновение.** Идея вдохновлена «Сетью» (the Net) из киберпанка — образом +> глобальной сети поверх разнородных каналов и устройств, которая не принадлежит +> одной корпорации. Это художественное вдохновение: проект не связан с +> правообладателями киберпанк-произведений и ничего из них не воспроизводит. + +Репозиторий: +Лицензия: **LGPL-3.0-or-later** — см. [LICENSE](LICENSE) и [LICENSES/](LICENSES/GPL-3.0.txt). + +ICE-NET — проект независимой сети: идентичность устройства отдельно от транспорта, +медленные радиоканалы преимущественно для объявления доступности и малых сообщений, +большие данные — только по подходящим быстрым каналам, при отсутствии пути — очередь. + +## 🧭 Путь чтения + +1. [Статус: что проверено и что нет](docs/STATUS.md) и [TODO: план по этапам](TODO.md) — **начни здесь**. + **[Полный кликабельный индекс всех Markdown-файлов](docs/INDEX.md).** +2. [Правила разработки и ограничение 250/4](RULES.md). +3. [Аудит зависимостей](docs/build/dependencies.md) и [лицензия Slint](docs/build/slint_license.md). +4. [Архитектура](docs/architecture/overview.md) и [граф зависимостей крейтов](docs/architecture/crates.md). +5. [Интерактивная модель города](docs/simulator/city_editor.md) и [сценарии](docs/simulator/scenarios.md). +6. [Исследование Reticulum](docs/research/reticulum.md), [Meshtastic](docs/research/meshtastic.md), + [наш пробел/гипотеза](docs/research/gaps.md), [лицензии](docs/research/licensing.md). +7. [Руководство Arch Linux](docs/guides/quickstart.md), [команды CI](docs/guides/testing.md). +8. [Ревизия 0.1 → 0.3](docs/review/revision.md) и [открытые решения](docs/review/questions.md). +9. [Архив всех исходных Markdown](archive/README.md), [ссылки исследований](docs/SOURCES.md). + +## Каталоги + +| Путь | Роль | +| --- | --- | +| `workspace/crates/` | библиотеки на Rust без зависимости от GUI | +| `workspace/apps/icenet-city/` | нативный визуальный городской эмулятор (Slint 1.18.1, software rendering) | +| `workspace/apps/icenetd/` | CLI (`route`/`send`/`sim`/`policy`/`wire`, UDP `serve`/`send-udp`); daemon позже | +| `workspace/tools/` | автоматическая проверка структуры 250/4 и тестов | +| `docs/` | актуальные решения, симулятор, безопасность, исследования | +| `archive/` | полный исходный исследовательский пакет 0.1, не выброшен | + +## Минимальный путь без железа + +```bash +cd workspace +python3 tools/check_layout.py +cargo fmt --all -- --check +cargo test -p icenet-sim -p icenet-routing +cargo run -p icenet-city +``` + +Что именно проверено (тесты, fmt, clippy, замеры) и что **не** проверено — только в +[docs/STATUS.md](docs/STATUS.md). + +## Что специально НЕ обещаем + +- Глобальное покрытие, бесплатные вышки или «высокую скорость по LoRa». +- Совместимость с Reticulum/Meshtastic на уровне wire-протоколов. +- Подтверждённую безопасность: исходные криптографические примитивы пока **не реализованы**. +- Что модель города физически достоверно предсказывает радиопокрытие. +- Что ICE-NET уже лучше существующих решений: это проверяемая гипотеза. + +## Зависимости + +- Core-библиотеки: **0 внешних crates** (7 внутренних крейтов — границы проекта). +- GUI: `slint` + `slint-build` (build-time), версия и число записей lock — в [STATUS](docs/STATUS.md). +- `default-features = false` не гарантирует меньше транзитивных зависимостей. + +Подробности и контрольный список: [dependencies.md](docs/build/dependencies.md). diff --git a/RULES.md b/RULES.md new file mode 100644 index 0000000..f379cab --- /dev/null +++ b/RULES.md @@ -0,0 +1,71 @@ +# Правила репозитория ICE-NET · обязательные + +## Структура и ограничения + +1. **Не более 250 физических строк на любой авторский текстовый файл**, включая MD, Rust, Slint, TOML, Python, YAML. +2. **Не более 4 авторских файлов непосредственно в одном каталоге** (подкаталоги отдельно). Сгенерированный `Cargo.lock`, `.gitignore` и системный `.DS_Store` не учитываются при подсчёте; на исходники и `.slint` это исключение не действует. +3. Если модуль вырос — делить по ответственности, **не** сжимать код в одну строку. +4. Не размещать тесты в `src/` через `#[cfg(test)]`: unit-like и integration tests — отдельные `tests/*.rs`. +5. Не создавать crate ради каждого типа; новая граница crate требует независимой ответственности и односторонних зависимостей. +6. `workspace/tools/check_layout.py` проверяет лимиты для `.rs`, `.slint`, `.md` и конфигурации. Не обходить скрипт переименованием файла. +7. Исключение: дословные тексты лицензий (`LICENSE`, `LICENSES/`) — не авторские файлы; не править и не сокращать. + +## Documentation & comments (English) + +- Public crates: `//! Module or crate description.` +- Public types, traits, methods: `/// Summary.` — **rustdoc** (Rust-аналог JavaDoc). +- Для нетривиальных API применять секции `# Arguments`, `# Returns`, `# Errors`, `# Panics`, `# Examples`, `# Safety` где уместно. +- Комментарии внутри исходников — **English**, поясняют *почему*, а не буквально *что* делает строка. +- Текст документации в `docs/` и issue допускается на русском. + +```rust +/// Finds a route that satisfies the traffic class policy. +/// +/// # Arguments +/// - `class`: The traffic class to schedule. +/// +/// # Returns +/// A route, or `None` when no eligible path exists. +/// +/// # Errors +/// This operation currently does not return I/O errors. +pub fn find_route(class: TrafficClass) -> Option { /* example */ None } +``` + +## Архитектурные принципы + +- **KISS:** сначала простейшая проверяемая реализация; избегать преждевременного async/actor/DI-фреймворка. +- **DRY:** общая логика живёт в одном crate; не превращать каждый похожий `match` в абстракцию. +- **SOLID:** маленькие интерфейсы (`Transport`, `RoutePlanner`), разделение политик и механики, инверсия зависимостей на границе с железом. +- **Hexagonal architecture:** UI и сеть — адаптеры; алгоритмы **не** импортируют GUI и операционную систему. +- Детерминированность симулятора: фиксированные seed, стабильный порядок событий, симулированное время. +- Одна ответственность на модуль; публичный API минимальный; ошибки типизированные, не `panic` на входных пакетах. + +## Код, качество, безопасность + +- Rust Edition 2024, `resolver = "3"`; версия инструмента согласуется с версиями GUI. +- Не применять `unsafe` без ADR + ревью; `unwrap()` в обработке входных данных запрещён. +- Запретить секреты, токены, приватные ключи и реальные данные пользователей в git/фикстурах. +- Test Pyramid: проверка инвариантов → integration → сценарии города → hardware-in-the-loop. +- Криптографическая «угроза» от ICE: только **локально разрешить/отказать/ограничить/залогировать**; никаких ответных атак. +- Code review по контрактам, тестам, потреблению RAM/airtime, privacy и зависимости. + +## Definition of Done для PR + +- [ ] Лимиты 250/4, rustdoc на новых публичных API, тесты в `tests/`. +- [ ] `cargo fmt`, `cargo clippy`, `cargo test` без ошибок. +- [ ] Указано, какие сценарии покрыты, какие риски и какие измерения получены. +- [ ] Не заявлена совместимость/безопасность без тестов, лицензия зависимостей проверена. + +## Внешние зависимости (MVP) + +- Библиотечные крейты по умолчанию работают **без crates.io-зависимостей**. +- Каждая новая зависимость требует краткого обоснования: функция, лицензия, MSRV, + транситивные зависимости, поддержка, альтернатива на std. +- GUI-зависимости только в `apps/icenet-city`, никогда в `icenet-core`/`icenet-sim`. +- Для Slint выключены defaults: без Qt, Skia, WGPU, webview, tokio или serde. +- `slint-build` нужен только для компиляции `.slint` в `build.rs`. +- В версии 0.3 GUI: Slint 1.18.1, software renderer и Winit (desktop Linux). +- Поставляемые программы требуют проверки лицензий, особенно Slint. +- Лицензия собственного кода: **LGPL-3.0-or-later** (`license` в `workspace/Cargo.toml`; каждый crate наследует её). Код других проектов с несовместимой лицензией не копировать. +- После обновления GUI **перегенерировать и закоммитить новый `Cargo.lock`**. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..933a599 --- /dev/null +++ b/TODO.md @@ -0,0 +1,94 @@ +# TODO · план ICE-NET (v0.4) + +> Отмечай только после **измеренного результата**. Этап не считается готовым по факту написания документа. +> Приоритет: P0 — обязательно, P1 — после первого прототипа, P2 — позже. +> Числа и результаты проверок — только в [docs/STATUS.md](docs/STATUS.md). + +## P0 · подготовка и изучение (Этап 0) + +- [ ] Прочитать [Reticulum manual](https://reticulum.network/manual/) и проверить его текущие QoS, discoverable interfaces, blackhole и transport modes. +- [ ] На Arch поднять 2 локальных Reticulum-инстанса, провести обмен текстом и файлом; записать команды, задержки и неожиданности. +- [ ] Проверить Meshtastic **без покупки радио** по документации и доступным симуляторам/эмуляторам; позже протестировать 2 платы. +- [ ] Сформулировать **один измеримый разрыв** относительно Reticulum/Meshtastic; пока гипотеза: политика data/control path selection. +- [ ] Оформить ADR: строим свой wire-протокол или слой политики/плагин поверх готового стека. +- [ ] Не копировать исходники Reticulum до правового анализа его **нестандартной лицензии**. + +## P0 · Slint и контроль зависимостей (v0.3) + +- [x] Удалить прямой `egui/eframe` и вынести декларативную UI в `.slint`. +- [x] Выключить default-features Slint; включить только Winit + software renderer. +- [x] Оставить все базовые библиотеки без внешних crates.io-зависимостей. +- [x] Добавить отдельные state-тесты без графического backend. +- [x] Исправить конфликт 4 файла vs `Cargo.lock` в `check_layout.py`. +- [x] **На Arch собрать Slint 1.18.1** (результаты проверок — в STATUS). +- [ ] Замерить RSS и холодный старт Slint GUI в release (сравнение с egui снято: старого проекта нет). +- [x] Сгенерировать новый `Cargo.lock`; старый `Cargo.lock` с egui **не использовать**. +- [x] `cargo fmt`, `cargo clippy`, `cargo test` на Slint-сборке. +- [x] Вручную проверить перетаскивание точек, линии и элементы боковой панели (X11/Xvfb + XTest). +- [ ] Уточнить режим распространения ПО и выполнить обязательства лицензии Slint. + +## P0 · Rust workspace и правила + +- [x] Установить `rustup`, Rust toolchain, `rustfmt`, `clippy` и `python3` на Arch. +- [x] `python3 workspace/tools/check_layout.py` проходит без исключений. +- [x] `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`. +- [x] `cargo test --workspace`, включая отдельные файлы в `tests/`. +- [x] Все публичные API документированы в rustdoc на английском, без JavaDoc-синтаксиса `/** */`. +- [x] Зафиксировать **новый** Cargo.lock после разрешения Slint-графа для GUI/daemon. + +## P0 · интерактивный город (M0) + +- [x] Запустить `cargo run -p icenet-city` и проверить создание/отключение линков. +- [x] Визуально выбрать отправителя и получателя, послать Text и Photo. +- [x] Проверить: Photo **никогда** не выбирает slow-only маршрут. +- [x] Проверить: Text может пройти через slow radio, если другого пути нет. +- [x] Отключить транзитный узел, убедиться в QUEUED/NO_ROUTE и повторной попытке. +- [x] Одинаковый сценарий и действия → байт-в-байт одинаковые CSV/JSON. +- [ ] Seeded случайные отказы линков/узлов. **`seed` не реализован**; детерминизм сейчас обеспечен отсутствием случайности. +- [x] Добавить экспорт JSON сценария/CSV метрик. + +## P0 · CLI без GUI (headless) + +- [x] `icenetd route` — путь/NO_ROUTE по demo-топологии и отключённым линкам. +- [x] `icenetd send` — статусы Delivered/Queued/Expired с TTL и виртуальным временем. +- [x] `icenetd sim` — детерминированный сценарий + экспорт CSV/JSON. +- [x] `icenetd policy` — Permit/Deny с причиной (ACL, размер, authenticated). +- [x] `icenetd wire-encode/wire-decode` — roundtrip чернового кадра. +- [x] CLI integration tests запускают реальный бинарник. +- [x] `icenetd serve`/`send-udp` поверх UDP adapter (сеть, без GUI). + +## P1 · инженерные измерения и безопасность + +- [ ] 100/1000 узлов, p50/p95 поиска маршрута, delivery ratio, control airtime, RAM. + Частично, цифры — в STATUS. RAM на 1000 узлов и release-замеры — позже. +- [x] Исправить ложный `DELIVERED` при обрыве маршрута до крупного шага времени (регрессионные тесты). +- [x] Класс трафика выводится из размера (Control ≤ 256 Б, Text ≤ 4096 Б, иначе Bulk). +- [x] Ёмкость линка: слоты эфира, очередь на ребре, `slow_radio_airtime_ms`. +- [ ] Генератор служебного (announce/discovery) трафика — без него H4 не проверить. +- [ ] Метрика задержки от создания сообщения (`first_route_ms` сейчас — абсолютная метка). +- [ ] Выбор пути с учётом бэклога линков и перепланирование с текущего узла, не с источника. +- [ ] Сравнить результаты с базовыми алгоритмами, не делать заявлений о превосходстве без данных. +- [ ] Выбрать криптосхему в ADR + тест-векторы; до этого не заявлять E2E-защиту. +- [x] Реализовать replay window, ACL, rate limit, лимиты очередей. +- [x] Детерминированный fuzz-smoke парсера (10 000 входов, без паник). +- [ ] Полноценный fuzz-прогон (cargo-fuzz/OSS-Fuzz) и очередь с квотами/TTL. +- [x] UDP adapter (std::net) + loopback integration test. +- [ ] A-B-C в трёх network namespaces с `tc netem`. +- [ ] Store-and-Forward: TTL и явные QUEUED/DELIVERED/EXPIRED есть, но сообщение хранится + в общем списке, а не на узле. Нет хранения на промежуточных узлах, квот и store-carry. +- [ ] Обсудить телефон+ПК: модель пользователя и несколько DeviceID. + +## P2 · реальное радио и экосистема + +- [ ] Подключить готовый RNode/LoRa адаптер и измерить фактический airtime. +- [ ] Изучить законодательство конкретной страны до передачи в эфир. +- [ ] Wi-Fi mesh / направленный backhaul, затем мобильные SDK (UniFFI — кандидат). +- [ ] Опубликовать один воспроизводимый сценарий + метрики; затем искать коллег. +- [x] Выбрать лицензию кода (LGPL-3.0-or-later) и `git init`; первый коммит — по решению автора. +- [ ] Опубликовать репозиторий () после первого коммита. + +## Решение, которое нужно принять первым + +**Что делаем на старте?** Рекомендация: отдельная симуляция и независимый Rust API, +без объявления собственного сетевого протокола «стандартом» и без беспроводного железа. +См. [вопросы для автора](docs/review/questions.md). diff --git a/archive/README.md b/archive/README.md new file mode 100644 index 0000000..91de3e1 --- /dev/null +++ b/archive/README.md @@ -0,0 +1,12 @@ +# Архив первичного исследования (2026-11-12) + +Здесь **сохранены все 34 исходных Markdown-файла** из ICE-NET research-draft-0.1. +Папки глубже разбиты исключительно для нового правила «не более 4 файлов на каталог». +Внутренние относительные Markdown-ссылки переназначены на новые пути. + +- [Оригинальный README](README_0.1.md) +- [Оригинальный START_HERE](START_HERE_0.1.md) +- [Источники S01–S30](sources/part1.md) и [S31–S60](sources/part2.md) + +**Внимание:** архивные гипотезы не становятся утверждёнными решениями. Смотри актуальные +[README](../README.md), [правила](../RULES.md), [сравнение](../docs/research/gaps.md). diff --git a/archive/README_0.1.md b/archive/README_0.1.md new file mode 100644 index 0000000..88018d7 --- /dev/null +++ b/archive/README_0.1.md @@ -0,0 +1,68 @@ +# ICE-NET — исследовательский пакет проекта автономной гибридной сети + +**Версия заметок:** `research-draft-0.1` +**Дата проверки:** 2026-11-12 +**Язык:** русский +**Статус:** концепция и план экспериментов, **НЕ готовый протокол**. + +> **Коротко.** ICE-NET — идея децентрализованной сети, способной работать через интернет, Wi-Fi, кабель, радиорелейные каналы и низкоскоростное радио; сохранять идентичность устройств независимо от физического адреса; доставлять сообщения по нескольким переходам и переживать разрывы связи. Защитный компонент условно называется **ICE Guard**. Глобальное покрытие пока только долгосрочная цель. + +## 🧭 Как читать + +1. [Начни здесь: сводка на одной странице](START_HERE_0.1.md). +2. [Общая архитектура](project/foundation/architecture.md) → [требования](project/foundation/requirements.md) → [ограничения и риски](project/governance/risks.md). +3. [Идея адресов и идентичности](protocol/foundation/identities_addresses.md) → [пакеты](protocol/foundation/packet_wire_format.md) → [маршрутизация](protocol/control/routing.md). +4. [Радио](radio/physical_links.md) → [вышки и магистрали](radio/backhaul_city_deployment.md) → [закон и частоты](radio/legal_spectrum.md). +5. [ICE Guard](security/ice_engine.md) → [модель угроз](security/threat_model.md). +6. [Что существует в мире](research/comparison.md) → [новое в 2025–2026](research/2025_2026_updates.md) → [чтение по темам](research/reading_list.md). +7. [MVP без бюджета](implementation/mvp_zero_budget.md) → [симулятор](implementation/simulation.md) → [тесты](implementation/tests_metrics.md). +8. [Где искать команду](community/projects_people.md) → [Reddit и стратегия](community/reddit_strategy.md) → [текст объявления](community/call_for_collaborators.md). + +## 🗂️ Карта разделов + +| Папка | Что внутри | +|---|---| +| [`project/`](project/foundation/vision.md) | миссия, архитектура, решения, риски | +| [`protocol/`](protocol/foundation/overview.md) | идентичность, адресация, формат пакетов, discovery, маршруты, QoS, DTN | +| [`radio/`](radio/physical_links.md) | физическая связь, направленные мосты, радиоправила | +| [`security/`](security/ice_engine.md) | ICE, криптография, приватность и модель атак | +| [`research/`](research/comparison.md) | сравнение с реальными проектами, новое в 2025–2026 | +| [`community/`](community/projects_people.md) | сообщества и публичные контакты разработчиков | +| [`implementation/`](implementation/roadmap.md) | реализация, эксперимент, тестовые сценарии и roadmap | +| [`docs/`](docs/glossary.md) | глоссарий, открытые вопросы, хронология разговоров | +| [`SOURCES.md`](sources/part1.md) | **60 пронумерованных ссылок**: RFC, мануалы, проекты, комьюнити | + +## 🧩 Ядро идеи + +```text + ICE-NET: логическая адресация и доставка + ┌────────────────────────────────────────────────────┐ + │ Приложения: текст / фото / файлы / сервисы │ + ├────────────────────────────────────────────────────┤ + │ ID узла + ID сервиса + E2E-защита + ICE Guard │ + ├────────────────────────────────────────────────────┤ + │ Discovery / routing / store-and-forward / QoS │ + └────────────────────────────────────────────────────┘ + │ │ │ │ + Интернет Wi-Fi Mesh LoRa / радио Ethernet + (временно) (быстрые) (служебный) (магистраль) +``` + +**Ключевая идея пользователя:** узкая радиополоса — преимущественно для поиска соседей, малых сообщений и объявления доступности. Большие объёмы (например, фото) идут только по найденному быстрому маршруту. Если быстрого маршрута нет — честно показываем задержку и предлагаем отложенную доставку, а не засоряем радио. + +## Что НЕ утверждается + +- «Без IP» означает: **ICE-NET не обязан использовать IP для собственных адресов и пакетов**. В гибридном режиме IP/UDP может быть одним из транспортов. +- Нет обещания бесплатного глобального покрытия: нужна физическая инфраструктура, спектр, энергия, администрирование и пользователи. +- LoRa не измеряет автоматически точную дистанцию и не подтверждает личность человека. +- Модель ICE не должна «атаковать хакера в ответ»: политика — локальная защита, аутентификация, ограничение ресурсов и отчётность. +- Слово **ICE** также закреплено за действующим IETF-протоколом NAT traversal ([RFC 8445](https://www.rfc-editor.org/info/rfc8445/)). В будущем бренд модуля безопасности потребуется уточнить. +- Здесь нет нового проверенного криптографического примитива. Для MVP берём стандартные решения. + +## Главная рекомендация + +**Не начинать с форка Linux и закупки вышек.** Сначала proof-of-concept на одном Arch Linux, затем проверка у сообщества, затем низкобюджетный физический тест. См. [roadmap](implementation/roadmap.md). + +## Лицензии и авторство + +Это новый текст исследовательского досье, подготовленный по запросу. Архив **не содержит копий стороннего исходного кода или RFC**; вместо них — ссылки. Лицензию будущего публичного репозитория нужно выбрать отдельно после обсуждения (MIT/Apache-2.0 для кода, CC BY для собственных документов — лишь варианты, не назначенные лицензии). Не присваивай себе права на сторонние разработки. diff --git a/archive/START_HERE_0.1.md b/archive/START_HERE_0.1.md new file mode 100644 index 0000000..9536b28 --- /dev/null +++ b/archive/START_HERE_0.1.md @@ -0,0 +1,36 @@ +# За 5 минут: суть ICE-NET + +## Цель +Построить сеть, в которой *идентичность* устройства не зависит от IP, операторов, дата-центров и центрального DNS. Она должна объединять любые физические линии, работать локально при падении глобального интернета и постепенно расширяться от пары компьютеров до радиомагистралей. + +## Основная архитектурная ставка + +- **Discovery / контроль:** небольшой объём объявлений по медленным каналам; ограничения количества, TTL и эфирного времени. +- **Data plane / пользовательский трафик:** большой файл только через маршруты с достаточной пропускной способностью; запрет случайного переноса фото через LoRa. +- **Addressing:** криптографическая идентичность узла и независимый идентификатор сервиса. Это **не** новые стандартные TCP-порты. +- **Routing:** поиск следующего перехода, ограниченная область распространения объявлений, метрики качества; допустима задержанная доставка. +- **ICE Guard:** небольшой детерминированный защитный компонент на CPU без GPU; поведение + правила + контроль лимитов. +- **Transport adapters:** UDP/QUIC, LAN, Wi-Fi, serial/LoRa, радиорелейная линия, Ethernet; всё опционально. + +## Неприятные, но важные факты + +1. Сеть без IP-адресов на логическом уровне **не отменяет** радиофизику и требования законодательства. +2. Даже при красивой маршрутизации фотографии не передать быстро, если каждый возможный физический путь медленный. +3. Масштабирование — не «хранить хеши всех пользователей на каждой вышке»: нужны иерархия / ограничение анонсов / кэш / запрос по требованию. +4. Большая общая база местоположений создаёт слежку. Приватность должна быть встроена изначально. +5. «Порт 77777» возможен как виртуальный ID сервиса ICE-NET, но **не** как стандартный TCP/UDP-порт ([S01](sources/part1.md#s01)). +6. Похожий подход уже демонстрирует [Reticulum](sources/part1.md#s13); лучше изучить и протестировать его, прежде чем писать всё с нуля. + +## 3 первых действия без расходов + +1. Записать 10 измеримых требований и модель угроз: [требования](project/foundation/requirements.md). +2. Поднять симулятор 10–100 узлов на одном ПК: [сценарии](implementation/simulation.md). +3. Выставить черновик спецификации на обсуждение (без обещания «заменим интернет»): [сообщества](community/projects_people.md), [пост](community/call_for_collaborators.md). + +## Сейчас не делать +- не переписывать ядро Linux; +- не изобретать криптографию; +- не закупать дорогие 60-ГГц мосты до радиопланирования; +- не обещать защиту от полного отключения энергии, массовых помех или отсутствия физического канала. + +Составной обзор: [сравнение проектов](research/comparison.md), [новинки 2025–2026](research/2025_2026_updates.md), [источники](sources/part1.md). diff --git a/archive/build/migration_egui_to_slint.md b/archive/build/migration_egui_to_slint.md new file mode 100644 index 0000000..3abcd1a --- /dev/null +++ b/archive/build/migration_egui_to_slint.md @@ -0,0 +1,35 @@ +# Переход с v0.2 (egui) на v0.3 (Slint) + +> **Исторический документ.** Миграция выполнена, Slint собирается и проверен (см. [STATUS](../../docs/STATUS.md)). +> Старого checkout с egui не существует, шаги ниже сохранены только как запись. + +В v0.3 изменён GUI; алгоритмы маршрутизации, пакеты и тесты доменных +крейтов сохранены из v0.2. Старый `ice-net-v0.2-fix.patch` больше не требуется: +он исправлял eframe API и относится только к удалённым исходникам egui. + +## Для существующего checkout + +1. Сохрани незакоммиченные изменения. +2. Замени файлы из v0.2 на новую структуру v0.3. +3. Удали старые `apps/icenet-city/src/app.rs` и `map.rs`, если они остались. +4. Удали **старый** `workspace/Cargo.lock`, который фиксировал egui/eframe. +5. Убедись, что появился `apps/icenet-city/ui/main.slint`. +6. Пересоздай `Cargo.lock`, проверь компиляцию и закоммить lockfile. + +```bash +cd workspace +cargo generate-lockfile +python3 tools/check_layout.py +cargo fmt --all +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace +cargo run -p icenet-city +``` + +## Как оценивать результат + +- Разделение GUI/симулятора важнее количества строк интерфейса. +- Для v0.3 прямых внешних зависимостей GUI только две (runtime/build-time), + но число транзитивных dependencies неизвестно до генерации lockfile. +- Slint **не гарантирует** меньший size/compile-time относительно egui. + Измерь это на одной машине, одном toolchain, с чистым `target`. diff --git a/archive/community/call_for_collaborators.md b/archive/community/call_for_collaborators.md new file mode 100644 index 0000000..9854ba1 --- /dev/null +++ b/archive/community/call_for_collaborators.md @@ -0,0 +1,38 @@ +# Черновик объявления для поиска единомышленников + +> Можно размещать после появления репозитория и одного воспроизводимого теста. Переменные в `[квадратных скобках]` заполнить реальными данными; не заявлять несуществующие достижения. + +## Русская версия + +### ICE-NET: исследовательский протокол для автономной гибридной mesh-сети + +Исследую концепцию сети, которая может жить без центрального DNS или обязательного провайдера и поддерживает разные физические линии: провод, Wi-Fi, направленные радиомосты, интернет-туннель и узкополосное радио. Низкоскоростной канал предназначен прежде всего для обнаружения соседей, коротких сообщений и маршрутов; большие файлы должны идти только через подходящую быструю линию или откладываться. + +Основные направления: ключевая идентичность узла независимо от IP, минимальный control plane, multi-hop, DTN/store-carry-forward, управление пропускной способностью и лёгкая локальная защита ICE Guard. Уже сравниваю Reticulum, Meshtastic, Babel, BPv7, libp2p и AREDN — **не утверждаю, что придумал всё с нуля**. + +Пока это draft, не готовый продукт. Ищу конструктивное ревью архитектуры и идеи для самого маленького воспроизводимого теста на Linux (1 ПК, 10–100 виртуальных узлов). Особо интересны люди с опытом routing, LoRa, Wi-Fi mesh, Rust, threat modeling, SDR и community networks. Не обещаю оплату/релиз/покрытие. + +- Архитектура: `[ссылка на репозиторий/документ]` +- Технический вопрос: «как ограничить control-plane airtime при изменении топологии и не потерять discovery?» +- Демо/тесты: `[действительная ссылка, если появились]` + +## English version + +### ICE-NET: exploring a transport-agnostic, disruption-tolerant community mesh + +I'm researching an experimental networking architecture that does not require IP addressing at its logical layer or a central server. The idea is to use low-bandwidth links (e.g. LoRa) primarily for bounded discovery/control traffic and small messages, while sending bulk data over whatever high-capacity physical route is actually available (Wi-Fi, Ethernet, point-to-point radio links or Internet tunnels). When no suitable path exists, delivery may be deferred rather than saturating a shared radio channel. + +The design topics are cryptographic node identity, service identifiers, constrained control plane, multi-hop routing, QoS, store-carry-forward, and a small local policy engine (working name: ICE Guard). I'm studying existing work including Reticulum, Meshtastic, Babel, BPv7, libp2p and AREDN, not claiming to reinvent those systems. + +It's an early research draft, **not a working global network**. I'm looking for technical criticism and collaborators willing to help define a tiny reproducible Linux simulation. Especially interested in mesh routing, RF/SDR, DTN, security and Rust systems programming. No funding or compensation is promised. + +- Draft: `[actual public URL]` +- Proposed first benchmark: control-plane airtime and recovery after link loss on a 10–100-node virtual network. +- Specific question: What failure mode would you test first, and what existing protocol should I study before implementing this? + +## Не писать так + +- «Никто никогда такого не делал» — неверно. +- «Будет покрывать весь мир бесплатно» — физически не обосновано. +- «Нейронная ICE непобедима» — нет security evidence. +- «Защищено от всех атак» — нет аудита. diff --git a/archive/community/projects_people.md b/archive/community/projects_people.md new file mode 100644 index 0000000..14a7365 --- /dev/null +++ b/archive/community/projects_people.md @@ -0,0 +1,48 @@ +# Где искать людей и партнёров — реальные входы в сообщества + +> «Люди, с которыми можно было бы реализовать» — **публичные проекты, рабочие группы и их авторы**, а не обещание их участия. Не пишем, что кто-то согласился или ищет работу. Начинать стоит с общего канала проекта и конкретного технического вопроса, а не с массовой личной рассылки. + +## Самые практичные направления + +| Организация / проект | Чем помогут в теории | Куда заходить | +|---|---|---| +| **Reticulum** | криптографические ID, низкая полоса, transport adaptation | [официальный manual](../sources/part1.md#s13), [зеркало GitHub/предупреждения](../sources/part1.md#s16) | +| **Meshtastic** | узкополосная LoRa mesh, эфир, буферы, Next-Hop | [документация](../sources/part1.md#s17), [r/meshtastic](../sources/part2.md#s50) | +| **AREDN** | реальная эксплуатация узлов, Babel, Wi-Fi HaLow | [официальный сайт](../sources/part1.md#s24), [release notes](../sources/part2.md#s35) | +| **NYC Mesh** | построение городской инфраструктуры, rooftop, карта | [volunteer / Slack / onboarding](../sources/part2.md#s45) | +| **Freifunk** | региональные mesh-сообщества и разработчики OpenWrt | [как вступить](../sources/part2.md#s46) | +| **guifi.net** | устойчивое совместное управление инфраструктурой | [платформа и гайды](../sources/part2.md#s47) | +| **Wireless Battlemesh** | личная сеть разработчиков routing/firmware | [сайт](../sources/part2.md#s48), [прошедший v18, 2026](../sources/part2.md#s49) | +| **IETF MANET** | routing в мобильных ad-hoc сетях | [WG и открытая рассылка](../sources/part1.md#s10) | +| **IETF DTN** | отсутствие непрерывного пути, стандарты BP | [WG](../sources/part1.md#s11), [документы 2026](../sources/part1.md#s12) | +| **rust-libp2p** | дешёвый P2P MVP, peer discovery, релеи | [Discussions и форум](../sources/part1.md#s22) | +| **GNU Radio** | SDR и модуляция, эксперимент в симуляции | [сообщество/релиз](../sources/part2.md#s34) | + +## Публично известные технические участники, работы которых стоит читать + +- **Mark Qvist** — автор/сопровождающий Reticulum reference implementation; README зеркала чётко объясняет, куда относится официальный процесс разработки ([публичный проект](../sources/part1.md#s16)). Сначала читать manual и уважать указания о допустимом использовании кода. +- **Juliusz Chroboczek** и **David Schinazi** — авторы [Babel RFC 8966](../sources/part1.md#s06); прежде чем задавать вопросы, изучить RFC и публичные дискуссии IETF. +- **Don Fedyk, Donald E. Eastlake 3rd, Ronald in ’t Velt** — перечислены как председатели [IETF MANET](../sources/part1.md#s10) на дату проверки; обращаться через **рабочую группу**, а не угадывать частные контакты. +- **Josh Morman** — опубликован как автор сообщения о [GNU Radio 4 RC3](../sources/part2.md#s34); обсуждать идеи SDR через публичные каналы проекта. + +Наличие имени в документации **не** означает интерес к ICE-NET, доступность к сотрудничеству или разрешение использовать чужой код. + +## Какие специалисты нужны в реальности + +1. **Network protocol engineer:** статусы узлов, адреса, congestion/routing/DTN. +2. **Wireless/RF engineer:** link budget, радиомонтаж, антенны и правовой частотный план. +3. **Systems developer (Rust/C):** быстрый стабильный core и adapters для ARM/x86. +4. **Security engineer:** threat modeling, криптографические протоколы, fuzzing. +5. **Android/iOS developer:** реальная поддержка Wi-Fi Aware, фоновая работа и батарея. +6. **Community network organizer:** люди, крыши, бюджет, инфраструктурное обслуживание. +7. **Technical writer / translator:** спецификации и onboarding. + +## В какой последовательности выходить на людей + +1. Показать **одну страницу архитектуры** и **один воспроизводимый опыт**. +2. Уточнить узкую проблему: например, «как ограничивать объявления на 1 кбит/с при изменяющейся топологии?». +3. Спросить, не реализовано ли это уже; попросить ссылку на prior art. +4. Опубликовать маленький тест/таблицу, исправить ошибки после обратной связи. +5. Только затем приглашать участвовать в разработке или запуске узла. + +**Не обещать зарплату, гранты, глобальный запуск и аудит, которых нет.** Репутация инженерного проекта строится на открытых проверяемых результатах. diff --git a/archive/community/reddit_strategy.md b/archive/community/reddit_strategy.md new file mode 100644 index 0000000..9c96245 --- /dev/null +++ b/archive/community/reddit_strategy.md @@ -0,0 +1,41 @@ +# Reddit и публичное сообщество: как собрать команду + +## Существующие сабреддиты, которые проверены + +| Площадка | Тема | Какой пост уместен | +|---|---|---| +| [r/meshtastic](../sources/part2.md#s50) | LoRa/low-speed mesh | конкретные эфирные ограничения, discovery, hardware | +| [r/darknetplan](../sources/part2.md#s51) | независимая инфраструктура | архитектура и поиск похожих проектов | +| [r/amateurradio](../sources/part2.md#s52) | радио | законность, link budget, практические измерения | +| [r/selfhosted](../sources/part2.md#s53) | автономные сервисы | пользовательские сценарии и hosted relays | +| [r/Lora](../sources/part2.md#s54) | LoRa/радиомодули | PHY и ограничения канала | +| [r/ReticulumNetwork](../sources/part2.md#s55) | тема подходит | на дату проверки постов не было: не рассчитывать на аудиторию | +| [r/Meshnet](../sources/part2.md#s56) | много тем о домашнем mesh Wi-Fi | не оптимальная площадка для новых routing-протоколов | + +**Перед публикацией** читать правила каждого сабреддита. В Reddit много практических наблюдений, но не все мнения и обещания основаны на измерениях; проверять через RFC и стенды. + +## Делать ли собственный subreddit? + +**Не в первый день.** Свой сабреддит без участников почти не решает проблему набора команды. Разумнее начать с публичного репозитория, issue-tracker и 2–3 точных обсуждений в существующих сообществах. Собственный `r/ICE_NET` или похожее имя возможно только после проверки доступности названия и появления регулярных обновлений; наличие сообщества с таким адресом **не проверено и не утверждается**. + +## Хороший первый пост + +Не «Я изобрету новый интернет, кто со мной?»; лучше: + +> Исследую transport-agnostic сеть без обязательных IP-адресов в overlay: LoRa только для маленьких discovery-анонсов, файлы через Wi-Fi/проводные/направленные backhaul, DTN при разрывах. Есть требования и таблица prior art (Reticulum, Meshtastic, Babel, BPv7). Какие фундаментальные ошибки в модели и какой тест измерить первым? + +Здесь есть узкая техническая тема и уважение к уже существующим работам. + +## Что сделать, чтобы не превратить сообщество в спам + +- На каждой площадке — **разный вопрос**, релевантный теме, без массового одинакового текста. +- Первый пост содержит архитектуру, конкретные ограничения и ссылку на воспроизводимый эксперимент. +- Ясно сказать, что это draft, не релиз/готовая сеть и не инвестиционный сбор. +- Публиковать измерения, негативные результаты и исправления ошибок. +- Документировать Code of Conduct, процесс отзывов по security, contribution guide и список good first issues. + +## Практический минимальный набор + +`README.md` → `ARCHITECTURE.md` → `tests/` с графиками → `good-first-issues` → публичный чат/форум. Когда есть живые 10–20 участников, обсуждать отдельный subreddit и модерацию. + +Текст объявления на двух языках: [call_for_collaborators](call_for_collaborators.md). diff --git a/archive/docs/changelog.md b/archive/docs/changelog.md new file mode 100644 index 0000000..0bbc2a9 --- /dev/null +++ b/archive/docs/changelog.md @@ -0,0 +1,17 @@ +# История досье + +## 2026-11-12 — Research draft 0.1 + +Собран первый архив markdown. Содержание: цели, архитектура, адресация, service ID, wire-format предложение, малоскоростное discovery, маршруты, QoS, DTN, ICE Guard, threat model, физические радиоканалы/магистрали, закон ЕС/CEPT, сравнение проектов, актуальные 2025–2026 изменения, сообщества и поэтапный MVP. + +**Подтверждено официальными источниками:** существование RFC 10069 от ноября 2026; IETF DTN обновления осени 2026; архитектура Reticulum и Meshtastic; AREDN и Wi-Fi HaLow; WBA Wi-Fi 7 MLO испытания 2026; GNU Radio 4 RC3 2026; современные нормы ЕС/CEPT. + +**Не подтверждено как работающее:** собственный ICE-NET wire format, универсальные адреса и discovery, глобальные маршруты, масштабируемая схема хешей на вышках, безопасность ICE Guard и экономическая осуществимость полного покрытия. Это исследовательские предложения. + +## Что изменить в следующей версии + +- Реальная таблица измерений после симулятора. +- Сравнить Airtime/announce budget с эталонным Reticulum и Meshtastic. +- Зафиксировать threat model и криптографические алгоритмы после review. +- Оценить стоимости двух-трёх типичных городских радиолиний с разрешённым железом. +- Опубликовать первую воспроизводимую demo-topology и получить отзывы экспертов. diff --git a/archive/docs/future_questions.md b/archive/docs/future_questions.md new file mode 100644 index 0000000..85f975e --- /dev/null +++ b/archive/docs/future_questions.md @@ -0,0 +1,39 @@ +# Открытые инженерные вопросы для следующих итераций + +## Архитектура + +- Нужен ли новый протокол вместо адаптации Reticulum? **Какая одна функция отсутствует в существующем стеке?** +- Отделять ли идентичность пользователя от идентичности физического ретранслятора? +- Как реализовать смену ключей и восстановление идентичности без центра? +- Стоит ли NodeID адресовать саму конечную машину, сервис или группу? + +## Routing + +- Как ограничить маршрутизаторную информацию в LoRa до заданного airtime budget? +- Как выбирать путь с низкой латентностью, не забивая канал неверными метриками? +- Как разделять лес локальных domain'ов и long-haul backbone? +- Что делать при взломанных relay, ложных объявленных метриках и Sybil? +- Можно ли доказать отсутствие циклов при комбинированных алгоритмах? + +## Приватность + +- Как сохранять поиск друзей без глобальной геолокации и постоянных маяков? +- Как обеспечить приватный discovery с минимальным размером пакета? +- Нужна ли анонимность? Если да, какую угроз-модель реально выдержать? + +## Радиофизика + +- Что быстрее и дешевле в конкретной местности: 5 ГГц P2P, 802.11ah, 60 ГГц или оптика? +- Какие погодные условия, зона Френеля и высоты нужны на конкретной линии? +- Какой национальный радиорежим разрешает фактическое оборудование и мощность? + +## Организация + +- Есть ли городское сообщество, готовое поставить один relay и измерять сеть месяц? +- Какая модель распределения затрат и ответственности за rooftop? +- На какой лицензии выпускать reference implementation и public specification? +- Как принять security bug без публичного раскрытия уязвимости до исправления? + +## Проверка гипотез + +Самый полезный первый сравнительный эксперимент: два алгоритма discovery на одинаковой 100-node топологии, ограничение медленного интерфейса 1 кбит/с, измерения control overhead, p95 route time, errors и energy estimate. Числа — **сценарные**, не измеренная физика. diff --git a/archive/docs/glossary.md b/archive/docs/glossary.md new file mode 100644 index 0000000..8eb3305 --- /dev/null +++ b/archive/docs/glossary.md @@ -0,0 +1,34 @@ +# Глоссарий ICE-NET + +- **Overlay** — логическая сеть поверх существующих транспортов; может использовать IP как носитель, не используя его как собственный ID. +- **Underlay** — физическая/существующая транспортная сеть. +- **NodeID** — криптографическая идентичность устройства или узла, не координаты. +- **Locator** — временный способ добраться до узла через определённый интерфейс/ретранслятор. +- **ServiceID** — логический ID сервиса, потенциально 64-битный; это не TCP-порт. +- **Control plane** — discovery/объявления/маршрутная информация. +- **Data plane** — передача пользовательской нагрузки. +- **Backhaul** — магистральная связь между узлами/вышками. +- **Mesh** — сеть с несколькими равноправными/ретранслирующими узлами; не обязательно полностью децентрализована. +- **Multi-hop** — передача через последовательность устройств. +- **Broadcast / flooding** — рассылка нескольким соседям; дорого в радиоэфире. +- **Next hop** — следующий узел в направлении конечного адресата. +- **DTN** — сеть с длительными задержками и периодическими разрывами связи. +- **Store-carry-forward** — временное хранение и передача при появлении контакта. +- **LoRa** — радиомодуляция для дальнобойной малоскоростной связи. +- **LoRaWAN** — отдельный MAC/network-протокол и экосистема поверх LoRa, не синоним LoRa. +- **Wi-Fi Aware / NAN** — прямое обнаружение nearby устройств без internet/AP при поддержке ОС и радиочипа. +- **802.11s** — Wi-Fi mesh-режим; требует аппаратной/программной поддержки. +- **802.11ah / HaLow** — Wi-Fi с суб-ГГц линком, специализированное оборудование. +- **MLO** — Wi-Fi 7 multi-link operation; несколько Wi-Fi линков. +- **FSO** — свободнопространственная оптическая связь, например оптический мост. +- **E2E encryption** — шифрование между конечными участниками, транзитным узлам ключи не предоставляются. +- **Sybil** — атака множеством поддельных идентичностей. +- **Eclipse** — вытеснение честных соседей/источников маршрутов контролируемыми атакующим узлами. +- **Anti-replay** — защита от повторного предъявления ранее корректного пакета. +- **ICE Guard** — условное название локальной защитной системы этого проекта. +- **IETF ICE** — совершенно другой протокол NAT traversal (RFC 8445), не Cyberpunk ICE Guard. +- **Proposed Standard** — статус части RFC, не то же, что Internet-Draft. +- **Internet-Draft** — рабочий черновик, может измениться или не стать RFC. +- **Goodput** — скорость передачи полезных данных после накладных расходов. +- **Airtime** — время занятия радиоканала передатчиком. +- **TTL** — срок или hop-budget доставки, чтобы пакеты не жили бесконечно. diff --git a/archive/implementation/mvp_zero_budget.md b/archive/implementation/mvp_zero_budget.md new file mode 100644 index 0000000..1bf457f --- /dev/null +++ b/archive/implementation/mvp_zero_budget.md @@ -0,0 +1,46 @@ +# MVP без бюджета — Arch Linux, один ПК + +## Цель первой версии + +Сделать **один демон ICE-NET**, который запускает виртуальные NodeID, умеет передать зашифрованное маленькое сообщение по двум-трём hop и отказывается отправлять большой файл через slow-only маршрут. Не нужно модифицировать ядро Linux, создавать дистрибутив или покупать антенны. + +## Приоритетные компоненты + +```text +icenetd + identity/ generation, fingerprints, key storage + protocols/ messages, versioning, serialization, parser tests + routing/ neighbor table, weighted path, TTL, expiry + transports/ loopback + UDP; later: serial/LoRa + LAN + storage/ bounded queue / TTL / receipts + ice_guard/ ACL, rate limit, replay, audit + cli/ node, neighbors, send, routes, trace + simulator/ topology, delay, loss, throughput, churn +``` + +Предложение языка: **Rust** для mainline (типобезопасность и ARM/x86), с использованием существующих криптографических библиотек. C также возможен, но требует особенно строгой работы с памятью. Не привязываться к одному runtime на время проектирования спецификации. + +## План на четыре небольшие вехи (без обещания дат) + +### M0 — логическая пересылка +Три виртуальных узла `A-B-C`. Узел A знает только B, но доставляет текст C. Проверить ACK конечного получателя, ограничение TTL и dedup. + +### M1 — две среды +`A-B` быстрый, `B-C` очень медленный. Симулировать 1 кбит/с; проверка, что короткий текст допускается, а фото не идёт автоматически. + +### M2 — смена пути +Добавить `A-D-C`. Отключить B, повторить. Проверить route invalidation, loss и очередь. + +### M3 — E2E + ICE Guard +Включить шифрование сообщений на endpoints, ACL сервисов, лимиты ресурсов, тест на поддельный пакет и spam flood. + +## На чём испытывать + +- Unix process + UDP loopback (для начала достаточно). +- Linux network namespaces и veth для более реалистичного поведения ([S40](../sources/part2.md#s40)). +- `tc netem` для задержки/потерь/скорости ([S41](../sources/part2.md#s41)). +- CORE/ns-3, если нужен более точный сетевой/RF симулятор ([S43](../sources/part2.md#s43), [S42](../sources/part2.md#s42)). + +## Готовность для первой публичной демонстрации + +В README должны быть шаги запуска на чистой машине, ожидаемое поведение, команда теста, один trace с 3 hops, негативный тест с большим payload, чётко отмеченные несделанные функции и security disclaimer. diff --git a/archive/implementation/roadmap.md b/archive/implementation/roadmap.md new file mode 100644 index 0000000..0a93886 --- /dev/null +++ b/archive/implementation/roadmap.md @@ -0,0 +1,37 @@ +# Roadmap: от идеи до сообщества (без придуманных сроков) + +## Фаза A — требования / prior art + +**Выход:** 1-страничная архитектура, сравнительная таблица альтернатив, модель угроз, список критериев невозможности. **Проверка:** другой разработчик понимает границу control/data и может назвать главный риск. + +## Фаза B — симулятор на одном ПК + +**Выход:** 10–1000 виртуальных узлов, фиксированные сценарии, профили медленного/быстрого канала, трассировка. **Проверка:** воспроизводимый тест после обрыва связи и запрет фото по slow link. + +## Фаза C — overlay MVP + +**Выход:** userland daemon, NodeID+ServiceID, encrypted text, UDP/LAN adapters, ICE Core, краткий API. **Проверка:** три реальных процесса по разным сетевым namespace. + +## Фаза D — интеграция и сравнение + +**Выход:** интеграционные испытания с Reticulum/Meshtastic/AREDN как *сравниваемыми эталонами*, а не выдача их кода за собственный. **Проверка:** публичные CSV, графики и честные ограничения. + +## Фаза E — физический low-cost pilot + +**Выход:** два радиоустройства/стационарных relay, законная работа в разрешённом диапазоне, реальная оценка airtime и packet loss. **Проверка:** измеренный бюджет канала и работа текстовых сценариев. + +## Фаза F — локальная mesh-инфраструктура + +**Выход:** несколько независимых реле и минимум два пути; приложение на компьютере/телефоне; безопасное обновление ПО. **Проверка:** восстановление связи после отключения одного реле. + +## Фаза G — магистральные мосты + +**Выход:** разрешённые размещения на крышах, направленная линия, учёт бюджета оборудования, локальная кооперация. **Проверка:** многодневные реальные измерения качества и отказов, законность. + +## Фаза H — федерация и стандарт + +**Выход:** независимые реализации или хотя бы независимая проверка, документированный wire format, управление версиями, governance и security disclosure. **Проверка:** две команды могут реализовать совместимые узлы без доступа к внутренним данным друг друга. + +## Не перескакивать + +Ни публичные сборы на мачты, ни форк дистрибутива Linux, ни заявление о новой безопасной глобальной сети до успешных фаз B–D. В любой фазе можно закрыть риск или поменять архитектуру, не «сжигать» годы на предположениях. diff --git a/archive/implementation/simulation.md b/archive/implementation/simulation.md new file mode 100644 index 0000000..6df0c36 --- /dev/null +++ b/archive/implementation/simulation.md @@ -0,0 +1,43 @@ +# Симуляция до покупки железа + +## Зачем + +На одном компьютере можно сравнить маршрутизацию, перегрузку и отказоустойчивость на сотнях узлов. Это не заменит физическое радио, но спасёт от нескольких месяцев разработки неверной идеи. + +## Сценарии + +| Сценарий | Топология | Что проверяем | +|---|---|---| +| A | 3 узла в цепочке | TTL, dedup, end-to-end ACK | +| B | 15 узлов, несколько путей | выбор next hop и восстановление после потери relay | +| C | 50 узлов, 1 кбит/с discovery | airtime, overhead, rate limits | +| D | 100 узлов, mobile churn | stale routes, reconnect, path search p95 | +| E | 1000 виртуальных узлов | RAM, CPU, таблицы, поток анонсов | +| F | 2 disconnected islands | store-carry-forward и честный статус без пути | +| G | 20% malicious peers | Sybil/flood/path poisoning, ложные блокировки | +| H | fast/slow mixed | 5MiB photo не забивает control plane | + +## Модель физического канала + +Для каждого edge хранить `available`, `capacity_bps`, `loss_rate`, `latency_ms`, `jitter_ms`, `energy_cost` и `airtime_budget`. Измеренные параметры отделить от придуманной симуляции. Начать с условных параметров и честно обозначать их как **сценарные**, а не реальные свойства LoRa/5GHz. + +## Бесплатные инструменты + +- **Свой дискретно-событийный симулятор**: самый дешёвый старт; логика событий, узлов, queues, TTL. +- **Linux namespaces**: настоящее сетевое ПО в изолированных сетевых окружениях ([S40](../sources/part2.md#s40)). +- **tc-netem**: имитация потерь, задержек, reorder ([S41](../sources/part2.md#s41)). +- **CORE**: графический и программный эмулятор сетей ([S43](../sources/part2.md#s43)). +- **ns-3**: более детальное моделирование среды и радио ([S42](../sources/part2.md#s42)). +- **Mininet**: простой быстрый стенд для логики сети ([S44](../sources/part2.md#s44)). +- **GNU Radio**: физические waveform/модуляции в симуляции, без разрешений на передачу, если нет реального излучения ([S33](../sources/part2.md#s33)). + +## Минимальный эксперимент без shell-команд root + +Собрать приложение из процессов/задач с `VirtualLink` и фиксированным `random_seed`. При каждом тесте записывать CSV: `time,node,event,from,to,bytes,channel,reason`. Затем вычислять [метрики](tests_metrics.md). Публичный результат должен включать topologies и seed, иначе benchmark нельзя повторить. + +## Два почти наверняка важных отрицательных результата + +1. Глобальный broadcast новых IDs перегрузит общий LoRa-канал при росте сети. +2. Aggressive learning ICE на нестационарных сетях будет ошибочно блокировать честных мобильных клиентов. + +Оба тезиса — **гипотезы для проверки**, не измеренные результаты. diff --git a/archive/implementation/tests_metrics.md b/archive/implementation/tests_metrics.md new file mode 100644 index 0000000..c975f24 --- /dev/null +++ b/archive/implementation/tests_metrics.md @@ -0,0 +1,47 @@ +# Метрики, протоколы испытаний и критерии фальсификации + +## Что мерить + +| Метрика | Единица | Зачем | +|---|---|---| +| Delivery ratio | % сообщений, дошедших до адресата | основная функция сети | +| Time-to-first-route | p50/p95 секунд | discovery и routing | +| Time-to-recover | p95 секунд | self-healing после отказа | +| Control-plane airtime | % физического канала | предотвращение засорения LoRa | +| Goodput | полезных бит/с | отличие от линковой скорости | +| Bottleneck throughput | бит/с | видимость узкого hop | +| Tail latency | p99 мс/с | редкие тяжёлые задержки | +| CPU usage | % ядра / пакетов в секунду | слабые устройства | +| RAM per 1000 peers | MiB | масштабируемость | +| Storage per relay | MiB / TTL | злоупотребление DTN | +| False positive blocking | % нормального трафика | ICE качество | +| Metadata exposed | список полей / hop | приватность | +| Energy budget | mWh / переданный MiB | мобильные узлы | + +## Первые гипотезы + +- **H1:** адаптивные объявления с rate cap сохраняют более низкий control-plane airtime, чем регулярный flood в тех же условиях. +- **H2:** отделение пути DATA от discovery предотвращает переполнение медленного радио при передаче фото. +- **H3:** path cache снижает число route queries, но увеличивает stale route errors. +- **H4:** предельные политики ICE сохраняют RAM/CPU bounded при злонамеренном флуде. + +Каждую проверять на одинаковом графе, seed, traffic pattern, времени работы и уровне потерь. Результаты должны включать отрицательные сценарии. + +## Тестовые пакеты и fuzz + +1. Неправильная длина пакета и неизвестные поля. +2. Повторный MessageID. +3. TTL=0, TTL переполнение, поддельные ACK. +4. Большие фрагменты и неограниченная reassembly. +5. Быстро меняющийся next hop. +6. 1000 случайных NodeID от одного радиоисточника. +7. Восстановление после отключения половины узлов. +8. Локальный сервис закрыт для чужих ключей. + +## Что означало бы провал концепции + +Если после разумной оптимизации control traffic растёт быстрее полезной пропускной способности медленных каналов; если нет возможности валидировать доставку без массового слежения; если цена хранения/перенаправления не ограничивается; если реальная радиофизика не позволяет полезные маршруты для целевого сценария без неприемлемой инфраструктуры. Тогда надо изменить архитектуру, а не скрывать результаты. + +## Как оформлять бенчмарк + +Один Markdown-отчёт, таблица CSV/JSON (будущий репозиторий), дата и hardware, commit hash, конфигурация, seed, график, выводы, ограничения. Не публиковать заявления «в 100 раз лучше Reticulum» без честных сравнимых измерений. diff --git a/archive/project/foundation/architecture.md b/archive/project/foundation/architecture.md new file mode 100644 index 0000000..3451bc9 --- /dev/null +++ b/archive/project/foundation/architecture.md @@ -0,0 +1,59 @@ +# Архитектура ICE-NET + +## Слои + +```text +┌───────────────────────────────────────────────┐ +│ APP: chat / images / files / service API │ +├───────────────────────────────────────────────┤ +│ SERVICE: 64-bit ID / ACL / end-to-end crypto │ +├───────────────────────────────────────────────┤ +│ DELIVERY: sessions / chunks / receipts / DTN │ +├───────────────────────────────────────────────┤ +│ NETWORK: Node ID / routing / rate limits │ +├───────────────────────────────────────────────┤ +│ ADAPTERS: UDP / LAN / Wi-Fi / serial / LoRa │ +└───────────────────────────────────────────────┘ + │ + physical medium +``` + +Это логическая модель **проекта**; ни один слой не объявлен существующим стандартом. + +## Control plane и data plane разделены логически + +- **Control plane**: HELLO, объявление доступности сервиса, получение кратких метрик, route discovery и отзыв устаревшего маршрута. Он имеет бюджет *на каждом физическом интерфейсе*. +- **Data plane**: реальные сообщения/файлы; может использовать несколько быстрых каналов, не обязан следовать тем же маршрутами, что маленькие радиопакеты. +- **Переменная задержка**: если путь отсутствует, для отдельных сервисов применяется DTN/очередь; не притворяемся, что соединение постоянно. + +## Типы узлов + +| Тип | Обязанности | Доступные среды | +|---|---|---| +| Client | Отправка/приём, иногда транзит по согласию | телефон, ПК | +| Relay | Ограниченный forward по заданным политикам | дом, крыша, маршрутизатор | +| Gateway | Мост между физическими средами | LoRa ↔ Ethernet; Wi-Fi ↔ microwave | +| Store | Защищённая очередь отложенных данных | всегда включённый узел | +| Backbone | Быстрые устойчивые линии | оптика/кабель/направленное радио | + +Могут сочетаться на одном устройстве. Никто не обязан хранить полную глобальную таблицу пользователей. + +## Сценарий «отправить фото» + +1. Телефон знает **Node ID** друга (например, из QR-кода/контактов), сервис `photo.inbox`. +2. Подключается к соседнему локальному узлу (Wi-Fi Aware, LAN, обычный интернет, когда есть). +3. Сеть оценивает наличие пути с достаточной пропускной способностью. +4. Медленный радиоканал может помочь объявить доступность или перенести небольшую управляющую запись, **но не файл**. +5. Файл разбивается на фрагменты, шифруется и уходит через быстрый путь. Посредники видят только необходимую им служебную информацию. +6. Если пути нет — приложение показывает `ожидает доставки` и TTL; пользователь сам решает, разрешить ли дорогой/медленный режим. + +## Чего не делать + +- Не flood'ить каждый поиск на всю планету. +- Не публиковать постоянный глобальный GPS узлов. +- Не разрешать любому пользователю загружать произвольные гигабайты в память чужого ретранслятора. +- Не считать «больше пути» автоматически «больше скорости». Нужно учитывать узкое место, перегрузку и стоимость передачи. + +## Ближайшие родственные подходы + +[Reticulum](../../sources/part1.md#s13) решает очень близкую задачу криптоидентичности и работы поверх разных сред. [Babel](../../sources/part1.md#s06) и [SCION](../../sources/part1.md#s20) дают другие ориентиры по маршрутам, [DTN/BPv7](../../sources/part1.md#s04) — по задержанной доставке. Не следует механически смешивать их wire-форматы без исследования совместимости. diff --git a/archive/project/foundation/requirements.md b/archive/project/foundation/requirements.md new file mode 100644 index 0000000..a5e1ecc --- /dev/null +++ b/archive/project/foundation/requirements.md @@ -0,0 +1,36 @@ +# Требования и критерии готовности v0.1 + +> Все требования ниже — **предлагаемые**, ещё не согласованный стандарт. Их следует превратить в машинные тесты. + +| ID | Требование | Проверка | +|---|---|---| +| R-01 | Логический Node ID не зависит от IP | Node ID одинаков после смены UDP-туннеля на локальный линк | +| R-02 | Нет обязательного сервера координации | Три изолированных Linux-узла могут обменяться сообщениями | +| R-03 | Транспорт сменный | Один API отправки поверх UDP, затем raw serial/test adapter | +| R-04 | Service ID шире 16 бит | Выбор идентификатора 77777, не попытка bind TCP:77777 | +| R-05 | Discovery не забивает канал | Верхний лимит доли пропускной способности на каждый интерфейс | +| R-06 | Фото не уходит через дальнее малоскоростное радио по умолчанию | Тест: запрет передачи payload > заданного размера на narrowband | +| R-07 | Неизвестный узел не получает доступ к приватному сервису | Тест deny-by-default | +| R-08 | Удаление ретранслятора не ломает идентичность | Повторный поиск маршрута и счётчик потерь | +| R-09 | У отсутствующего адресата допускается отложенная доставка | Пакет сохраняется до TTL и подтверждения | +| R-10 | Узел устойчив к флуду соседей | Rate limits, caps на память/CPU/очередь, timeout | +| R-11 | Ключи не передаются посредникам | Проверка протокола, threat review | +| R-12 | При отсутствии пути сообщаем правду | Состояния queued/no-route/expired, а не ложное «доставлено» | +| R-13 | Сбор данных о местоположении выключен по умолчанию | Проверка discovery-пакетов и конфигурации | +| R-14 | Протокол имеет версионирование | Неизвестные расширения корректно игнорируются/отклоняются | +| R-15 | Работа на ARM/x86 без GPU | Собираемый бинарник и бюджет ресурсов в тестах | + +## Non-goals v0.1 + +- Глобальное покрытие на первом релизе. +- Безлимитная пропускная способность. +- Абсолютная анонимность по умолчанию. +- Модификация Linux kernel. +- Обход правовых ограничений радиоспектра. +- Массовый публичный запуск с непроверенной криптографией. + +## Техническая проверка готовности + +**Milestone M0:** детерминированная доставка текстового сообщения по 3 hops в симуляции, проверяемый trace. **M1:** две физически разные связи, автоматическое восстановление. **M2:** E2E-ключи и лимиты трафика. **M3:** тестирование третьими лицами. + +См. [план испытаний](../../implementation/tests_metrics.md). diff --git a/archive/project/foundation/vision.md b/archive/project/foundation/vision.md new file mode 100644 index 0000000..978dc5a --- /dev/null +++ b/archive/project/foundation/vision.md @@ -0,0 +1,33 @@ +# Миссия и происхождение идеи + +## Откуда взялась ICE-NET + +Разговор начался с вопроса о 16-битных TCP/UDP-портах (0…65535) и возможности «порта 77777». Затем обсуждались собственный сетевой стек Linux/Arch, децентрализованная сеть из Cyberpunk, условная охранная система ICE, малые CPU-модели и независимость от глобального интернета. + +Идея развивалась к двум связанным направлениям: + +**1. Протокол без обязательной зависимости от IP:** свой адрес устройства, ID сервиса (хоть 64-битный), маршрутизация, доверие и обмен сообщениями поверх разных физических каналов. **2. Инфраструктура:** дальнее радио для малых объявлений/текста и быстрые маршруты через устройства, направленные антенны, локальную Wi-Fi mesh и, где есть, кабельные мосты. + +Фантастика Cyberpunk вдохновила на название ICE и идею активного охранника соединений, но сюжетная механика Breach Protocol — не инженерная спецификация. + +## Что проект должен приносить людям + +- Локальные коммуникации, когда нет доступного интернета. +- Переписку и обмен файлами с возможностью задержанной доставки. +- Возможность самостоятельно развернуть узел и не зависеть от единого центрального сервера. +- Предсказуемое поведение на дешёвых маломощных машинах и возможность CPU-only защиты. +- Открытые интерфейсы, пригодные для проверки и независимой реализации. + +## Правила проекта + +**Открытость.** Протокол документируется независимо от конкретной реализации. **Интероперабельность.** Не зависит от одной ОС или бренда устройств. **Градация возможностей.** Медленный канал — не ошибка, а ограниченная опция. **Приватность.** Не публикуем глобальные карты людей. **Безопасность.** Защищаем свои ресурсы, не атакуем других. **Исследовательская честность.** Метрики доказываются экспериментом, а не красивой схемой. + +## Небольшие точные цели вместо «всей планеты» + +- P0: три узла в одной виртуальной сети, доставка сообщений и изменение маршрута. +- P1: два типа каналов с разной пропускной способностью, управление нагрузкой. +- P2: сквозное шифрование и разрешения для сервисов. +- P3: передача файла без использования медленного discovery-канала. +- P4: выход за пределы IP-переноса через физический последовательный/радиоинтерфейс. + +Дальнейший путь см. [roadmap](../../implementation/roadmap.md). diff --git a/archive/project/governance/decisions.md b/archive/project/governance/decisions.md new file mode 100644 index 0000000..65b5f35 --- /dev/null +++ b/archive/project/governance/decisions.md @@ -0,0 +1,40 @@ +# ADR: журнал архитектурных решений + +Правило: изменение большого решения оформляем как новый ADR с мотивацией, альтернативами и критериями пересмотра. + +## ADR-001: транспорт-независимые адреса (предложено) +**Решение:** Node ID = стабильный криптографический идентификатор, физический адрес = временный маршрут. +**Причина:** адрес должен работать при переходе с UDP на локальное радио. +**Риск:** метаданные и ротация ключей; см. [privacy](../../security/crypto_privacy.md). + +## ADR-002: управление ≠ передача больших файлов (предложено) +**Решение:** discovery имеет минимальный общий интерфейс и строгие эфирные лимиты, а крупные payload допускаются только при наличии подходящего канала. +**Причина:** не забивать LoRa фотографиями. +**Исключение:** добровольная отложенная пересылка малых chunks при отсутствии альтернативы и явных квотах. + +## ADR-003: CPU-only ICE Guard (предложено) +**Решение:** детерминированное ядро правил, FSM, счётчики, token bucket и маленькая классификация без обязательной нейросети. +**Причина:** работает на слабых процессорах и поддаётся аудиту. +**Риск:** ложные блокировки, data poisoning; см. [security](../../security/ice_engine.md). + +## ADR-004: без форка ядра на MVP (принято для прототипа) +**Решение:** пользовательский процесс на Linux + сменные adapters. +**Причина:** меньшая цена эксперимента, легче тестировать и переносить. + +## ADR-005: заимствуем принципы, а не копируем чужой протокол (принято для исследований) +**Решение:** сравнительный анализ Reticulum, DTN, Babel, libp2p и других; юридический аудит лицензий перед использованием кода. +**Причина:** безопасность и лицензионная чистота. + +## ADR-006: нет активных атак «в ответ» (принято для модели безопасности) +**Решение:** ICE может локально прекратить обмен, уменьшить rate, потребовать повторную аутентификацию, изолировать ключ и сообщить владельцу, но не взламывает чужой узел. + +## ADR-007: глобальное радио — цель, а не свойство MVP +**Решение:** первая версия гибридная, но каждый компонент может работать без центральной инфраструктуры там, где есть физическая связность. + +## Открытые ADR + +- Выбор длины Node ID: полный 256-битный ключевой hash vs сокращённые идентификаторы и риск коллизий. +- Дискавери: proactive annonces vs on-demand поиск, различная политика для LoRa/backhaul. +- Домашние relay по opt-in, лимиты энергии и доверия. +- Приватная адресная книга vs глобальный каталог сервисов. +- Фрагментация, окна подтверждений и разные TTL для разных типов данных. diff --git a/archive/project/governance/risks.md b/archive/project/governance/risks.md new file mode 100644 index 0000000..be8e40a --- /dev/null +++ b/archive/project/governance/risks.md @@ -0,0 +1,38 @@ +# Риски и неприятные ограничения + +## Физика / инфраструктура + +| Риск | Почему важно | Защита от самообмана | +|---|---|---| +| Нет радиовидимости | Направленный мост не проходит через любые здания | Исследовать рельеф, высоту, зону Френеля и реальные измерения | +| Радиоэфир перегружен | Discovery не бесплатен: каждое объявление потребляет airtime | Жёсткий бюджет, периодичность, приоритеты | +| Узкое место | Один 1 кбит/с hop ограничивает всю передачу | Учитывать bottleneck; запрет больших payload | +| Нет электричества | Все ретрансляторы могут выключиться | Резерв питания там, где экономически оправданно | +| Разные частоты/нормы | Страны регулируют передатчики по-разному | Частотный план и консультация перед выходом в эфир | +| Неравномерная плотность | В городе пути есть, между городами — пустота | Backhaul, DTN и стратегические узлы | + +## Протокол + +- **Sybil/Eclipse**: ложные идентичности и поддельная «карта соседей» могут вытеснить честные маршруты. +- **Routing poisoning**: злоумышленник предлагает привлекательный путь, затем сбрасывает трафик. +- **Flooding**: каждый новый чужой Node ID вынуждает узлы тратить CPU/время эфира. +- **Metadata leakage**: повторяющийся стабильный идентификатор может позволить отслеживание даже при сильном шифровании. +- **Store-and-forward abuse**: чужие сообщения могут забить локальные диски. +- **Version fragmentation**: несовместимые версии провоцируют образование закрытых островов. + +## Проект / команда + +- Слишком рано писать своё всё (ядро, радиодрайвер, протокол, crypto, UI). +- Переоценка интереса сообщества без демонстрации кода или измерений. +- Сложная лицензия сторонних реализаций (особенно внимательно изучить предупреждения [Reticulum](../../sources/part1.md#s16)). +- Цена крыши/монтажа/страховки/электричества выше цены одного радиомодуля. + +## Пять честных предпосылок + +1. Глобальная география ≠ глобальная связность: сеть может быть набором островов. +2. Защищённая идентичность ≠ известное реальное имя и местонахождение. +3. «Сеть без IP» можно строить поверх IP при наличии интернета; это не противоречие. +4. Маршрутизаторы не обязаны понимать прикладное содержимое; политики доступа лучше проверять у конечного сервиса. +5. Новизна проекта — не в том, чтобы «открыть P2P», а в **проверяемом сочетании** низкоскоростного discovery, многосредной маршрутизации, ограничений ресурсов и UX при исчезновении связи. + +Подробная [модель угроз](../../security/threat_model.md), [закон](../../radio/legal_spectrum.md), [метрики](../../implementation/tests_metrics.md). diff --git a/archive/protocol/control/discovery_control_plane.md b/archive/protocol/control/discovery_control_plane.md new file mode 100644 index 0000000..00db36d --- /dev/null +++ b/archive/protocol/control/discovery_control_plane.md @@ -0,0 +1,40 @@ +# Обнаружение узлов: экономный control plane + +## Исходное предложение + +Дальнобойное радио распространяет **не файл**, а короткие данные: «сосед доступен», «у меня есть путь», «этот ID видел недавно», «сервис возможен через меня». Стабильные ключи, полные списки контактов и GPS-позиции не должны публиковаться по умолчанию. + +## Процедура + +1. Узел слушает несколько каналов/адаптеров и строит таблицу **непосредственных соседей**. +2. Периодически с jitter отправляет редкое HELLO согласно airtime budget. +3. Транспортный узел анонсирует **ограниченный** набор направлений, а не всех клиентов мира. +4. При необходимости узел задаёт rate-limited запрос PATH_QUERY; ответы записываются в кеш со сроком годности. +5. При переполнении медленного канала служебные обновления сокращаются, объединяются или откладываются. + +## Не путать «хеши» с маршрутизацией + +Хеш ID подходит для ключа записи. Bloom filter может сказать «возможно есть такой ID в области», но: + +- false positive -> ошибочный поиск; +- хеш не даёт права читать содержимое; +- глобальный индекс ID может компрометировать приватность; +- фильтры имеют параметры размера и ошибки; их распространение тоже стоит airtime. + +Поэтому Bloom filters — **исследуемая опция** для агрегированного presence, не базовая истина проекта. + +## Масштабирование + +| Масштаб | Стратегия | +|---|---| +| Несколько узлов | прямая таблица соседей | +| Район | локальные агрегаты + route queries | +| Город | границы зон, ретрансляторы, приоритизация и кеш | +| Города | высокоскоростные backbone переходы или DTN | +| Глобально | разделённые домены управления и проверка стоимости служебного трафика | + +У Reticulum есть подробная схема announces и ограничения полосы под них ([S14](../../sources/part1.md#s14)); Meshtastic управляет floods и использует next-hop для direct messages ([S17](../../sources/part1.md#s17)). Сначала сравнить их airtime и поведение при перемещении узлов. + +## Измерения, без которых архитектура не обоснована + +Control overhead (% полезной/доступной полосы), среднее число анонсов/узел/час, время поиска (p50/p95), отношение false-positive, степень устаревания маршрутов и раскрытие идентичности. diff --git a/archive/protocol/control/routing.md b/archive/protocol/control/routing.md new file mode 100644 index 0000000..66f82fd --- /dev/null +++ b/archive/protocol/control/routing.md @@ -0,0 +1,52 @@ +# Маршрутизация: как найти друга через тысячи устройств + +## Требования + +Маршрутизатор знает **своих соседей** и следующий переход для части адресов. Ему не нужен полный граф всей сети или «все люди в радиусе каждой вышки». + +## Пример + +```text + Дом A ─── Wi-Fi ─── R1 ══ радиомост ══ R2 ─── Wi-Fi ─── Дом B + │ │ + LoRa LoRa + discovery discovery +``` + +Когда A отправляет фото B, LoRa может помочь обнаружению. Большой файл идёт A→R1→R2→B, **только если** есть реальные быстрые физические участки и они разрешены политиками. + +## Метрики маршрута + +Нельзя выбирать только по числу hops. Учитывать: + +- оценку задержки и потерь; +- *минимальную* пропускную способность вдоль пути; +- airtime и фактическую занятость радио; +- стоимость энергии на мобильном устройстве; +- разрешение владельца relay, квоту/платный канал; +- надёжность/время последнего контакта; +- безопасность маршрута и историю отказов. + +## Возможные направления реализации + +**A. Проактивная маршрутизация (Babel/батманоподобная)** — хорошо для сравнительно связной локальной сети, есть регулярные обновления. [Babel RFC 8966](../../sources/part1.md#s06), [batman-adv](../../sources/part1.md#s23). +**B. On-demand / announce-based** — меньше постоянных сообщений при редких запросах. Изучать [Reticulum](../../sources/part1.md#s14). +**C. Content/destination discovery** — DHT через стабильные быстрые узлы (см. [libp2p](../../sources/part1.md#s21)); DHT не переносится бесплатно на узкополосное радио. +**D. DTN** — доставка при отсутствии одновременного пути ([RFC 9171](../../sources/part1.md#s04)). + +## Гибридная гипотеза + +- В пределах высокоскоростного района — поддерживаем соседские маршруты и метрики. +- Между районами — отдельные backbone-переходы и границы анонсирования. +- При отсутствии пути — store-carry-forward с TTL и квотами. + +Это **пока не доказано**. Особая проблема — единая корректность при изменении путей между разными классами link'ов. Тестировать петли, route storms, malicious metrics и голодание медленных узлов. + +## Failure behavior + +- После смерти соседнего узла — route invalidation, backoff на перестроение. +- Для дублирующихся путей — осторожная multipath политика, не перемножать дубликаты бесконтрольно. +- `NO_ROUTE` — обычный статус. +- `QUEUED` ≠ `DELIVERED`. Только конечное подтверждение даёт `DELIVERED`. + +Полезное новое: [RFC 10069 (2026)](../../sources/part1.md#s03) добавил управление несколькими путями **в QUIC**, но он не заменяет маршрутизатор ICE-NET. diff --git a/archive/protocol/control/transport_qos.md b/archive/protocol/control/transport_qos.md new file mode 100644 index 0000000..7986778 --- /dev/null +++ b/archive/protocol/control/transport_qos.md @@ -0,0 +1,41 @@ +# Транспорт и QoS: от нескольких байтов до фотографии + +## Почему классификация трафика обязательна + +Представим 5 MiB фото (≈41.9 млн бит). Даже идеальный канал **1 кбит/с** теоретически потребовал бы **≈11.7 часа**, без сетевых заголовков, повторов, пауз и правовых ограничений. Поэтому «через LoRa пойдёт, просто медленно» — опасная продуктовая установка; она забьёт общий эфир. + +## Классы трафика (предложение) + +| Класс | Пример | Политика | +|---|---|---| +| C0 | HELLO, route hints, ошибки | очень короткий payload, rate limit, высокий приоритет только в пределах квоты | +| C1 | SOS, короткое текстовое сообщение | допускается slow link по согласию, отдельная fair queue | +| C2 | обычный чат и подтверждения | высокий приоритет среди приложений, encryption | +| C3 | фото, файлы, обновления | **fast-links-only** по умолчанию, chunks + resume | +| C4 | потоковое видео/аудио | best-effort, без гарантий, только при подходящем непрерывном пути | + +## Доставка файла + +- Разбивать на ограниченные chunks, иметь идентификаторы фрагментов, integrity hash всего файла, окно выдачи и возобновление. +- Сжимать там, где экономия реальна (не предполагать, что JPEG сжимается ещё на порядок). +- Уважать лимиты памяти и диска каждого транзитного узла. +- Использовать congestion/flow control для каждой доступной среды, а не одну «скорость сети». +- Не делать многопутевую передачу доступной по умолчанию без контроля порядка и устойчивости. + +## Предварительный scheduler + +```text +if no_path: queue_or_fail() +elif file_size > MAX_SLOW_PAYLOAD and path.bottleneck < FAST_THRESHOLD: + offer_deferred_delivery() +else: + send_chunks_with_rate_limit() +``` + +Порог выбирается экспериментом. Идентичность узла/сервиса и разрешения проверяются **до** доступа к ресурсоёмкому приложению. + +## Сравнить с реальными технологиями + +- [QUIC RFC 9000](../../sources/part1.md#s02): streams, смена пути, congestion control. +- [Multipath QUIC RFC 10069](../../sources/part1.md#s03): несколько путей при одном соединении, новый стандарт 2026; не автоматически пригоден для каждого LoRa линка. +- [LoRaWAN ограничения](../../sources/part2.md#s31): хороший пример, почему канал малых пакетов нельзя продавать как видеосеть. diff --git a/archive/protocol/foundation/identities_addresses.md b/archive/protocol/foundation/identities_addresses.md new file mode 100644 index 0000000..36ccb33 --- /dev/null +++ b/archive/protocol/foundation/identities_addresses.md @@ -0,0 +1,37 @@ +# Криптографическая идентичность и адресация + +## Исходная проблема + +IP — адрес интерфейса в сети с определённой моделью маршрутизации. В ICE-NET нужен логический ID, который переживает смену транспорта. **Это не «IP плохой»**: IPv6 уже имеет огромный адресный диапазон, а польза новой адресации — независимость от IP-плоскости, поддержка радиосвязи и идентичность по ключу, а не число портов. + +## Предложенная модель + +```text +node-id: ice1:Q7HW... (краткое человекочитаемое представление) +service: 77777 (логический ServiceID, uint64) +locator: local-wifi / serial-radio / udp-gateway / relay-next-hop +``` + +- Генерировать приватный ключ локально и хранить его защищённо. +- `NodeID` вычислять из открытого ключа стандартной функцией криптографического хеширования и схемой однозначного кодирования. +- `ServiceID` определять независимо от физического адреса; **приложение** решает, разрешён ли сервис на этом узле. +- Human readable alias (`friend@...`) — отдельно, с локальной книгой контактов и проверкой отпечатка. + +## Запрос «кто ты?» и «где ты?» — разные вещи + +Подпись challenge доказывает **владение ключом**, но не доказывает, что человек действительно друг и что устройство находится в заявленном городе. Для привязки к человеку нужен обмен отпечатками (QR-код, личное подтверждение) или модель доверия. Для расстояния нужны измерения RTT/RTT-радио, а не чтение NodeID. Подробнее: [Wi-Fi Aware RTT](../../sources/part1.md#s27). + +## Приватность + +Долгоживущий идентификатор в публичном beacon можно использовать для трекинга. Рассмотреть ротируемые announcement ID, псевдонимы локальных сервисов, короткий TTL, разделение идентичности и сетевого локатора. Нельзя назвать сеть «анонимной», пока не оценена утечка метаданных. + +## Важные операции + +- **Key rotation:** при замене ключа узел подписывает безопасное переназначение до компрометации; при компрометации нужна политика отзывов. +- **Lost keys:** восстановление ключей — отдельная пользовательская задача, централизованная «проверка паспорта» не требуется протоколу. +- **Collisions:** сокращённые адреса экономят эфир, но повышают риск совпадения; нужно хранить полный ID при аутентификации. +- **Key separation:** отдельные ключи аутентификации, шифрования и подписи сообщений в соответствии с выбранным криптографическим протоколом. + +## Что читать + +[HPKE RFC 9180](../../sources/part1.md#s08), [Noise](../../sources/part1.md#s26), [Reticulum ID](../../sources/part1.md#s14), [MLS](../../sources/part1.md#s07). Выбор конкретных алгоритмов — результат отдельного security review. diff --git a/archive/protocol/foundation/overview.md b/archive/protocol/foundation/overview.md new file mode 100644 index 0000000..6f3b404 --- /dev/null +++ b/archive/protocol/foundation/overview.md @@ -0,0 +1,40 @@ +# Протокол: границы и жизненный цикл v0.1 + +> **Proposal:** ниже не RFC, а исходный скелет. Цель — удобство инженерного обсуждения, а не немедленная реализация совместимого стандарта. + +## Что в сети считается адресом + +- `NodeID` обозначает **идентичность конечного устройства**, а не физический радиоканал. +- `ServiceID` (пока предложено 64 бита) обозначает конкретное приложение/доступную функцию. +- `Locator` — локальные сведения о пути: Wi-Fi MAC, последовательный порт, UDP endpoint, следующий ретранслятор. Он может изменяться без изменения идентичности. + +Невозможно создать реальный TCP/UDP порт 77777 без изменения wire format TCP/UDP; возможен **виртуальный сервис** с ID `77777` в собственном протоколе ([RFC 9293](../../sources/part1.md#s01)). + +## Обязательные элементы протокола + +1. `HELLO`: обнаружение соседа и его способностей (ограниченная локальная область). +2. `ANNOUNCE`: сообщение о достижимости NodeID/сервиса с ограниченным сроком действия. +3. `PATH_QUERY / PATH_REPLY`: поиск маршрута по запросу; rate limited. +4. `DATA`: зашифрованный пользовательский payload; metadata минимальна. +5. `ACK / STATUS`: доставка до получателя (не путать с подтверждением от одного ретранслятора). +6. `ERROR / QUOTA`: явный отказ, нет пути, закончился бюджет или TTL. + +## Фазы отправки + +```text +UNKNOWN → DISCOVERY → PATH CANDIDATE → POLICY CHECK + ↘ NO PATH → QUEUED (if allowed) +POLICY CHECK → SEND CHUNKS → VERIFY → DELIVERED + ↘ EXPIRED / FAILED +``` + +## Чего не стоит стандартизировать сразу + +- Человекочитаемые имена: они удобны, но могут потребовать сложного распределённого резолвера. +- «Полную» унифицированную таблицу топологии. +- Самостоятельные новые криптографические операции. +- Одновременную поддержку всех радиопротоколов. + +## Референсы + +[Reticulum](../../sources/part1.md#s13), [Babel](../../sources/part1.md#s06), [DTN](../../sources/part1.md#s04), [libp2p](../../sources/part1.md#s21). См. детальную [адресацию](identities_addresses.md), [маршруты](../control/routing.md), [wire format](packet_wire_format.md). diff --git a/archive/protocol/foundation/packet_wire_format.md b/archive/protocol/foundation/packet_wire_format.md new file mode 100644 index 0000000..9fc1454 --- /dev/null +++ b/archive/protocol/foundation/packet_wire_format.md @@ -0,0 +1,40 @@ +# Черновой wire format (proposal; не для production) + +Формат нужен, чтобы обсудить стоимость каждого байта. **Ниже иллюстративный формат без окончательно выбранных размеров и криптографических параметров.** Он намеренно не является готовой реализацией. + +## Пример полей + +| Поле | Предварительно | Назначение | +|---|---:|---| +| Version | 1 байт | Обратная совместимость | +| Type | 1 байт | HELLO / ANNOUNCE / DATA / ACK | +| Flags | 1 байт | Опциональные признаки | +| HopLimit | 1 байт | Снижение риска бесконечных петель | +| MessageID | 8–16 байт | Dedup; нужен анти-replay анализ | +| Src/Dst hint | переменно | Указатели без раскрытия полных ключей всегда | +| ServiceID | varint или 8 байт | Логический сервис, например 77777 | +| TTL / Expiry | переменно | Завершение жизни пакета | +| Payload | переменно | Зашифрованные данные/служебная нагрузка | +| Auth tag | по выбранному AEAD | Контроль целостности/подлинности | + +## Приоритетная проблема — не экономия одного байта + +Радиоканалу дорого стоит **каждая передача**, а особенно широковещательная. Сначала измерить частоту объявлений, длины пакетов, ограничения времени эфира и повторов, потом оптимизировать кодирование. + +## Дополнения + +- `HELLO` должен укладываться в бюджет discovery-адаптера; не раскрывать лишние имена и координаты. +- `DATA` не обязательно помещается в один пакет физического канала; нужна фрагментация, контроль памяти и защита от повторов. +- Уменьшение HopLimit на каждом переходе, проверка явных возрастных/TTL полей. +- Список расширений по TLV или другому парсибельному схематическому кодированию, обработка неизвестных обязательных полей. +- Все входные длины, смещения, переменные числа проверять до выделения памяти. + +## Невыполненные задачи перед реализацией + +1. Угрозы подделки/повторного воспроизведения сообщений. +2. Формат подписи и каноническое кодирование при нескольких языках программирования. +3. MTU по каждому адаптеру, фрагментация и сохранение replay-window при DTN. +4. Стратегия версии + downgrade protection. +5. Закреплённые test vectors и fuzzing сериализатора. + +Протоколу нельзя давать обещания безопасности, пока он не прошёл независимый аудит. См. [threat model](../../security/threat_model.md). diff --git a/archive/protocol/store/storage_dtn.md b/archive/protocol/store/storage_dtn.md new file mode 100644 index 0000000..65e2d66 --- /dev/null +++ b/archive/protocol/store/storage_dtn.md @@ -0,0 +1,29 @@ +# Когда связь прерывается: DTN / store-carry-forward + +## Сценарий + +Деревня без постоянного радио-моста. Сообщение для друга помещается в зашифрованную локальную очередь, а когда появляется доступный узел (машина/рюкзак/вышка/временный gateway), копия переправляется. Получатель может получить данные через часы. Это **задержанная доставка**, не live-соединение. + +## Очередь должна иметь правила + +- Storage quota по пользователю/узлу/сервису. +- TTL/expiry для каждого сообщения. +- Отдельно квитанция о приёме relay и о доставке адресату. +- Content ciphertext + минимум метаданных. +- Удаление старых сообщений по прозрачной политике, а не бесконечный диск. +- Предотвращение replay, копирования одних и тех же bundle и намеренного засорения памяти. +- Не обещать доставку, если пути не возникает ни разу. + +## Три модели + +1. **Store-and-forward при активном пути** — краткая очередь между соседними hops. +2. **Store-carry-forward (DTN)** — нет end-to-end пути, relay переносит зашифрованный пакет физически или ждёт появления линка. +3. **Scheduled contacts** — известные окна доступности, например периодический мост; требует календаря доступности и реального измерения. + +## Инженерные источники + +[BPv7 RFC 9171](../../sources/part1.md#s04) уже формализует передачу через проблемные сети. [BPSec RFC 9172](../../sources/part1.md#s05) прямо обсуждает защиту хранения, ограниченность ресурсов и отсутствие непрерывного доступа к авторитетному серверу. В 2026 IETF продолжает работу над [обнаружением и управлением в DTN](../../sources/part1.md#s12), но эти новые документы — **drafts**, пока не стандарт. + +## UX + +Показывать пользователю `отправлено с моего устройства`, `передано следующему узлу`, `доставлено конечному`, `истекло`. Никогда не называть первую стадию финальной доставкой. diff --git a/archive/radio/backhaul_city_deployment.md b/archive/radio/backhaul_city_deployment.md new file mode 100644 index 0000000..b8c27af --- /dev/null +++ b/archive/radio/backhaul_city_deployment.md @@ -0,0 +1,48 @@ +# Вышки, крыши, направленные мосты и реальная цена сети + +## Что пользователю понравилось в идее + +Низкоскоростная вышка **не прокачивает все фото через себя**. Она объявляет присутствие и помогает поиску маршрута. Для крупных данных строится физически быстрый маршрут из соседних смартфонов, локальных Wi-Fi устройств, домовых relay и направленных мостов между крышами. + +## Реалистичная городская схема + +```text + Смартфоны ↔ [домашний Wi-Fi relay] ---+-- [районный hub A] + | || + Ethernet || направленный backhaul + | || + Смартфоны ↔ [другой дом/кафе] --------+-- [районный hub B] + ... | + резервный канал/DTN +``` + +**Важное уточнение:** цепочка из телефонов менее предсказуема, чем инфраструктурные узлы: они уходят, выключают Wi-Fi, экономят батарею; ОС ограничивает фоновую работу. Город с большим количеством пользователей не гарантирует непрерывный путь без стационарных узлов. + +## Что нужно реальной «вышке» + +1. Разрешение разместить оборудование на крыше / мачте. +2. Питание, погодозащита, молниезащита и требования электробезопасности. +3. Радиомодем, антенна и согласованный частотный план. +4. Вычислитель/маршрутизатор, не обязательно полноценный мини-сервер. +5. Мониторинг состояния, обновления, физический доступ для ремонта. +6. Резервный путь или понятное поведение при обрыве. + +## Какие магистрали испытывать первыми + +- 5 ГГц направленная радиолиния: относительно доступна по железу, но качество и законные параметры зависят от географии/частоты. +- Кабель между собственными двумя комнатами/помещениями: бесплатная в смысле радиопомех тестовая база, если кабель уже есть. +- 60 ГГц там, где короткая гарантированная видимость и нужен большой backhaul. Делать осмысленный budget дождя и атмосферного затухания. +- Длинные licensed microwave линии — **не** дешёвый хобби-первый шаг. +- FSO — интересная исследовательская альтернатива, но туман и юстировка делают её рискованной как единственный магистральный канал. + +## Как сократить капитальные расходы + +**Архитектурно:** сетевые узлы могут быть предоставлены добровольцами, работать на существующих мини-компьютерах/совместимых роутерах. **Операционно:** требуются обязанности, финансирование обслуживания, прозрачные правила и учёт потока ресурсов. Модель сообщества изучать у [NYC Mesh](../sources/part2.md#s45), [Freifunk](../sources/part2.md#s46), [guifi.net](../sources/part2.md#s47). + +## Масштабирование без потери независимости + +Предлагать **федерацию районов**: каждый район сам управляет relay, ключами доступа к своим сервисам и политиками backhaul; объединение по добровольным interconnect соглашениям. Не давать одному центральному серверу права запретить работу всех остальных. + +## Предлагаемый пилот + +Первый физический пилот = два стационарных узла + один мобильный клиент + один искусственно плохой канал. Цель — подтвердить *работу протокола*, а не показать покрытие города. После измерений перейти к 3–5 реальным точкам с резервным маршрутом. diff --git a/archive/radio/legal_spectrum.md b/archive/radio/legal_spectrum.md new file mode 100644 index 0000000..224f33d --- /dev/null +++ b/archive/radio/legal_spectrum.md @@ -0,0 +1,32 @@ +# Радиозаконодательство и безопасность эксплуатации (обязательно до эфира) + +> Информационный обзор, не юридическая консультация. Страна, диапазон, мощность, аппаратный класс, назначение и тип передачи определяют правила. **Нельзя** просто выбрать частоту и произвольно излучать. + +## Что проверить перед покупкой/передачей + +1. Национальная таблица распределения частот, ограничения на конкретную полосу. +2. Разрешённая EIRP/ERP с учётом усиления направленной антенны (не только мощность модуля). +3. Duty cycle, LBT/AFA и требования к совместному использованию спектра, если применимы. +4. Ограничения на наружные устройства, DFS/TPC и каналы Wi-Fi, если применимы. +5. Требования по соответствию радиооборудования, CE/RED, монтажу и электро/лазерной безопасности. +6. Нужно ли получать индивидуальную лицензию / согласие на размещение антенны. +7. Правила радиолюбительской службы: не считать все её диапазоны свободной альтернативой для приватного коммерческого зашифрованного трафика; проверить правила соответствующей юрисдикции. + +## Источники (проверены до 12.11.2026) + +- [CEPT/EFIS](../sources/part2.md#s36) и [ERC/REC 70-03](../sources/part2.md#s37) — подбор по диапазону и национальные отклонения. +- [Директива 2014/53/EU](../sources/part2.md#s38) — правовая рамка при выводе радиооборудования на рынок ЕС. +- [Страница Еврокомиссии о RED](../sources/part2.md#s39) — юридические изменения 2026. **Важно:** в 2026 принят акт об отмене отдельного cybersecurity-регулирования RED с действием отмены с 11 декабря 2027 года на фоне перехода к CRA; не полагаться на старые FAQ 2024–2025 как на окончательное состояние. + +## Для ЕС/Польши, если сеть разворачивается там + +В ЕС гармонизация не означает идентичность всех ограничений в каждой стране. Для конкретного оборудования и частоты требуется проверка национальных интерфейсов и актуальных решений регулятора; рекомендации CEPT сами по себе не заменяют применимое право. + +## Нельзя упрощать + +- «868 МГц — свободная частота для чего угодно» — неверно. +- «Направленная антенна позволяет бесконечно увеличивать мощность» — неверно. +- «Если это P2P и не интернет, то закон о радиочастотах не действует» — неверно. +- «Лазер между крышами не требует безопасности» — неверно. + +Первый легальный и безопасный этап — **симуляция и проводной стенд**; радиочасть только после отдельной проверки диапазона и железа. diff --git a/archive/radio/physical_links.md b/archive/radio/physical_links.md new file mode 100644 index 0000000..c9e3f13 --- /dev/null +++ b/archive/radio/physical_links.md @@ -0,0 +1,39 @@ +# Физическая передача: какие каналы подходят ICE-NET + +> Среда не выбирается по лозунгу «дальше = лучше». Важны зона видимости, суммарная полоса, задержка, чувствительность к помехам, управление спектром, энергия, цена размещения и число устройств. + +## Технологии по задачам + +| Среда | Для чего может пригодиться | Что не стоит обещать | +|---|---|---| +| LoRa (физический уровень) | редкие HELLO, SOS, короткий текст, очень экономные объявления | высокая скорость для фото и массовых широковещаний | +| LoRaWAN | отдельная IoT-сеть со своей архитектурой шлюзов и управляющей сетью | «универсальная LoRa mesh»: LoRaWAN не означает mesh по умолчанию | +| Wi-Fi 2.4/5/6 ГГц | локальные быстрые данные, соединения ближайших узлов | постоянное километровое покрытие в городе сквозь здания | +| Wi-Fi Aware (NAN) | discovery и прямое соединение поддерживаемых телефонов | поддержка абсолютно всех смартфонов, свободная многохоп-маршрутизация ОС | +| 802.11s + batman-adv | локальный mesh из поддерживаемых роутеров | работа без ограничения общего эфирного ресурса | +| Wi-Fi HaLow (802.11ah) | промежуточный вариант «дальность / скорость» в суб-ГГц диапазоне | обязательная поддержка обычным телефоном | +| Направленный 5 ГГц | сравнительно дешёвый backhaul между крышами при прямой видимости | гарантия скорости и легальности в любой стране/полосе | +| 60 ГГц | быстрые короткие плотные магистральные мосты в подходящих условиях | надёжная связь на десятки километров сквозь дождь/здания | +| Радиорелейная СВЧ | более дальние магистрали при расчёте трасс и правильных разрешениях | монтаж без инженерных расчётов и требований регулятора | +| FSO/лазер | быстрый оптический мост между фиксированными точками | устойчивость к туману и отсутствие требований к безопасности излучения | +| Ethernet / оптоволокно | самая предсказуемая backbone-связь где возможно | доступность везде без прокладки и разрешений | +| SDR (GNU Radio) | эксперименты с физическим протоколом и сигнальной обработкой | возможность законно излучать что угодно на любой частоте | + +## Что действительно новое/полезное к 2026 + +- **Wi-Fi 7 MLO:** несколько Wi-Fi-линков между совместимыми клиентами и AP; доказанное направление повышения устойчивости, **не mesh между городами** ([AOSP](../sources/part1.md#s29), [полевые испытания 2026](../sources/part1.md#s30)). +- **Wi-Fi Aware:** уже позволяет прямое обнаружение и высокоскоростное общение без интернета на поддерживаемых устройствах ([AOSP](../sources/part1.md#s27), [Apple](../sources/part2.md#s59)); отличная тема для клиента ICE-NET, но смотреть API и поддержку железа. +- **AREDN использует 802.11ah/HaLow:** практические прошивки и драйверы существуют ([S25](../sources/part1.md#s25), [S35](../sources/part2.md#s35)). +- **GNU Radio 4 RC3 от октября 2026:** для разработки DSP и SDR есть живая open-source экосистема ([S34](../sources/part2.md#s34)). + +## Нельзя путать «дальность» и «адресацию» + +Радиомаяк может помочь понять, что некий узел **слышен** и какой сигнал принят. Но RSSI сам по себе не измеряет точное расстояние: мешают мощность передатчика, отражения, препятствия и антенны. Для определения положения могут понадобиться RTT, несколько приёмников, GNSS или специальные методы, с отдельной моделью приватности. + +## Задача про фото + +Если человек отправляет фото — scheduler сперва ищет fast path, а затем либо использует его, либо откладывает доставку. **Не надо** «выбирать хороший канал по красивой метке вышки»: узкое звено может находиться на любом hop. + +## Надёжность магистралей + +Для фиксированных трасс применимы расчёты ITU-R P.530-19 ([S32](../sources/part2.md#s32)). Туман для FSO исследуется отдельно ([S57](../sources/part2.md#s57)). Не переносить лабораторную пропускную способность на случайную городскую сеть. diff --git a/archive/research/2025_2026_updates.md b/archive/research/2025_2026_updates.md new file mode 100644 index 0000000..a8200a6 --- /dev/null +++ b/archive/research/2025_2026_updates.md @@ -0,0 +1,49 @@ +# Что особенно важно из найденного в 2025–2026 + +> **Срез исследований на 12 ноября 2026.** Здесь только результаты с конкретными источниками и статусами. Не все «новые» технологии впервые появились в эти годы — часто нова редакция, релиз или испытание. + +## Ноябрь 2026 — Multipath QUIC становится RFC 10069 + +[Опубликован RFC 10069](../sources/part1.md#s03), *Managing Multiple Paths for a QUIC Connection*, статус Proposed Standard. Он описывает управление несколькими путями одного QUIC-соединения и явные path IDs. Авторы прямо оговаривают, что адресное обнаружение и планирование трафика по путям вне документа. **Для ICE-NET**: идея отделять транспортное многопутевое соединение от собственно mesh-маршрутизатора. + +## Октябрь–ноябрь 2026 — активная работа над DTN + +[IETF DTN WG](../sources/part1.md#s11) обновила устав 5 октября 2026. В реестре [активных документов](../sources/part1.md#s12) находятся Internet-Drafts о безопасных объявлениях и соседском discovery (SAND), однонаправленной передаче, forward error correction и QUIC convergence layers. **Это проекты стандартов**, ещё не обещанная совместимость. Для ICE-NET особенно важны автономное discovery, доставляемость при длительных разрывах и управление очередями. + +## Октябрь 2026 — GNU Radio 4.0 RC3 + +[13 октября 2026 GNU Radio выпустила RC3](../sources/part2.md#s34): новый modular runtime и новые DSP-модули; объявлен переход к более широкому сопровождению сообщества. Это не релиз 4.0 final. Для проекта — возможность экспериментировать с сигналами, не создавая радиотракт с нуля. + +## Октябрь 2026 — Briar и AREDN + +Сайт [Briar](../sources/part1.md#s18) указывает релиз 1.5.24 от 30 октября 2026 — P2P-общение без центрального сервера через Bluetooth/Wi-Fi/Tor. +Сайт [AREDN](../sources/part1.md#s24) описывает выпуск 4.26.10.0 и новые возможности multi-radio в 2026; его публичные [release notes](../sources/part2.md#s35) показывают практику использования Babel, OpenWrt, Wi-Fi и HaLow. + +## Февраль 2026 — Wi-Fi 7 Multi-Link Operation + +[Wireless Broadband Alliance](../sources/part1.md#s30) опубликовала результаты полевых испытаний. MLO поддерживает параллельные/альтернативные каналы совместимых устройств и может улучшать устойчивость. **Ограничение**: тесты проведены в конкретной жилой среде, это не доказательство километрового mesh. Для ICE-NET интересен выбор физического канала, а не создание нового стандарта радиосвязи. + +## 2025–2026 — Wi-Fi HaLow / 802.11ah в практических mesh-проектах + +[AREDN (октябрь 2025)](../sources/part1.md#s25) перечисляет поддерживаемые HaLow-устройства в экспериментальных ветках, а [release notes 2026](../sources/part2.md#s35) подтверждают продолжение поддержки. Для ICE-NET HaLow стоит исследовать как **средний класс** между LoRa и обычным Wi-Fi. Это не замена радиомагистрали и не стандартная функция каждого смартфона. + +## Сентябрь 2025 — ITU-R P.530-19 + +Новая действующая редакция [P.530-19](../sources/part2.md#s32) содержит модель расчёта надёжности terrestrial line-of-sight радиолиний. Это практическая база для проектирования направленных мостов, особенно дождевых потерь, fading и устойчивости нескольких hops. + +## 2026 — FSO в исследовательской литературе + +[Статья ноября 2026](../sources/part2.md#s57) рассматривает fog-limited оптические линии и обоснованность моделей затухания. Она подчёркивает, что высокая скорость FSO сама по себе не означает приемлемую круглогодичную доступность. + +## Регулирование — документы тоже меняются + +[CEPT](../sources/part2.md#s37) и [EFIS](../sources/part2.md#s36) обновляют условия применения SRD. [Еврокомиссия](../sources/part2.md#s39) сообщила в 2026 об утверждённой отмене отдельного делегированного cybersecurity-акта RED **с 11 декабря 2027 года** на фоне перехода к CRA. Перед радиотестами проверять последнюю **национальную** реализацию, а не только дату старой статьи. + +## Что не является доказанным «прорывом» + +- 6G как гарантия бесплатной автономной связи: нет. +- Квантовый интернет, автоматически решающий mesh discovery: нет. +- Умная антенна, передающая фото сквозь любой город без ретрансляторов: нет. +- Обучаемый ICE без ложных блокировок: пока нет. + +Следить прежде всего за [IETF MANET](../sources/part1.md#s10), [IETF DTN](../sources/part1.md#s12), [Reticulum](../sources/part1.md#s13), [AREDN](../sources/part1.md#s24) и [GNU Radio](../sources/part2.md#s34). diff --git a/archive/research/comparison.md b/archive/research/comparison.md new file mode 100644 index 0000000..67cf1dc --- /dev/null +++ b/archive/research/comparison.md @@ -0,0 +1,45 @@ +# Сравнение существующих проектов — чему учиться, а не копировать вслепую + +## Карта альтернатив + +| Проект | Ключевая идея | Чем полезен ICE-NET | Чего не решает автоматически | +|---|---|---|---| +| [Reticulum](../sources/part1.md#s13) | crypto адреса + transport-agnostic сеть | почти прямой ориентир по логическому уровню | не обещает произвольной скорости без физического канала | +| [Meshtastic](../sources/part1.md#s17) | LoRa mesh и ограничения эфира | алгоритмы flood, next-hop, airtime | не скоростная сеть фото/видео | +| [AREDN](../sources/part1.md#s24) | mesh-сеть на роутерах/радиомостах | реальная эксплуатация, multi-radio, Babel | модель адресации в основном IP-ориентированная | +| [Yggdrasil](../sources/part1.md#s19) | end-to-end encrypted overlay | self-healing и идентичность | само overlay использует IPv6 API и не создаёт радио | +| [Briar](../sources/part1.md#s18) | offline P2P мессенджер | UX без интернета, локальная privacy | не общий сетевой backhaul | +| [libp2p](../sources/part1.md#s21) | P2P transports, relay, peer discovery | инструменты для первого Rust MVP | некоторые протоколы/DHT чрезмерны для узкополосного радио | +| [Babel](../sources/part1.md#s06) | устойчивые маршруты на проводе и Wi-Fi | быстрый путь к работающей mesh-маршрутизации | зависит от модели адресов и метрик | +| [batman-adv](../sources/part1.md#s23) | L2 mesh forwarding в Linux/OpenWrt | местные Wi-Fi домены | широковещание и масштаб на огромные расстояния | +| [DTN / BPv7](../sources/part1.md#s04) | хранение-передача при разрывах | прерывистые дальние связи | живой видеозвонок без постоянного пути | +| [SCION](../sources/part1.md#s20) | path-aware, доверие и отказоустойчивость | источники идей контроля маршрутов | не ориентирован на LoRa и чисто ad-hoc клиент | +| [Wi-Fi Aware](../sources/part1.md#s27) | discovery и прямой скоростной линк | мобильное подключение без сети оператора | многопереходная маршрутизация не предоставляется сама | +| [guifi.net](../sources/part2.md#s47) | общественная физическая сеть | реальная управленческая модель | не готовый новый wire format | + +## Главное открытие исследования + +**Почти все элементы идеи уже встречаются по отдельности.** Сильная постановка задачи ICE-NET — не доказывать «первое в мире открытие», а предложить проверяемую и полезную интеграцию с понятной границей slow discovery и fast transport, строгим QoS, E2E privacy и понятным UX. + +## Что разумнее использовать, а не переписывать + +- для прототипа Rust peers/транспорты — [rust-libp2p](../sources/part1.md#s22), если размер и свойства подходят; +- для исследования радио/разрывов — [ns-3](../sources/part2.md#s42), [CORE](../sources/part2.md#s43), [GNU Radio](../sources/part2.md#s33); +- для безопасности сообщений — общепринятые криптопримитивы и стандартные схемы, не новый шифр; +- для предсказуемости в локальной Wi-Fi области — попробовать Babel/batman-adv вместо разработки маршрутизатора с нуля с первого дня. + +## Критический момент по Reticulum + +На GitHub существует публичное зеркало, сам проект явно предупреждает о большом количестве некорректных сторонних реализаций и лицензионных нарушений ([S16](../sources/part1.md#s16)). **Читать** его — хорошо; **копировать чужой код и объявлять своим** — нельзя. Если решишь делать compatible implementation, сначала изучить лицензию, истинную спецификацию и тестировать реальную интероперабельность. + +## Вопросы для сравнения протоколов + +1. Какова доля control traffic при 10 / 100 / 1000 соседних узлов? +2. Как ведёт себя маршрут при 30% packet loss? +3. Какой payload overhead на пакете 32–64 байта? +4. Обязательна ли глобальная DHT или центральный bootstrap? +5. Возможен ли store-carry-forward без активного пути? +6. Что видит промежуточный узел и что может изменить? +7. Каков размер бинарника/памяти на x86 и ARM? + +Не выбирать победителя на основе одного рекламного benchmark. diff --git a/archive/research/reading_list.md b/archive/research/reading_list.md new file mode 100644 index 0000000..85efd7c --- /dev/null +++ b/archive/research/reading_list.md @@ -0,0 +1,31 @@ +# План чтения: что изучать и в каком порядке + +## Если хочется разобраться и начать программировать + +**Сначала:** [Linux network namespaces](../sources/part2.md#s40) → [tc netem](../sources/part2.md#s41) → [Reticulum manual](../sources/part1.md#s13). Это покажет, как создать сеть и потерять пакеты на одном компьютере. + +**Адреса и маршруты:** [Reticulum understanding](../sources/part1.md#s14) → [Babel RFC](../sources/part1.md#s06) → [Meshtastic mesh algo](../sources/part1.md#s17) → [libp2p protocols](../sources/part1.md#s21). + +**Разрывы связи:** [BPv7](../sources/part1.md#s04) → [BPSec](../sources/part1.md#s05) → [DTN drafts](../sources/part1.md#s12). + +**Криптография:** [Noise](../sources/part1.md#s26) → [HPKE](../sources/part1.md#s08) → [MLS](../sources/part1.md#s07); не надо читать все RFC подряд для первой версии чата. + +**Радио:** [Meshtastic](../sources/part1.md#s17) → [LoRaWAN limitations](../sources/part2.md#s31) → [Wi-Fi Aware](../sources/part1.md#s27) → [ITU-R P.530](../sources/part2.md#s32) → [GNU Radio](../sources/part2.md#s33). + +**Сообщество:** [NYC Mesh](../sources/part2.md#s45) → [Freifunk](../sources/part2.md#s46) → [Battlemesh](../sources/part2.md#s48) → [IETF](../sources/part2.md#s58). + +## Обязательно прочитать перед формальным design review + +- [Требования](../project/foundation/requirements.md) +- [Границы слоёв](../project/foundation/architecture.md) +- [Модель угроз](../security/threat_model.md) +- [Служебные объявления](../protocol/control/discovery_control_plane.md) +- [Радиочастоты и закон](../radio/legal_spectrum.md) + +## Фактчек-лист для добавления нового источника + +1. Записать название, URL, автора/организацию, дату версии, дату просмотра. +2. Определить тип: RFC, draft, manual, эксперимент, статья, маркетинг, форум. +3. Разделить «источник сообщает» и «ICE-NET предполагает». +4. Не переписывать страницы целиком в архив: краткая аннотация + ссылка. +5. Не считать ссылку доказательством безопасной реализации. diff --git a/archive/security/crypto_privacy.md b/archive/security/crypto_privacy.md new file mode 100644 index 0000000..957c551 --- /dev/null +++ b/archive/security/crypto_privacy.md @@ -0,0 +1,35 @@ +# Криптография и приватность: проектные принципы + +## Цель + +Даже если посредники физически хранят и передают данные, они не получают ключей для чтения сообщений. При этом защита от чтения содержимого **не** равна защите от анализа метаданных. + +## Стандартные строительные блоки + +- Проверенная криптографическая библиотека, не собственный алгоритм шифрования. +- Аутентифицированный обмен ключами; исследовать [Noise](../sources/part1.md#s26). +- E2E сообщения с аутентификацией и подтверждением криптографического sender identity; варианты [HPKE](../sources/part1.md#s08) и [MLS для групп](../sources/part1.md#s07). +- DTN требует защищать **данные в очереди** (encryption at rest, TTL, квоты). Полезен [BPSec](../sources/part1.md#s05). +- Отдельный слой авторизации сервисов: корректная подпись Node ID не означает право читать «фото-ящик». + +## Приватность географии и графа контактов + +Сильный шифр не скрывает, что два устройства часто переписываются, когда передают и какой relay используют. Публикация стабильного хеша ID в каждой вышке может построить базу перемещений. План защиты: + +1. Не объявлять GPS/местоположение автоматически. +2. По умолчанию лишь ephemeral идентификаторы поиска соседей, насколько это совместимо с маршрутизацией. +3. Не строить публичные «списки присутствующих людей на вышке». +4. Хранить маршрутизаторные кэши недолго; минимизировать журналы. +5. Обсудить возможные атаки корреляцией сигнала, времени и размера пакетов. + +## Конфликт приватности и маршрутизации + +Ротация псевдонимов увеличивает цену поиска. Глобальная discoverability уменьшает privacy. Нет бесплатной магии — оценивать компромиссы отдельно для городского high-bandwidth домена и LoRa. + +## Модель доверия + +`NodeID = криптографическая идентичность`, `Contact = утверждение пользователя`, `Service permission = локальная политика`. Не смешивать эти три понятия. + +## Криптографический релиз-гейт + +Никакого публичного «100% безопасно» до независимого аудита, тестовых векторов, результатов fuzz и воспроизводимой сборки. Даже при аудите формулировать ограниченную угроз-модель. diff --git a/archive/security/ice_engine.md b/archive/security/ice_engine.md new file mode 100644 index 0000000..a0cfe5f --- /dev/null +++ b/archive/security/ice_engine.md @@ -0,0 +1,52 @@ +# ICE Guard: маленькая локальная система безопасности + +> Слово ICE вдохновлено Cyberpunk; его нужно отличать от [Interactive Connectivity Establishment (RFC 8445)](../sources/part1.md#s09). Внутреннее название **ICE Guard** пока рабочее. Система **не** атакует чужие компьютеры. + +## Цель + +Дешёвый модуль, который выполняет *проверку входящих сетевых событий* и не требует нейросети, GPU и постоянного сервера. Полезно разделить защиту на **обязательные правила** и **адаптивную оценку риска**. + +## Базовый путь решения + +```text + RX packet + │ + ├─ parser + caps → malformed? → DROP + ├─ cryptographic auth → invalid? → DROP + ├─ ACL service → denied? → DENY + ├─ anti-replay → replay? → DROP + ├─ rate limiter → over quota? → DELAY/DROP + └─ behavior telemetry → anomaly? → SCORE / REVIEW / THROTTLE + └─ allowed? → forward / deliver +``` + +## Подходящие CPU-only методы + +| Метод | Для чего | Ограничение | +|---|---|---| +| FSM | допустимые переходы состояний | фиксированные правила | +| Decision tree | быстрый предсказуемый классификатор | зависит от качества обучения | +| Байесовская модель | оценка риска по признакам | независимость признаков может быть неверной | +| EWMA/statistics | необычные потоки/скорость запросов | ошибка при смене нормального поведения | +| Token bucket | гарантированные rate caps | не распознаёт сложные угрозы | +| Exact ACL + signatures | права доступа и подлинность | требует корректной криптографии | + +## Архитектура + +- **ICE Core:** C/Rust, детерминированные проверки, лимиты байтов и CPU, фиксированные профили сервисов. +- **ICE Policy:** настройки владельца («этот сервис только контакты», «мобильная батарея не ретранслирует»). +- **ICE Learning:** необязательный офлайн-процесс: анализирует анонимизированные журналы/пометки, строит маленькое дерево и предлагает **новую версию правил**, но не включает её автоматически. + +## Важные предохранители + +1. Не блокировать доступ только из-за отклонения от статистики: false positive высоки в нестабильных радиосетях. +2. Не обучаться бесконтрольно на открытом трафике — возможно poisoning. +3. Не хранить бессрочно чужие адреса/локаторы и геопозиции. +4. Не отсылать ответные «атаки», вредоносные payload или сетевое сканирование чужих хостов. +5. Не задерживать критически важный текст ради сложной классификации: сначала дешёвые проверки и fair queue. + +## Измерять + +p95 времени проверки, CPU/пакет, память на 10k соседей, число ошибочных блокировок, устойчивость к burst, скорость восстановления честного узла, наличие удалённой возможности изменить политику без перезапуска. + +Основной RFC-подход к security для задержанной доставки см. [BPSec](../sources/part1.md#s05). Подход к рукопожатиям — [Noise](../sources/part1.md#s26). diff --git a/archive/security/threat_model.md b/archive/security/threat_model.md new file mode 100644 index 0000000..da78f91 --- /dev/null +++ b/archive/security/threat_model.md @@ -0,0 +1,41 @@ +# Модель угроз ICE-NET + +## Активы + +Закрытые ключи пользователя; сообщения и фото; metadata об участниках и маршрутах; airtime и батарея; память/диск реле; таблицы путей; контроль над сервисами. + +## Противники + +1. Пассивный наблюдатель радио: видит передачу, длительность, сигнал, даже если содержимое зашифровано. +2. Чужой relay: может задерживать, изменять, удалять пакеты, заявлять ложные маршруты. +3. Массовый участник: создаёт множество ключей (Sybil), фальшивые объявления, пытается истощить память и радиоэфир. +4. Владелец скомпрометированного конечного устройства: криптография не исправит заражённый endpoint. +5. Сбойный узел без злого умысла: дублирует пакеты, забывает state, путает время. + +## Угрозы и контроль + +| Угроза | Контроль | Остаточный риск | +|---|---|---| +| Подделка Node ID | подпись challenge, валидные ключи | адрес можно создать новый, Sybil остаётся | +| Подмена/чтение трафика relay | E2E encryption + integrity | relay видит часть metadata и может сбросить | +| Replay | уникальные packet IDs, ограниченные replay windows | при DTN окна сложнее | +| Flooding | лимиты на путь, на сервис, на анонс, bounded queues | массовая радиопомеха всё ещё возможна | +| Poisoned route | ограниченная область доверия, независимая проверка метрик | злой relay всё ещё может blackhole | +| Перехват имени | проверка fingerprint out-of-band | человек может ошибиться | +| Слежка по стабильным beacon | ротируемые псевдонимы, минимальные анонсы | анализ трафика остаётся | +| Зависимость от большого хаба | несколько peers / маршрутов и DTN | при отсутствии всех путей связь невозможна | + +## Правила реагирования + +**Разрешённые локальные действия ICE:** DROP, THROTTLE, REQUIRE-AUTH, QUARANTINE LOCAL SESSION, REVOKE KEY, REPORT LOCAL LOG. +**Не предусмотрены:** встречный взлом, повреждение чужих устройств, перехват управления чужим маршрутизатором. + +## Проверки безопасности + +- Fuzz всего парсера и сериализатора. +- Verify under traffic load + malicious input. +- Verify authenticated header binding: не оставлять опасные неаутентифицированные поля. +- Replay/drop/reorder и несинхронные часы в тестовой среде. +- Процедура security disclosure и отдельная политика хранения секретов. + +См. [ICE Guard](ice_engine.md), [privacy & crypto](crypto_privacy.md), [BPSec RFC 9172](../sources/part1.md#s05). diff --git a/archive/sources/part1.md b/archive/sources/part1.md new file mode 100644 index 0000000..51d9198 --- /dev/null +++ b/archive/sources/part1.md @@ -0,0 +1,131 @@ +# Каталог источников ICE-NET + +> Проверка материалов: **12 ноября 2026**. Источники собраны выборочно из доступной публичной документации и актуальных веб-страниц; это **не** систематический обзор всего интернета. Дата обновления отдельных сайтов может меняться, поэтому для проектных решений открывай оригинал. RFC и утверждённые стандарты отделены от черновиков, маркетинга и идей. +> +> Ссылки в файлах вида `[S12](part1.md#s12)` ведут сюда. Страницы пронумерованы для воспроизводимости обзора. + +## Стандарты, RFC, IETF + +## S01 — TCP, RFC 9293 (стандарт, 2022) +https://www.rfc-editor.org/info/rfc9293/ +16-битные поля source/destination port. Справка о том, почему обычный TCP-порт 77777 невозможен. + +## S02 — QUIC, RFC 9000 (Proposed Standard, 2021) +https://www.rfc-editor.org/info/rfc9000/ +Потоки, миграция соединения, защита данных в транспорте. + +## S03 — Multipath QUIC, RFC 10069 (Proposed Standard, **ноябрь 2026**) +https://www.rfc-editor.org/info/rfc10069/ +Новый стандарт расширения QUIC с несколькими путями. Это **не** готовая маршрутизация mesh-сети и не обнаружение узлов. + +## S04 — Bundle Protocol Version 7, RFC 9171 (Proposed Standard, 2022) +https://www.rfc-editor.org/info/rfc9171/ +Store-carry-forward при длительных задержках и разрывах связи. + +## S05 — Bundle Protocol Security, RFC 9172 (Proposed Standard, 2022) +https://www.rfc-editor.org/info/rfc9172/ +Целостность и конфиденциальность DTN-пакетов. + +## S06 — Babel, RFC 8966 (Proposed Standard, 2021) +https://www.rfc-editor.org/info/rfc8966/ +Маршрутизация в нестабильных и беспроводных mesh-сетях. + +## S07 — MLS, RFC 9420 (Proposed Standard, 2023) +https://www.rfc-editor.org/info/rfc9420/ +Управление ключами групповых сообщений, не готовый сетевой стек. + +## S08 — HPKE, RFC 9180 (Informational, 2022) +https://www.rfc-editor.org/info/rfc9180/ +Строительные блоки шифрования для получателя. + +## S09 — ICE/NAT traversal, RFC 8445 (Proposed Standard, 2018) +https://www.rfc-editor.org/info/rfc8445/ +Важно: стандартное название **ICE** уже занято протоколом Interactive Connectivity Establishment. Название «ICE Security» в проекте — временное. + +## S10 — IETF MANET, рабочая группа +https://datatracker.ietf.org/wg/manet/about/ +Активное сообщество по мобильным самоорганизующимся сетям, публичная рассылка и Zulip. + +## S11 — IETF DTN, рабочая группа (устав обновлён 5 октября 2026) +https://datatracker.ietf.org/doc/charter-ietf-dtn/ +Продолжается работа над сетями с переменной доступностью. + +## S12 — Активные документы IETF DTN (снимок на ноябрь 2026) +https://datatracker.ietf.org/group/dtn/documents/ +Содержит Internet-Drafts, в том числе соседское обнаружение, однонаправленную передачу, QUIC convergence layer. **Черновик — не RFC и не законченный стандарт.** + +## Сетевые стеки и реализация + +## S13 — Reticulum, официальный manual (наблюдалась документация 1.6.0) +https://reticulum.network/manual/ +Архитектура, криптографические адреса, интерфейсы, транспорт и ограничения. + +## S14 — Reticulum: understanding и announce +https://reticulum.network/manual/understanding.html +Обнаружение направлений и ограничение служебного радиоэфира. + +## S15 — Reticulum: building networks +https://reticulum.network/manual/networks.html +Смешивание LoRa/радиосвязи, Ethernet, туннелей и промежуточных узлов. + +## S16 — Reticulum: публичное зеркало репозитория +https://github.com/markqvist/Reticulum +**Осторожно:** зеркало не основной канал разработки. Прочитать предупреждение об ошибочных сторонних реализациях и лицензии перед повторным использованием кода. + +## S17 — Meshtastic: официальный алгоритм mesh +https://meshtastic.org/docs/overview/mesh-algo/ +Ограничение эфира, managed flooding, next-hop для прямых сообщений начиная с версии 2.6. + +## S18 — Briar, официальный проект (релиз 1.5.24 от 30 октября 2026 на сайте) +https://briarproject.org/ +Децентрализованная переписка поверх Bluetooth, Wi-Fi и Tor; не универсальный радиомаршрутизатор. + +## S19 — Yggdrasil Network +https://yggdrasilnetwork.org/ +Шифрованная P2P-сеть с IPv6-адресами в overlay. Экспериментальный проект, не отсутствие IP во всех слоях. + +## S20 — SCION, официальная документация +https://docs.scion.org/en/latest/ +Междоменные пути, доверие, изоляция отказов; ориентирован на другую среду, чем LoRa. + +## S21 — libp2p: protocol docs +https://libp2p.io/docs/protocols/ +Peer ID, discovery/DHT и relays; применимость к интернет-оверлею, а не непосредственная магистраль для 300 бит/с. + +## S22 — Rust libp2p, репозиторий и связи с сообществом +https://github.com/libp2p/rust-libp2p +GitHub Discussions и libp2p Discourse. + +## S23 — batman-adv/OpenWrt +https://openwrt.org/docs/guide-user/network/wifi/mesh/batman +Реальная L2 mesh-маршрутизация, осторожно с broadcast и масштабом. + +## S24 — AREDN, официальный проект (в октябре 2026 описан релиз 4.26.10.0) +https://www.arednmesh.org/ +Практический опыт аварийных радиосетей, перехода на Babel и разных типов узлов. + +## S25 — AREDN и поддержка 802.11ah (2025) +https://www.arednmesh.org/content/aredn-release-325100-80211ah-support +Реальный пример использования HaLow, а не гарантия поддержки любым телефоном. + +## S26 — Noise Protocol Framework +https://noiseprotocol.org/ +Шаблоны рукопожатий и свойства шифрования. Не нужно самостоятельно изобретать криптографию. + +## Физические технологии и радио + +## S27 — Wi-Fi Aware, AOSP (страница обновлена в 2026) +https://source.android.com/docs/core/connect/wifi-aware +Обнаружение устройств напрямую без интернета, на поддерживаемых Android-устройствах. + +## S28 — Wi-Fi Aware, Android API +https://developer.android.com/develop/connectivity/wifi/wifi-aware +Ограничения аппаратной поддержки и API. + +## S29 — Wi-Fi 7 MLO, Android/AOSP +https://source.android.com/docs/core/connect/wifi-7 +Multi-Link Operation — несколько физических Wi-Fi линков; **не** автоматическая межгородская mesh-маршрутизация. + +## S30 — WBA: полевые испытания Wi-Fi 7 MLO (февраль 2026) +https://wballiance.com/wba-validates-wifi-7-mlo-reliability-cablelabs-intel/ +Результаты испытаний в жилой среде, не универсальная гарантия скорости для ICE-NET. diff --git a/archive/sources/part2.md b/archive/sources/part2.md new file mode 100644 index 0000000..794295c --- /dev/null +++ b/archive/sources/part2.md @@ -0,0 +1,136 @@ +# Каталог источников ICE-NET — продолжение (S31–S60) + +## S31 — LoRaWAN: практические ограничения, The Things Network +https://www.thethingsnetwork.org/docs/lorawan/limitations/ +Низкая скорость и airtime. **LoRa PHY и LoRaWAN не одно и то же**; цифры этой страницы относятся к LoRaWAN. + +## S32 — ITU-R P.530-19 (утверждён сентябрь 2025) +https://www.itu.int/rec/R-REC-P.530-19-202509-I/en +Расчёт радиорелейных линий прямой видимости с учётом дождя, многолучёвости и отказов. + +## S33 — GNU Radio, проект и симуляция без SDR-железа +https://www.gnuradio.org/about/ +Разработка сигналов и модуляции; можно использовать без радиооборудования. + +## S34 — GNU Radio 4.0 RC3 (13 октября 2026) +https://www.gnuradio.org/news/2026-10-13-gr4-rc3-release/ +Активное развитие SDR-экосистемы, **релиз-кандидат**. + +## S35 — AREDN release notes в GitHub (обновления 2026) +https://github.com/aredn/aredn/blob/main/RELEASE_NOTES.md +Пример практики совмещения OpenWrt, Wi-Fi, HaLow, Babel и туннелей. + +## Регулирование + +## S36 — CEPT/EFIS, реестр условий SRD +https://efis.cept.org/sitecontent.jsp?sitecontent=srd_regulations +Условия зависят от диапазона, страны, мощности, назначения и класса устройства. Проверять непосредственно перед испытаниями. + +## S37 — ERC/REC 70-03, документация регуляторов CEPT +https://docdb.cept.org/document/845 +История обновлений, национальные ограничения; выпуски 2026, сверить с EFIS. + +## S38 — Директива ЕС 2014/53/EU (RED) +https://eur-lex.europa.eu/eli/dir/2014/53/oj/eng +Радиооборудование, соответствие требованиям при выводе оборудования на рынок ЕС. + +## S39 — Еврокомиссия: RED и изменения 2026 +https://single-market-economy.ec.europa.eu/sectors/electrical-and-electronic-engineering-industries-eei/radio-equipment-directive-red_en +Правовой статус новых актов; упомянута отмена отдельного акта по кибербезопасности RED с переходом к CRA. + +## Эмуляция и тестирование + +## S40 — Linux network namespaces, man7 +https://man7.org/linux/man-pages/man7/network_namespaces.7.html +Изоляция сетевых устройств и таблиц маршрутизации в одном Linux. + +## S41 — Linux tc-netem, man7 +https://linuxman7.org/linux/man-pages/man8/tc-netem.8.html +Имитация задержки, потерь, переупорядочивания, ограничения скорости. + +## S42 — ns-3 simulator, official docs +https://www2.nsnam.org/documentation/ +Дискретно-событийная модель; для исследования радиосети. + +## S43 — CORE Network Emulator +https://github.com/coreemu/core +Эмуляция множества узлов и реального сетевого ПО. + +## S44 — Mininet +https://mininet.org/ +Виртуальные сети на одном компьютере, удобны для первоначального тестирования логики. + +## Люди и сообщества, где реально можно искать участников + +## S45 — NYC Mesh: волонтёры и удалённые разработчики +https://www.nycmesh.net/help +Публичные способы участия; удалённый софт и документация возможны. + +## S46 — Freifunk: вступление и создание сообщества +https://freifunk.net/en/how-to-join/ +Сети с местными сообществами, разработчики и инфраструктура. + +## S47 — guifi.net: общие телекоммуникационные сети +https://network.guifi.net/ +Модель совместного владения и эксплуатации инфраструктуры. + +## S48 — Wireless Battle of the Mesh +https://www.battlemesh.org/HomePage +Встречи разработчиков wireless mesh и OpenWrt. Мероприятие 2026 состоялось 7–13 сентября. + +## S49 — Battlemesh v18: архив мероприятия 2026 +https://www.battlemesh.org/BattleMeshV18 +Записи, участники, темы и организаторы; не выдавать прошлое событие за предстоящее. + +## S50 — Reddit r/meshtastic +https://www.reddit.com/r/meshtastic/ +Реальная активность и практическое оборудование/сети. + +## S51 — Reddit r/darknetplan +https://www.reddit.com/r/darknetplan/ +Идеи о независимых mesh-сетях. Качество обсуждений неоднородно. + +## S52 — Reddit r/amateurradio +https://www.reddit.com/r/amateurradio/ +Радиочастоты, антенны, лицензии, реальные ограничения. + +## S53 — Reddit r/selfhosted +https://www.reddit.com/r/selfhosted/ +Локальные сервисы, эксплуатация, самохостинг и автономность. + +## S54 — Reddit r/Lora +https://www.reddit.com/r/LoRa/ +Датчики, модемы и практические радиопросчёты. + +## S55 — Reddit r/ReticulumNetwork +https://www.reddit.com/r/ReticulumNetwork/ +Сообщество существует, но на дату проверки **не имело публикаций**; плохая основная площадка для поиска команды. + +## S56 — Reddit r/Meshnet +https://www.reddit.com/r/meshnet/ +Существует, но много бытовых тем о домашних Wi-Fi mesh-системах; не основной форум для нового сетевого протокола. + +## S57 — FSO: исследование надёжности оптической связи при тумане (ноябрь 2026) +https://www.mdpi.com/2304-6732/13/11/1013 +Исследовательская статья; реальные выводы о погодной чувствительности FSO, не подтверждение конкретной будущей системы. + +## S58 — IETF: списки рассылок +https://www.ietf.org/participate/lists/wg-lists/ +Как участвовать: изучить документы и архив обсуждений до публикации идей. + +## S59 — Apple Developer Wi-Fi Aware +https://developer.apple.com/documentation/WiFiAware +Фреймворк для поддерживаемых устройств и сценариев, не гарантия поддержки всей линейки. + +## S60 — libp2p 0.57.1 (15 октября 2026) +https://docs.rs/crate/libp2p/latest +Конкретный пример активного Rust SDK, версия быстро устаревает. + +--- + +### Как использовать источники + +1. RFC/документация проекта → факты об уже существующих протоколах. +2. Исследовательская статья → гипотеза, модель, ограниченная экспериментальная область. +3. Форум/Reddit → практические отзывы и приглашения к обсуждению, **не** доказательство технических характеристик. +4. Дизайн ICE-NET ниже → **авторская проектная гипотеза**, пока не стандарт и не реальная работающая сеть. diff --git a/docs/INDEX.md b/docs/INDEX.md new file mode 100644 index 0000000..3994c6e --- /dev/null +++ b/docs/INDEX.md @@ -0,0 +1,84 @@ +# Индекс ICE-NET + +Все Markdown-документы проекта. Цифры и состояние — только в [STATUS.md](STATUS.md). + +## Корень + +- [README.md](../README.md) +- [RULES.md](../RULES.md) +- [TODO.md](../TODO.md) + +## Актуальные документы + +- [docs/INDEX.md](../docs/INDEX.md) +- [docs/SOURCES.md](../docs/SOURCES.md) +- [docs/STATUS.md](../docs/STATUS.md) +- [docs/architecture/contracts.md](../docs/architecture/contracts.md) +- [docs/architecture/crates.md](../docs/architecture/crates.md) +- [docs/architecture/decisions.md](../docs/architecture/decisions.md) +- [docs/architecture/overview.md](../docs/architecture/overview.md) +- [docs/build/dependencies.md](../docs/build/dependencies.md) +- [docs/build/slint_license.md](../docs/build/slint_license.md) +- [docs/community/announcement_en.md](../docs/community/announcement_en.md) +- [docs/community/announcement_ru.md](../docs/community/announcement_ru.md) +- [docs/guides/commands.md](../docs/guides/commands.md) +- [docs/guides/contributing.md](../docs/guides/contributing.md) +- [docs/guides/quickstart.md](../docs/guides/quickstart.md) +- [docs/guides/testing.md](../docs/guides/testing.md) +- [docs/research/gaps.md](../docs/research/gaps.md) +- [docs/research/licensing.md](../docs/research/licensing.md) +- [docs/research/meshtastic.md](../docs/research/meshtastic.md) +- [docs/research/reticulum.md](../docs/research/reticulum.md) +- [docs/review/questions.md](../docs/review/questions.md) +- [docs/review/revision.md](../docs/review/revision.md) +- [docs/review/rf_notes.md](../docs/review/rf_notes.md) +- [docs/security/guard.md](../docs/security/guard.md) +- [docs/security/privacy.md](../docs/security/privacy.md) +- [docs/simulator/city_editor.md](../docs/simulator/city_editor.md) +- [docs/simulator/event_model.md](../docs/simulator/event_model.md) +- [docs/simulator/metrics.md](../docs/simulator/metrics.md) +- [docs/simulator/scenarios.md](../docs/simulator/scenarios.md) + +## Workspace + +- [workspace/README.md](../workspace/README.md) + +## Архив исследования 0.1 + +- [archive/README.md](../archive/README.md) +- [archive/README_0.1.md](../archive/README_0.1.md) +- [archive/START_HERE_0.1.md](../archive/START_HERE_0.1.md) +- [archive/build/migration_egui_to_slint.md](../archive/build/migration_egui_to_slint.md) +- [archive/community/call_for_collaborators.md](../archive/community/call_for_collaborators.md) +- [archive/community/projects_people.md](../archive/community/projects_people.md) +- [archive/community/reddit_strategy.md](../archive/community/reddit_strategy.md) +- [archive/docs/changelog.md](../archive/docs/changelog.md) +- [archive/docs/future_questions.md](../archive/docs/future_questions.md) +- [archive/docs/glossary.md](../archive/docs/glossary.md) +- [archive/implementation/mvp_zero_budget.md](../archive/implementation/mvp_zero_budget.md) +- [archive/implementation/roadmap.md](../archive/implementation/roadmap.md) +- [archive/implementation/simulation.md](../archive/implementation/simulation.md) +- [archive/implementation/tests_metrics.md](../archive/implementation/tests_metrics.md) +- [archive/project/foundation/architecture.md](../archive/project/foundation/architecture.md) +- [archive/project/foundation/requirements.md](../archive/project/foundation/requirements.md) +- [archive/project/foundation/vision.md](../archive/project/foundation/vision.md) +- [archive/project/governance/decisions.md](../archive/project/governance/decisions.md) +- [archive/project/governance/risks.md](../archive/project/governance/risks.md) +- [archive/protocol/control/discovery_control_plane.md](../archive/protocol/control/discovery_control_plane.md) +- [archive/protocol/control/routing.md](../archive/protocol/control/routing.md) +- [archive/protocol/control/transport_qos.md](../archive/protocol/control/transport_qos.md) +- [archive/protocol/foundation/identities_addresses.md](../archive/protocol/foundation/identities_addresses.md) +- [archive/protocol/foundation/overview.md](../archive/protocol/foundation/overview.md) +- [archive/protocol/foundation/packet_wire_format.md](../archive/protocol/foundation/packet_wire_format.md) +- [archive/protocol/store/storage_dtn.md](../archive/protocol/store/storage_dtn.md) +- [archive/radio/backhaul_city_deployment.md](../archive/radio/backhaul_city_deployment.md) +- [archive/radio/legal_spectrum.md](../archive/radio/legal_spectrum.md) +- [archive/radio/physical_links.md](../archive/radio/physical_links.md) +- [archive/research/2025_2026_updates.md](../archive/research/2025_2026_updates.md) +- [archive/research/comparison.md](../archive/research/comparison.md) +- [archive/research/reading_list.md](../archive/research/reading_list.md) +- [archive/security/crypto_privacy.md](../archive/security/crypto_privacy.md) +- [archive/security/ice_engine.md](../archive/security/ice_engine.md) +- [archive/security/threat_model.md](../archive/security/threat_model.md) +- [archive/sources/part1.md](../archive/sources/part1.md) +- [archive/sources/part2.md](../archive/sources/part2.md) diff --git a/docs/SOURCES.md b/docs/SOURCES.md new file mode 100644 index 0000000..e19f483 --- /dev/null +++ b/docs/SOURCES.md @@ -0,0 +1,38 @@ +# Источники ICE-NET (срез 12.11.2026, дополнено 13.11.2026) + +Список ссылок на **первичные** документы и каталоги. Это источники фактов, +не разрешение на копирование исходников. Архивные 60 источников — +[часть 1](../archive/sources/part1.md) и [часть 2](../archive/sources/part2.md). + +| ID | Назначение | Первоисточник | +|---|---|---| +| N01 | Reticulum: полная текущая документация (1.6.0) | https://reticulum.network/manual/ | +| N02 | Reticulum: интерфейсы, обнаружение, rate limits | https://reticulum.network/manual/interfaces.html | +| N03 | Reticulum: transport nodes и разнородные среды | https://reticulum.network/manual/networks.html | +| N04 | Reticulum: FIFO для обычного трафика | https://reticulum.network/manual/understanding.html | +| N05 | Reticulum: лицензия и ограничения | https://github.com/markqvist/Reticulum/blob/master/LICENSE | +| N06 | Reticulum: код и происхождение, предупреждения | https://github.com/markqvist/Reticulum | +| N07 | Meshtastic: broadcast & next-hop | https://meshtastic.org/docs/overview/mesh-algo/ | +| N08 | Meshtastic: firmware и версии, включая prerelease | https://github.com/meshtastic/firmware/releases | +| N09 | Meshtastic: лицензии и компоненты | https://github.com/meshtastic | +| N10 | Cargo workspaces | https://doc.rust-lang.org/cargo/reference/workspaces.html | +| N11 | Rust 2024 resolver v3 | https://doc.rust-lang.org/stable/edition-guide/rust-2024/cargo-resolver.html | +| N12 | Отдельные integration tests | https://doc.rust-lang.org/stable/cargo/reference/cargo-targets.html | +| N13 | _снято_: eframe/egui (GUI заменён на Slint в v0.3) | — | +| N14 | _снято_: egui MSRV | — | +| N15 | Симуляция и отличие от реального RF (ns-3) | https://www.nsnam.org/ | +| N16 | Wi-Fi Aware (Apple) | https://developer.apple.com/documentation/wifiaware | + +**Ограничения:** страницы с latest могут изменяться после даты среза; +нужен `Cargo.lock` и регулярная повторная проверка лицензий. Выписанные факты +из [внешней ревизии](review/revision.md) отмечены отдельно от нового поиска. + +## Дополнение: Slint и экосистема + +- [Slint 1.18.1 Rust API](https://docs.slint.dev/latest/docs/rust/slint/) — интеграция Rust с компилируемым `.slint`. +- [Флаги Slint](https://docs.slint.dev/latest/docs/rust/slint/docs/cargo_features/) — управление backend/renderer. +- [Slint Winit backend](https://docs.slint.dev/latest/docs/slint/guide/backends-and-renderers/backend_winit/) — desktop Linux/X11/Wayland. +- [Slint TouchArea](https://docs.slint.dev/latest/docs/slint/reference/gestures/toucharea/) — drag без сторонней библиотеки. +- [Slint license](https://github.com/slint-ui/slint/blob/master/LICENSE.md) — GPLv3 / royalty-free / commercial. +- [Slint crate v1.18.1](https://docs.rs/crate/slint/1.18.1/source/Cargo.toml) — MSRV 1.92. +- [GNU LGPL v3](https://www.gnu.org/licenses/lgpl-3.0.html) и [GPL v3](https://www.gnu.org/licenses/gpl-3.0.html) — лицензия кода ICE-NET. diff --git a/docs/STATUS.md b/docs/STATUS.md new file mode 100644 index 0000000..5a1e9cd --- /dev/null +++ b/docs/STATUS.md @@ -0,0 +1,67 @@ +# Статус ICE-NET (единственный источник цифр) + +Все остальные документы **ссылаются сюда** и не повторяют числа. Меняешь код — +обнови только этот файл. Дата последней сверки: **13 ноября 2026**. + +## Окружение и лицензия + +| Параметр | Значение | +| --- | --- | +| Toolchain | Rust 1.95.0 (`workspace/rust-toolchain.toml`), Edition 2024, resolver 3 | +| Crates workspace | 7 библиотек + 2 приложения (`icenetd`, `icenet-city`) | +| Лицензия кода | **LGPL-3.0-or-later** (`LICENSE`, `LICENSES/GPL-3.0.txt`), см. ADR-010 | +| GUI-зависимость | Slint 1.18.1 (отдельная лицензионная проверка, [slint_license.md](build/slint_license.md)) | +| Git | репозиторий инициализирован; коммитов пока нет | + +## Что проверено (в этой сессии) + +| Проверка | Результат | +| --- | --- | +| `python3 tools/check_layout.py` | PASS (≤250 строк, ≤4 файла на каталог) | +| `cargo fmt --all -- --check` | чисто | +| `cargo clippy --workspace --all-targets -- -D warnings` | чисто | +| `cargo test --workspace` | **91 тест, 0 падений** (в v0.3 было 77) | +| Записей в `Cargo.lock` | 523 (не равно числу скомпилированных crates) | +| Поиск маршрута, сетка 1000 узлов, 200 запросов, **debug** | p50 ≈ 6.3 мс, p95 ≈ 8.4 мс (**реальное** время CPU, не симулированное) | + +Не перепроверялось в этой сессии и взято из записей 12.11.2026: ручной прогон GUI под +X11/Xvfb (клики, drag, экспорт), RSS GUI ≈ 55 МБ (debug), `cargo build --release` +`icenet-city` ≈ 2m27s и 18 МБ без strip. Wayland не проверялся. Сравнение с egui +невозможно: старого проекта и lock-файла нет. + +## Что реализовано, а что нет + +| Область | Состояние | +| --- | --- | +| Классы трафика, запрет Bulk на slow radio | Есть. Класс **выводится из размера** (`effective_for`): Control ≤ 256 Б, Text ≤ 4096 Б, иначе Bulk | +| Выбор пути | Dijkstra с детерминированным tie-break; возвращает индексы линков | +| Ёмкость линка | Есть: один линк — одна передача, слоты эфира, очередь на ребре, бэклог и airtime | +| Статусы | `Queued`, `InFlight`, `Delivered`, `Expired`; ложный `Delivered` при обрыве маршрута исправлен | +| TTL / EXPIRED | Есть | +| Store-and-forward | **Нет**: сообщение лежит в общем списке, не на узле; нет квот и store-carry | +| Случайность / `seed` | **Нет**: детерминизм обеспечен отсутствием случайности | +| Служебный (control) трафик | **Не генерируется**: announce/discovery не моделируются | +| Wire-формат | Черновик без криптографии, без fragmentation | +| ICE Guard | ACL, размер, очередь, replay window, token bucket; `authenticated` — тестовый флаг | +| Транспорт | `MemoryTransport` и неблокирующий `UdpTransport` (loopback) | +| Криптография, handshake, ключи | Нет | +| Реальное радио, RF-модель | Нет | + +## Статус гипотез + +| Гипотеза | Статус | +| --- | --- | +| H1: bulk не занимает airtime slow radio | Обеспечена фильтром маршрутизации и размером; тесты проходят, но это **инвариант кода**, а не научный результат. Измеряется `slow_radio_airtime_ms` | +| H2: короткий текст доходит по единственному slow-пути | Теперь проверяема (есть ёмкость, задержка растёт с очередью). Нагрузочных экспериментов ещё не было | +| H3: нет ложного `DELIVERED` | Исправлено и покрыто регрессионными тестами (`tests/city.rs`) | +| H4: контрольный airtime при 100→1000 узлов | **Не проверяема**: нет генератора служебного трафика | + +## Известные ограничения симулятора + +- Маршрутизация — оракул: видит весь граф бесплатно; стоимость пути не учитывает бэклог. +- Перепланирование начинает передачу заново с источника; уже потраченный airtime не возвращается. +- `first_route_ms` — **абсолютная** метка симулированного времени, не задержка от создания. +- Нет потерь, коллизий, скрытых терминалов, duty cycle и MAC; очередь — по порядку резервирования. +- Число в `demo_bps` — иллюстрация, не измерение железа. + +Планы и чек-листы: [TODO.md](../TODO.md). diff --git a/docs/architecture/contracts.md b/docs/architecture/contracts.md new file mode 100644 index 0000000..67b3077 --- /dev/null +++ b/docs/architecture/contracts.md @@ -0,0 +1,44 @@ +# Первые контракты и определения + +## Какие ID какие + +- `NodeId` **реальной сети** в `icenet-core` пока представлен `u64` исключительно для каркаса. Это НЕ криптографическая идентичность! +- `SimNodeId` по сути тот же тестовый ID. В будущем: стабильный fingerprint публичного ключа и отдельный DeviceID. +- `ServiceId(u64)` — логический номер сервиса, не ОС-порт и не гарантия уникальности без схемы namespace. +- `LinkKind::{SlowRadio, FastWireless, Wired, Internet}` — профили симуляции, не протоколы передачи по воздуху. + +## Классы + +- `Control`: объявления/короткие служебные данные, минимальный payload. +- `Text`: малый payload (≤ 4096 Б), в исключительных случаях допустима передача по slow radio. +- `Bulk`: файлы/фото, `SlowRadio` запрещён независимо от скорости маршрута. +- Класс **выводится из размера**: `effective_for(bytes)` повышает Control > 256 Б до Text, Text > 4096 Б до + Bulk; `Bulk` не уменьшается. Метка отправителя не даёт доступа к slow radio. + +## Маршрут + +- `choose_path` возвращает последовательность NodeId, индексы использованных линков и приблизительную + задержку сериализации **без очереди**. +- Каждый переход проверяется на `enabled`, разрешённый класс, throughput > 0. +- Для сравнимости первые измерения: dijkstra с deterministic tie-break, затем baseline shortest hops. +- Нельзя автоматически считать `route_found` равным `delivered`. +- Линк несёт одну передачу за раз: время прибытия включает ожидание слота. `Delivered` ставится + только если маршрут (узлы, линки, класс) ещё пригоден на момент `tick`. +- У сообщения есть `created_ms`/`expires_ms`; истёкшее сообщение переходит в `Expired` + и не оживает. Прибытие не позже `expires_ms` считается доставкой. +- CSV/JSON экспорт детерминирован и не использует системные часы. + +## Сетевой пакет (черновик) + +`magic | version | class | service_id | payload_len | bytes`. + +- Пример без криптографии, без anti-replay, без fragmentation. +- Отдельный парсер ограничивает длину входящих байтов и возвращает `Result`. +- В продакшене формат нужно будет изменить после threat modeling и test vectors. + +## Результат безопасности + +- `Permit`, `Deny(reason)`; без "strike back". +- `Deny` не расходует replay/rate state; `sequence` фиксируется только после `Permit`. +- Входной `authenticated: bool` в scaffold — только тестовый флаг, + **не криптографическая проверка**. diff --git a/docs/architecture/crates.md b/docs/architecture/crates.md new file mode 100644 index 0000000..841e35a --- /dev/null +++ b/docs/architecture/crates.md @@ -0,0 +1,47 @@ +# Cargo workspace: границы крейтов + +| Crate | Ответственность | Кому может зависеть | +|---|---|---| +| `icenet-core` | типы идентификаторов, класс сообщения, среда | стандартная библиотека | +| `icenet-wire` | framing + парсер *чернового* пакета | core | +| `icenet-guard` | детерминированные ACL, размер, очередь, replay, rate (без crypto) | core | +| `icenet-routing` | выбор допустимого пути на графе, индексы линков | core | +| `icenet-transport` | интерфейс отправки байтов, memory + UDP адаптеры | core | +| `icenet-sim` | виртуальное время, узлы, ёмкость линков, сценарии, метрики | core, routing | +| `icenet-sdk` | будущий публичный фасад API | core, wire, guard, transport | +| `icenetd` | CLI и UDP `serve`/`send-udp`; позже daemon | sdk, sim | +| `icenet-city` | GUI-карта и контроллер сценариев | sim, core, Slint | + +## Принципы границ + +- Ни один core crate не зависит от `Slint`, Tokio, Linux, Wi-Fi или LoRa. +- Sim **не** использует `icenetd`; GUI **не** содержит алгоритма маршрутизации. +- SDK является библиотекой встраивания, а daemon и GUI — клиентами публичных интерфейсов. +- Адаптеры настоящего радио добавятся **после** тестов в симуляторе и решения ADR. +- Защиту и типы не дублировать в GUI: дополнять tests на границе библиотеки. + +## Почему не 20 crates + +SOLID — не повод усложнять сборку. Переносим модуль в crate, если есть отдельная +ответственность, тестируемый контракт или платформенная граница. Сейчас есть +7 библиотек и 2 приложения, почти все минимальные. + +## Программируемые интерфейсы + +- `Transport::send(bytes)`, `Transport::recv()` — реальные bytes, не UI-события. +- `choose_path(nodes, links, source, destination, class, size)` — чистая функция. +- `City::send(...)`, `City::tick(delta_ms)`, `City::set_link_enabled(...)`, `City::link_airtime_ms(kind)` — контролируемая модель. +- `Guard::check(context)` — решение доступа, не ответная атака. +- `icenetd route|send|sim|policy|wire-*` — headless-проверка этих контрактов. + +Детали: [API-контракты](contracts.md) и [симулятор](../simulator/city_editor.md). + +## Зависимости и границы UI + +`icenet-city` — только адаптер интерфейса. Slint UI в `ui/main.slint`; +`src/state.rs` изменяет `City`; `src/view.rs` конвертирует данные в модели; +`src/main.rs` подключает callbacks. В остальные crates не импортируется Slint. + +Все 7 библиотек намеренно разделены по обязанностям, **все без внешних crates** (числа — в [STATUS](../STATUS.md)). +Если эти границы перестанут приносить пользу, нужно объединить crates по ADR, +а не бездумно делить ещё мельче. См. [аудит](../build/dependencies.md). diff --git a/docs/architecture/decisions.md b/docs/architecture/decisions.md new file mode 100644 index 0000000..f728806 --- /dev/null +++ b/docs/architecture/decisions.md @@ -0,0 +1,48 @@ +# ADR register + +| ADR | Решение | Статус | +|---|---|---| +| ADR-001 | Userland Rust вместо Linux kernel fork | Принято для MVP | +| ADR-002 | Slow control / fast bulk policy | Принято как **гипотеза** | +| ADR-003 | Rust workspace + отдельные integration tests | Принято | +| ADR-004 | Город — графовая DES-модель, не RF-доказательство | Принято | +| ADR-005 | Slint 1.18.1 + software renderer для native GUI (egui удалён) | Принято в v0.3 | +| ADR-006 | Реальная криптография, wire-format, физические драйверы | Открыто | +| ADR-007 | Свой полноценный протокол или адаптер к Reticulum | Открыто до экспериментов | +| ADR-008 | Общая идентичность человека на нескольких устройствах | Открыто | +| ADR-009 | TTL и явное состояние `EXPIRED` для недоставленных сообщений | Принято в v0.3 | +| ADR-010 | Лицензия собственного кода: LGPL-3.0-or-later | Принято (автор проекта) | +| ADR-011 | Класс трафика выводится из размера, метка не доверена | Принято в v0.4 | +| ADR-012 | Ёмкость линка: слоты эфира с владельцем, очередь на ребре | Принято в v0.4 | + +## Для каждого нового ADR + +Описание контекста → альтернативы → причины выбора → проверяемые последствия → риски → срок ревизии. + +Запрещено объявлять открытые ADR реализованными в README. + +## ADR-010 · Лицензия: LGPL-3.0-or-later + +- **Контекст:** автор выбрал LGPL; репозиторий не имел лицензии. +- **Решение:** LGPL-3.0-or-later; тексты в `LICENSE` и `LICENSES/GPL-3.0.txt` (LGPL v3 опирается на GPL v3). +- **Альтернативы:** LGPL-2.1 (несовместима с GPLv3-only), MIT/Apache (не выбраны автором). +- **Последствия:** Rust линкует crates статически; при распространении бинарника с LGPL-кодом нужно + дать получателю возможность пересобрать его с изменённой библиотекой (исходники или объектные файлы). + Комбинация с Slint по GPLv3 даёт GPLv3 для бинарника GUI. Юристом не проверялось. +- **Ревизия:** до первой публикации бинарников. + +## ADR-011 · Класс по размеру + +- **Контекст:** метка `Text` на 5 МБ проходила по slow radio: класс заявлял отправитель. +- **Решение:** `TrafficClass::effective_for(bytes)`: Control > 256 Б → Text, Text > 4096 Б → Bulk; + `Bulk` не уменьшается. Применяется внутри `choose_path`, поэтому защищает всех вызывающих. +- **Последствия:** лимит Text совпадает с лимитом payload wire-кадра; пороги условные, их надо + подтвердить airtime-расчётом для реального радио (ADR-006). + +## ADR-012 · Ёмкость линка + +- **Контекст:** линк пропускал любое число сообщений параллельно, поэтому S4/H2/H4 были пустыми. +- **Решение:** на каждом линке календарь слотов; слот принадлежит сообщению; перепланирование + освобождает ещё не начатые слоты. Время передачи — `transfer_ms + HOP_OVERHEAD_MS` на hop. +- **Последствия:** задержка растёт с очередью, TTL может истечь из-за бэклога. Выбор пути пока не + учитывает бэклог, перепланирование начинает с источника — это записано как ограничение. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md new file mode 100644 index 0000000..a745e61 --- /dev/null +++ b/docs/architecture/overview.md @@ -0,0 +1,44 @@ +# Актуальная архитектура ICE-NET + +## Инварианты + +1. `NodeID` — стабильная криптографическая идентичность (будущая), не IP и не физическая координата. +2. `ServiceID` адресует сервис на узле; 64-битные значения — концепция, **не TCP-порты**. +3. Медленный канал (`SlowRadio`) допускает beacon, route-discovery и маленький текст, но не bulk. + Класс определяется **размером**, а не только меткой отправителя (Control ≤ 256 Б, Text ≤ 4096 Б). +4. Фото и файлы отправляются только если найден **разрешённый по политике** путь. +5. Отсутствие пути ≠ успешная доставка; статусы `Queued`, `InFlight`, `Delivered`, `Expired` различаются; `Delivered` только если маршрут жив. +6. End-to-end криптография обязательна для реальной сети, **в симуляторе пока не реализована**. +7. Сетевой слой существует независимо от транспорта (UDP/радиомодем/ethernet) и UI. + +## Границы + +```text +apps/icenet-city ───> icenet-sim ──> icenet-routing ──> icenet-core +apps/icenetd ───────> icenet-sim (offline-команды) +apps/icenetd ───────> icenet-sdk ───> icenet-wire / icenet-transport / icenet-guard + └──────────────> icenet-core +``` + +Актуальный список и точные зависимости: [crates.md](crates.md). + +## Control plane / data plane + +- **Control**: маленькие объявления, отметки доступности, поиск маршрутов, ACK; отдельный лимит airtime и TTL. +- **Data**: текст, файлы, сервисные потоки; расписание маршрутов с учётом профиля физического канала. +- В будущем LoRa может передавать экстренный текст, если это допускают местные правила. +- В сети неизвестных узлов объявления не должны бесконтрольно распространяться; нужны квоты, дедупликация, expire. + +## Какую проблему изучаем + +Не «мы изобрели mesh/IPv6/крипто-адреса», а: +**может ли строгая политика передачи по гетерогенным каналам избежать перегрузки узкой полосы, +сохранив доставку коротких сообщений и стабильную идентичность?** + +Это гипотеза. Сравнивать надо с [Reticulum](../research/reticulum.md) и baselines. + +## Важная разница между симуляцией и продакшеном + +- Редактор города — модель графа со скоростью ребра, не радиотехнический расчёт покрытия. +- В нём нет настоящей криптографии, реального Wi-Fi, скрытых терминалов, интерференции, MAC. +- Числа в демо условны. Линк несёт одну передачу за раз, но потерь, коллизий и MAC нет. Для реального RF потребуется измерение или ns-3/другая PHY-модель. diff --git a/docs/build/dependencies.md b/docs/build/dependencies.md new file mode 100644 index 0000000..cacc7bf --- /dev/null +++ b/docs/build/dependencies.md @@ -0,0 +1,50 @@ +# Аудит зависимостей ICE-NET + +Числа (записи `Cargo.lock`, версия Rust, результаты сборки и замеров) — только в +[STATUS.md](../STATUS.md). Здесь — решения и политика. + +## Прямые внешние зависимости + +| Уровень | Внешняя зависимость | Почему | +| --- | --- | --- | +| `icenet-core`, `wire`, `guard`, `routing`, `transport`, `sdk`, `sim` | нет | Алгоритмы и интерфейсы на `std` | +| `icenetd` | нет | CLI и UDP на `std::net` | +| `icenet-city` | `slint = 1.18.1` | Декларативный GUI | +| сборка `icenet-city` | `slint-build = 1.18.1` | Генерация Rust из `.slint` | + +`slint` подключён с `default-features = false` и признаками `std`, `backend-winit`, +`renderer-software`, `compat-1-18`. Не включены Qt, Skia, FemtoVG, OpenGL, Vello, WGPU, +системный трей и интеграции. `renderer-software` не требует GPU, но `winit` зависит от +окружения рабочего стола. `slint-build` имеет собственный большой граф, который нельзя +убрать при заранее компилируемом UI. Меньшие флаги **не гарантируют** меньше транзитивных +зависимостей: число записей lock — не число скомпилированных crates. + +## История + +До v0.3 GUI был на `eframe`/`egui`. Он заменён на Slint; старый lock-файл не сохранён, +поэтому сравнение размера, RSS и старта с egui **невозможно** и снято с плана. +Инструкция по переходу — в архиве: [migration_egui_to_slint.md](../../archive/build/migration_egui_to_slint.md). + +## Проверка + +```bash +cd workspace +cargo tree -p icenet-city --depth 1 +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace +cargo build -p icenet-city --release +``` + +`Cargo.lock` нужно коммитить: workspace содержит исполняемые программы. + +## Политика для новых crates + +Перед добавлением библиотеки — отдельный ADR: какую задачу решает, почему нельзя на `std`, +MSRV, лицензия (совместимость с LGPL-3.0-or-later), число транзитивных crates, размер, +поддержка и план отказа. Не импортировать `serde`, `tokio`, `async-std`, `tracing`, `wgpu`, +`iced`, `egui` до замеров. + +Источники: +- [Slint feature flags](https://docs.slint.dev/latest/docs/rust/slint/docs/cargo_features/) +- [Slint Winit backend](https://docs.slint.dev/latest/docs/slint/guide/backends-and-renderers/backend_winit/) +- [Slint Rust integration](https://docs.rs/slint/latest/slint/) diff --git a/docs/build/slint_license.md b/docs/build/slint_license.md new file mode 100644 index 0000000..df2d6e5 --- /dev/null +++ b/docs/build/slint_license.md @@ -0,0 +1,25 @@ +# Лицензия Slint: решение до публичного релиза + +Slint не MIT/Apache; это **тройное лицензирование**: +GPLv3, royalty-free с условиями и коммерческая лицензия. + +- **GPLv3:** можно для открытого проекта, но совместное распространяемое + приложение должно соблюдать GPLv3. +- **Royalty-free:** для desktop/mobile/web, включая проприетарные приложения, + но с надлежащей атрибуцией Slint; не распространяется на embedded. +- **Коммерческая:** вариант для закрытого embedded или специальных требований. + +Лицензия собственного кода ICE-NET — **LGPL-3.0-or-later** (ADR-010). Она совместима с GPLv3: +если `icenet-city` распространяется со Slint по GPLv3, бинарник GUI целиком идёт под GPLv3. +Если нужна иная схема (royalty-free с атрибуцией), её надо проверить отдельно. Юридически это +не проверялось. + +Для ICE-NET: `icenet-city` — desktop GUI, а будущий роутер/LoRa-узел +не должен содержать Slint. Поэтому выбор лицензии GUI **отделён** от +сетевых библиотек. Условия не переносятся автоматически на независимые +библиотеки, но для связанного и распространяемого приложения обязательства +нужно проверить до публикации бинарников. Режим лицензии Slint для распространяемых бинарников GUI всё ещё **не выбран** (открытый пункт TODO). + +Источники: +- [Официальный LICENSE Slint](https://github.com/slint-ui/slint/blob/master/LICENSE.md) +- [FAQ лицензирования](https://slint.dev/faqs) diff --git a/docs/community/announcement_en.md b/docs/community/announcement_en.md new file mode 100644 index 0000000..4679517 --- /dev/null +++ b/docs/community/announcement_en.md @@ -0,0 +1,16 @@ +# Community post draft (EN) + +Hi! I'm experimenting with ICE-NET, a research-oriented Rust project inspired by +the Net of cyberpunk fiction: an identity-centric network that can span multiple underlying links, including +wired, IP, Wi-Fi, and low-bandwidth radio. + +Our first falsifiable hypothesis is that a strict, measurable scheduling +policy can keep slow radio available for discovery and tiny messages while +sending bulk data only through appropriate higher-capacity paths. + +This is currently a graph-based simulator and a set of protocol design notes, +not an operating wireless network. I'd love critical feedback on routing, +control-plane airtime, failure handling, and comparisons to Reticulum and +Meshtastic. Please suggest reproducible scenarios rather than feature lists. + +Repository: https://git.wihuk.pro/boba/ICE-NET.git (LGPL-3.0-or-later). diff --git a/docs/community/announcement_ru.md b/docs/community/announcement_ru.md new file mode 100644 index 0000000..32694ca --- /dev/null +++ b/docs/community/announcement_ru.md @@ -0,0 +1,15 @@ +# Черновик поста о проекте (RU) + +Привет! Мы экспериментируем с ICE-NET — идеей сети, вдохновлённой «Сетью» из киберпанка, которая может работать через +разные виды связи, включая интернет, кабель, Wi-Fi и малоскоростное радио. + +Цель первого опыта — проверить, можно ли гарантированно сохранять медленный +радиоканал для коротких сообщений и обнаружения узлов, направляя файлы только +через подходящие быстрые маршруты. Проект ещё на стадии симулятора на Rust, +а не развёрнутой радиосети. + +Ищу обратную связь по routing/QoS, ограничению служебного трафика и тестам. +Особенно полезны критические сравнения с Reticulum, Meshtastic и существующими +планировщиками. Желателен конкретный сценарий или воспроизводимый тест. + +Репозиторий: https://git.wihuk.pro/boba/ICE-NET.git (лицензия LGPL-3.0-or-later). diff --git a/docs/guides/commands.md b/docs/guides/commands.md new file mode 100644 index 0000000..8b3717a --- /dev/null +++ b/docs/guides/commands.md @@ -0,0 +1,22 @@ +# Шпаргалка команд + +```bash +cd workspace +python3 tools/check_layout.py # file <=250 lines, dir <=4 files +cargo metadata --no-deps +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace +cargo run -p icenet-city +cargo run -p icenetd -- help +cargo run -p icenetd -- route --from 1 --to 3 --class bulk --size 5000000 +cargo run -p icenetd -- send --from 1 --to 3 --class text --ticks 1000 +cargo run -p icenetd -- sim --csv metrics.csv --json scenario.json +cargo run -p icenetd -- policy --service 77777 --size 5 --allow 1 +cargo run -p icenetd -- wire-encode --service 7 --class text --text hello +cargo run -p icenetd -- serve --bind 127.0.0.1:9000 --count 1 --timeout 5000 +cargo run -p icenetd -- send-udp --to 127.0.0.1:9000 --service 7 --class text --text hello +``` + +Пакеты в `crates/*` — библиотеки, `apps/*` — исполняемые приложения. +Cargo workspace использует общий `Cargo.lock` (коммитится) и закреплённый toolchain. diff --git a/docs/guides/contributing.md b/docs/guides/contributing.md new file mode 100644 index 0000000..8fd8d53 --- /dev/null +++ b/docs/guides/contributing.md @@ -0,0 +1,18 @@ +# Contributing conventions + +- Feature branch: `feat/`; fix: `fix/`. +- PR начинается с проблемы и одного конкретного сценария, а не общих обещаний. +- Прежде чем добавлять crate, проверь зависимость и альтернативу module. +- Контракты в `docs/architecture/contracts.md`; тесты снаружи `src`. +- Публичные Rust элементы используют `///` doc comments на **английском**. +- Область изменения: краткая, отлаживаемая, 250 строк на файл максимум. +- До реального радио — legal review и тесты аппаратуры. + +## Suggested PR template + +- **What / Why:** одна конкретная проблема. +- **How:** какие crates и интерфейсы изменены. +- **Tests:** команды и результаты. +- **Metrics:** новые расходы CPU/RAM/airtime (если затронуты). +- **Security:** новые доверенные данные/границы. +- **Alternatives:** почему проще нельзя. diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.md new file mode 100644 index 0000000..10d55e9 --- /dev/null +++ b/docs/guides/quickstart.md @@ -0,0 +1,57 @@ +# Arch Linux: быстрый запуск разработчика + +## Установить инструменты + +```bash +sudo pacman -S --needed rustup python git pkgconf clang +rustup default stable +rustup component add rustfmt clippy +``` + +Для GUI могут потребоваться системные библиотеки графического backend (X11/Wayland, +mesa, fontconfig и т.п.); точные пакеты зависят от Arch, X11/Wayland и версии Slint. + +## Запуск + +```bash +cd workspace +python3 tools/check_layout.py +cargo test -p icenet-routing -p icenet-sim +cargo run -p icenet-city +``` + +В окне: выбрать From/To, отправить `Text`/`Photo`, менять состояние линков, +шагать по времени. Это моделирование, не сетевое соединение. + +## Отдельная библиотека + +```bash +cargo test -p icenet-routing --test routing +cargo test -p icenet-sim --test city +cargo doc --workspace --no-deps +``` + +`icenetd` — headless CLI для проверки ядра без GUI и без сети: + +```bash +cargo run -p icenetd -- route --from 1 --to 3 --class bulk --size 5000000 +cargo run -p icenetd -- send --from 1 --to 3 --class text --ticks 1000 +cargo run -p icenetd -- sim --csv /tmp/metrics.csv --json /tmp/scenario.json +``` + +Реальная UDP-передача между двумя процессами (локальный loopback, без crypto): + +```bash +# терминал 1 +cargo run -p icenetd -- serve --bind 127.0.0.1:9000 --count 1 --timeout 5000 +# терминал 2 +cargo run -p icenetd -- send-udp --to 127.0.0.1:9000 --service 7 --class text --text hello +``` + +Это незащищённый черновой кадр: без криптографии, аутентификации и защиты от replay на уровне сети. + +## Примечание по версиям + +`Slint 1.18.1` требует Rust >=1.92; toolchain закреплён в `rust-toolchain.toml` (версия — в [STATUS](../STATUS.md)). +Для ускоренной сборки не запускай `--workspace`, если сейчас тестируешь только +алгоритмы. Для релиза нужны полноценные CI-проверки всех crates и GUI. diff --git a/docs/guides/testing.md b/docs/guides/testing.md new file mode 100644 index 0000000..9f766a2 --- /dev/null +++ b/docs/guides/testing.md @@ -0,0 +1,42 @@ +# Tests / CI + +В Rust тесты лежат **только** в отдельной папке каждого крейта: +`crates//tests/*.rs` и `apps//tests/*.rs`. Inline `#[cfg(test)]` в `src` запрещён. + +```bash +cd workspace +python3 tools/check_layout.py +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace +cargo doc --workspace --no-deps +``` + +## Пирамида + +1. `core`: классы и логические ID. +2. `wire`: roundtrip + отказ на malformed frame / oversize. +3. `routing`: slow-only route for Text / forbidden for Bulk / oversized Text treated as Bulk / link-down. +4. `guard`: deny unknown service, cap payload, no fake authentication. +5. `sim`: node failure, in-flight state, queued retry, no false `Delivered` after a cut, link capacity (`tests/capacity/`). +6. `city`: GUI smoke test вручную (позднее snapshot/interaction integration tests). + +## Приёмка + +- Все новые тесты воспроизводимы без сети/радио. +- Каждый алгоритм не нуждается в реальном `sleep`; используется sim clock. +- При дефекте добавить regression test отдельно от production module. +- Маркеры `TODO`/`unimplemented!()` не прятать в ветки реальных пакетов. + +Что проверено и сколько тестов проходит — в [STATUS](../STATUS.md). + +## Быстрые и полные проверки + +```bash +cd workspace +sh tools/check_all.sh # core routing/simulator, без Slint-сборки +sh tools/check_all.sh --full # также Slint GUI и все integration tests +``` + +`cargo fmt --all` форматирует в том числе GUI crate; `.slint` не проверяется +`rustfmt` и проверяется компилятором Slint в `build.rs`. diff --git a/docs/research/gaps.md b/docs/research/gaps.md new file mode 100644 index 0000000..814b0fb --- /dev/null +++ b/docs/research/gaps.md @@ -0,0 +1,36 @@ +# ICE-NET vs существующие стеки — гипотеза уникальной ценности + +## Что НЕ уникально + +- Не-IP идентификаторы, криптография, announce routing, transport-agnostic mesh; + всё это уже реализовано в Reticulum и смежных проектах. +- Узкополосная LoRa discovery и next-hop маршрутизация представлены в Meshtastic. +- Статические радио-мосты, Wi-Fi mesh, store-and-forward и DTN не новые технологии. + +## Предлагаемая *исследовательская* функция + +**Constrained Path Policy Engine (CPPE)** — единая проверяемая политика, +которая запрещает большой полезный трафик на slow-control интерфейсах, +сопоставляет классы сообщений с возможностями канала, допускает очереди при +partition и измеряет цену служебного discovery в airtime. + +Это **не заявка на новизну**: ближайшие системы уже обладают частью этих функций; +эффект или удобство реализации должны быть доказаны экспериментами. + +## Проверяемые гипотезы + +- H1: bulk traffic не занимает slow-radio airtime при любом графе. +- H2: короткий текст достигает адресата, когда slow radio — единственный маршрут, + при условии допустимой загрузки канала. +- H3: смена link профилей/падение узла не создаёт ложного `DELIVERED`. +- H4: контрольный airtime и время поиска не растут неприемлемо при 100→1000 узлах. + +## Baselines + +1. Наивный shortest-hop. +2. Dijkstra по длине передачи/требуемому bitrate. +3. Reticulum с включёнными встроенными ограничениями/настройкой интерфейсов. +4. Meshtastic (узкая полоса, отдельный кейс, без попытки bulk). + +Если не обнаружено измеримого преимущества или недостающего рабочего сценария: +не писать весь свой протокол, а сделать policy adapter / contribution. diff --git a/docs/research/licensing.md b/docs/research/licensing.md new file mode 100644 index 0000000..14bf915 --- /dev/null +++ b/docs/research/licensing.md @@ -0,0 +1,20 @@ +# Правила лицензий и заимствований + +- Нельзя копировать исходники Reticulum, считая их MIT или Apache: его лицензия + содержит специфические ограничения. См. [полный текст](https://github.com/markqvist/Reticulum/blob/master/LICENSE). +- Reticulum является полезным независимым проектом; это исследование **не** заявляет его несовместимым с любой иной лицензией без юридической проверки. +- Meshtastic firmware официально GPL-3.0: проверять условия распространения производных работ. +- Slint и другие Rust зависимости сверять по версиям, NOTICE и SPDX; + нельзя механически приписывать всем crates одну лицензию. +- Наша документация написана заново, исходники сторонних проектов в ZIP **не вложены**. +- Лицензия собственного кода: **LGPL-3.0-or-later** (решение автора, ADR-010). Код с несовместимой + лицензией (в том числе нестандартной лицензии Reticulum) в ICE-NET не копировать. +- LGPL и статическая линковка Rust: получатель бинарника должен иметь возможность пересобрать его с + изменённой библиотекой. Юридически не проверялось. +- Не использовать чужие эмблемы/названия так, будто проект официально поддержан. + +## Рекомендация + +На старте: изучение документации, самостоятельная реализация демонстрационного +графового алгоритма, инструментальные сравнительные тесты. Кодовые зависимости +выбирать после review лицензий и security advisories. diff --git a/docs/research/meshtastic.md b/docs/research/meshtastic.md new file mode 100644 index 0000000..b985871 --- /dev/null +++ b/docs/research/meshtastic.md @@ -0,0 +1,29 @@ +# Meshtastic: как устроена дальняя текстовая mesh-сеть + +**Источник:** [официальный mesh algorithm](https://meshtastic.org/docs/overview/mesh-algo/). + +- Фокус: LoRa, текст, телеметрия и локальные сообщения без сотовой инфраструктуры. +- В `2.6+` broadcast использует управляемое flooding; direct-message после + обнаружения направления может использовать next-hop, затем откатиться к flooding. +- Используется Protocol Buffers (`MeshPacket`). +- У Meshtastic есть реальные ограничения bandwidth, airtime и батареи. +- **Он не является транспортом больших фото и не совместим с Reticulum по пакету.** + +## Что перенять + +1. Безусловный лимит на размер/частоту широковещательных объявлений. +2. Разделение broadcast и directed routing. +3. Корректный ACK/дедуп и hop limit. +4. Реальные правила эфира региона до включения радиоплаты. + +## Статус релизов + +GitHub Releases в ноябре 2026 показывает **2.7.x Beta и 2.8.x Alpha**, часть +alpha помечена `Revoked`. Не устанавливать «latest» вслепую; выбирать +стабильный релиз, проверять совместимость и регион. [Список релизов](https://github.com/meshtastic/firmware/releases). + +## Лицензии + +Meshtastic — группа репозиториев с разными лицензиями; официальный firmware +указан как **GPL-3.0**. Перед переносом кода проверять конкретный репозиторий, +а не название экосистемы целиком: https://github.com/meshtastic diff --git a/docs/research/reticulum.md b/docs/research/reticulum.md new file mode 100644 index 0000000..c21ff88 --- /dev/null +++ b/docs/research/reticulum.md @@ -0,0 +1,31 @@ +# Reticulum: что уже готово и чему учиться + +**Источник:** [официальный manual](https://reticulum.network/manual/) (на 12.11.2026 отображается 1.6.0). + +| Функция | Состояние у Reticulum | Вывод для ICE-NET | +|---|---|---| +| Не-IP идентичности | Есть, cryptographic addressing | не заявлять новизну | +| Multi-hop через разные среды | Есть | копировать идею, НЕ исходный код | +| Announce/path discovery | Есть | проверить baseline и стоимость пакетов | +| Interface discovery | Есть, включая private/encrypted announcements | большой пробел прежнего досье | +| QoS обычного трафика | В manual: обычные данные FIFO, без классов приоритета | возможная область исследований, не доказанное преимущество | +| Announce throttling / queue tuning | Есть | нельзя утверждать «нет контроля радиоэфира» | +| Передача файлов | Есть (`rncp`, Resources) | не изобретать ради галочки | + +## Что тестировать руками + +1. Две изолированные инстанции на localhost/UDP и transport node. +2. Смена интерфейса во время доступного маршрута. +3. Нагрузка на slow link: объявление + большой файл; измерить фактическое поведение. +4. Сверить с ограничениями Reticulum на rate, announce priority и interface modes. +5. Зафиксировать объективный пробел, а не предполагать его по обзору. + +## Осторожно с лицензией! + +[Reticulum License](https://github.com/markqvist/Reticulum/blob/master/LICENSE) — **нестандартная**; +включает дополнительные ограничения, включая запрет некоторых вредоносных +применений и использования кода для AI/ML training dataset. Её нельзя +автоматически считать MIT/Apache-2.0 или стандартной OSI-лицензией. +Изучать по документации можно; переносить код в ICE-NET без юридического +анализа нельзя. Официальный GitHub предупреждает о сторонних недостоверных +«совместимых» реализациях. Не объявлять wire-совместимость без тестов. diff --git a/docs/review/questions.md b/docs/review/questions.md new file mode 100644 index 0000000..75a8460 --- /dev/null +++ b/docs/review/questions.md @@ -0,0 +1,15 @@ +# Вопросы к автору ICE-NET (обсудить при следующем созвоне/чате) + +1. **Главная функция:** исследуем constrained routing или хочешь полностью свой новый протокол независимо от сравнения? +2. **Городской GUI:** нужен только топологический граф или настоящий вид города с улицами/домами и RF-моделью? +3. **Основная роль устройств:** мобильные клиенты — только leaf или добровольное временное реле при зарядке? +4. **Идентичность:** один пользователь с несколькими устройствами — аккаунт, группа ключей или отдельные адреса? +5. **Радио:** какое разрешённое оборудование/страна первичного пилота? Без этой детали не подбирать частоты. +6. ~~Open-source: какая лицензия?~~ **Решено:** LGPL-3.0-or-later (ADR-010). Чужие источники по-прежнему не копировать. +7. **Сетевые сервисы:** первый полезный сценарий — текст, файл, remote SSH-like сервис или другое? +8. **Мобильная платформа:** Android первым или только Linux/Arch до готового desktop MVP? +9. **GUI:** достаточно 2D на Slint (сильно быстрее) или нужен 3D город (дороже и сложнее)? +10. **Скорость vs ресурсность:** какой предел RAM/CPU у самых слабых устройств? + +**Не нужно отвечать сейчас на всё.** Для следующего этапа самый важный выбор: +пункт 1 и вид редактора из пункта 2. diff --git a/docs/review/revision.md b/docs/review/revision.md new file mode 100644 index 0000000..57232da --- /dev/null +++ b/docs/review/revision.md @@ -0,0 +1,57 @@ +# Что исправлено по внешней ревизии (18 страниц, 12.11.2026) + +**Основание:** загруженный пользователем документ +`ICE-NET_ревизия_досье_и_план_реализации.pdf/docx`. +Документ оценил 35 старых файлов, выборочно проверил 10 свежих утверждений +и предложил дополнительные направления; утверждения ревизора не являются +автоматически окончательной спецификацией. + +## Критика → решение v0.2 + +| Замечание | Ответ | +|---|---| +| Нет уникальной цели | отдельный [gaps.md](../research/gaps.md), H1–H4 | +| Много MD, нет кода | оформлен Cargo workspace, GUI и тесты; результаты проверок — в [STATUS](../STATUS.md) | +| Нет этапа 0 с Reticulum | отдельная P0 фаза в [TODO](../../TODO.md) | +| ICE Learning рискован | убран из MVP, [guard.md](../security/guard.md) | +| Нет mobile identity | открыто как ADR-008 | +| Нет экономической модели ретрансляторов | вынесено в [questions.md](questions.md) | +| Закон ограничен ЕС | по радиопередаче остаётся обязательная региональная проверка | +| Не зафиксированы API и тесты | [contracts.md](../architecture/contracts.md) + `workspace/*/tests/` | +| Нет выбора между своим протоколом/адаптером | ADR-007 открыт до полевых тестов | + +## Важные поправки к самому обзору + +- Фраза «телефоны не могут быть ретрансляторами» слишком категорична: Android может + участвовать в отдельных режимах, но непригоден как гарантированная магистраль 24/7. +- Цена и сроки железа оценочные; пользователь может стартовать с бюджетом ноль. +- Пример «городской mesh из смартфонов» не считается надёжным backbone. + +## Что не делали + +Не исполняли весь 30-дневный план; не проверяли по воздуху, не проводили аудит +безопасности. Этот документ — changelog решений, не сертификат готовности. + +## v0.3 · Slint и минимальные зависимости + +- GUI `eframe/egui` заменён на декларативный Slint; обновлены UI-модели и state-команды. +- Прямые внешние crates ограничены runtime `slint` и build-time `slint-build`. +- Rust domain crates изолированы и не используют сторонние пакеты. +- Проверка 250/4 не считает generated Cargo.lock / .gitignore, но считает `.slint`. +- Тесты добавлены отдельно; результаты `cargo test/fmt/clippy` — в [STATUS](../STATUS.md). + +## v0.4 · Внутренний разбор симулятора и документации + +Источник: самостоятельный разбор кода и доков 13.11.2026, не внешняя ревизия. + +| Находка | Исправление | +| --- | --- | +| Крупный `tick` давал `Delivered` после обрыва маршрута | доставка требует живого маршрута; регрессионные тесты в `tests/city.rs` | +| Метка `Text` на 5 МБ шла по slow radio | класс выводится из размера (ADR-011) | +| Линк пропускал любую нагрузку параллельно | слоты эфира и очередь на ребре (ADR-012) | +| `seed` в доках, но не в коде | убран из доков; TODO снят; случайные отказы — отдельная задача | +| Store-and-forward отмечен готовым | галочка снята, оговорено в TODO и STATUS | +| Устаревшие утверждения, v0.2/egui, дублирование чисел | числа вынесены в [STATUS](../STATUS.md), остатки убраны | +| Нет git и лицензии | `git init`, LGPL-3.0-or-later (ADR-010) | + +Не сделано: тела ADR-001…009, этап 0 с Reticulum, служебный трафик для H4. diff --git a/docs/review/rf_notes.md b/docs/review/rf_notes.md new file mode 100644 index 0000000..55e86dc --- /dev/null +++ b/docs/review/rf_notes.md @@ -0,0 +1,12 @@ +# Радиосвязь и физическая реальность + +- LoRa дальнобойнее на малой скорости, но радиоканал разделяется соседями и + регулируется полосой/мощностью/duty cycle. +- Направленные Wi-Fi/микроволновые мосты позволяют высокий bitrate при прямой + видимости, правильной установке и соблюдении местных норм. +- Расстояние по RSSI не является надёжным измерением геопозиции. +- Провал маршрута нельзя исправить «умным алгоритмом», если нет физического пути. +- В первом GUI геометрия **иллюстративная**, а линк задаётся пользователем вручную. + +Перед передачей в эфир проверить местные частоты, power/EIRP, duty cycle, DFS, +разрешения и условия для шифрованных данных. Пример региона не переносится на все страны. diff --git a/docs/security/guard.md b/docs/security/guard.md new file mode 100644 index 0000000..8966144 --- /dev/null +++ b/docs/security/guard.md @@ -0,0 +1,35 @@ +# ICE Guard: маленькая предсказуемая защита + +## До криптографии + +В `icenet-guard` реализованы детерминированные локальные проверки: +1. Разрешён ли сервис (ACL). +2. Не превышен ли лимит размера payload. +3. Есть ли место в очереди (`queue_full`). +4. Replay window per peer по монотонному `sequence`. +5. Token bucket per peer (`rate_limited`, `0` отключает лимит). +6. Передан ли тестовый `authenticated` flag **(не реальное доказательство)**. + +Проверка возвращает `Permit | Deny(reason)`. Отказ не расходует replay/rate state; +`sequence` фиксируется только после успешного `Permit`. Время передаёт вызывающий +код (`now_ms`), системные часы не читаются. + +**Нельзя** считать `authenticated` защитой от подмены на реальной сети. + +## После фиксации криптосхемы + +- Проверка подписи/handshake + binding NodeID -> key. +- Replay window per sender/peer, ограничение памяти на окна и очереди. +- Rate limits per interface/per service/per peer. +- Неизвестные пути, ложные announce, Sybil, DoS, packet bombs. +- Автоматическое действие только: log, local drop, local rate-limit, local revoke. + +## ICE Learning + +Из MVP исключён. Возможно вернётся **после** накопления реальных логов и +оценки ложноположительных блокировок, как отдельное необязательное решение. + +## Название + +Не путать «ICE Guard» со стандартизированным IETF ICE (Interactive Connectivity Establishment). +Перед публичным релизом обсудить переименование внутреннего security crate. diff --git a/docs/security/privacy.md b/docs/security/privacy.md new file mode 100644 index 0000000..72d320c --- /dev/null +++ b/docs/security/privacy.md @@ -0,0 +1,18 @@ +# Идентичность и приватность + +Криптографический NodeID подтверждает владение ключом, **не личность человека**. +Список соседей и объявления о маршрутах могут раскрывать паттерны движения. + +## Для дизайна + +- Device identity отдельно от user identity (телефон + ПК — независимые ключи). +- Нужно заранее решить, разрешён ли общий «профиль» на нескольких устройствах. +- Защитить метаданные TTL, discovery frequency и route request patterns. +- У relay должен быть минимальный доступ к содержимому сообщений. +- Не хранить GPS/историю маршрутов по умолчанию без согласия владельца. +- Перед повторной отправкой с нарушенной связью не объявлять доставку. + +## Не решено + +Public-key derivation, key rotation, group membership, encrypted store-and-forward +и TTL-политика ещё не специфицированы. См. [вопросы](../review/questions.md). diff --git a/docs/simulator/city_editor.md b/docs/simulator/city_editor.md new file mode 100644 index 0000000..33278a3 --- /dev/null +++ b/docs/simulator/city_editor.md @@ -0,0 +1,45 @@ +# ICE-NET City Lab — интерактивный эмулятор города + +## Назначение + +Нативное окно Rust/Slint, где видны устройства и каналы связи. +Первый GUI не зависит от реальных IP-адресов и может работать **офлайн**. + +## Возможности стартового каркаса + +- Нарисовать карту/граф, добавлять устройства и связи, видеть названия и типы. +- Выбрать отправителя/получателя; отправить Text (малый) или Photo (Bulk). +- Выбрать роль нового узла (Client/Relay/Backbone) и тип линка; подсветить последний маршрут. +- Отключить/включить узел или ребро через боковую панель. +- Продвинуть симуляционное время вручную (Step), посмотреть Queued/Delivered/Expired. +- Изменить расположение устройств кликом/drag (проверено под X11/Xvfb). +- Посмотреть выбранный маршрут и базовый журнал доставки. +- Экспортировать `icenet-metrics.csv` и `icenet-scenario.json` кнопками в боковой панели. + +## Не реализовано на старте + +- Сценарии на 1000 узлов в GUI, загрузка сохранённого JSON обратно. +- Настоящее позиционирование по GPS/радиосигналу, физика Fresnel, beamforming. +- Моделирование interference, duty cycle, hidden terminals и настоящая передача файлов. +- Релеи через смартфоны и реальный интернет. + +## Как использовать при разработке алгоритмов + +1. Реализовать новый `choose_path` в `icenet-routing`. +2. Добавить тест в `crates/icenet-routing/tests/routing.rs`. +3. Запустить city lab; сравнить Text vs Bulk на одном графе. +4. Отключить быстрейшую связь; проверить корректный NO_ROUTE/QUEUED. +5. Зафиксировать seed/топологию в scenario и сравнить метрики. + +**Критично:** рисовалка не должна выполнять маршрутизацию внутри `ui.update()`; +она передаёт запрос в `icenet-sim`, а рисует результат. + +## Граница GUI (v0.3) + +`ui/main.slint` показывает объекты из `VecModel`, фиксирует нажатия и drag. +`src/main.rs` регистрирует callback-обработчики, `src/state.rs` изменяет +`icenet-sim::City`, `src/view.rs` строит только визуальные модели. +Обработчик **не** рассчитывает маршруты сам; алгоритм остался в `icenet-routing`. + +GUI на Slint собран и проверен под X11/Xvfb: узлы, линии, drag, переключение +устройств/линий и экспорт CSV/JSON. Полная проверка на Wayland-сессии — отдельный шаг. diff --git a/docs/simulator/event_model.md b/docs/simulator/event_model.md new file mode 100644 index 0000000..a05db86 --- /dev/null +++ b/docs/simulator/event_model.md @@ -0,0 +1,45 @@ +# Simulation engine: contract + +## Состояния сообщения + +`Queued -> InFlight -> Delivered`; `InFlight -> Queued` при потере пригодного маршрута; +`Queued | InFlight -> Expired` по TTL. `Delivered` и `Expired` конечные. + +- Есть `created_ms`, `expires_ms`, `first_route_ms`; `tick()` переводит просроченное сообщение в + `Expired` и больше не доставляет его. +- Прибытие в момент `due_ms <= expires_ms` — доставка, даже если один крупный шаг времени + перескочил оба дедлайна (`tests/ttl.rs`). +- **Ложный `Delivered` исключён.** Изменения топологии происходят между тиками, поэтому топология + в `tick` держалась весь интервал. Доставка требует, чтобы все узлы маршрута были online, каждый + линк включён, соединял нужные узлы и допускал класс. Иначе сообщение перепланируется или встаёт + в `Queued` (`tests/city.rs`). + +## Ёмкость линка + +- На каждом линке календарь слотов эфира. Hop занимает `transfer_ms(bytes) + HOP_OVERHEAD_MS`. +- Резервирование идёт по порядку отправки; следующий слот начинается не раньше конца предыдущего, + а освободившиеся промежутки могут быть заняты. `due_ms` включает ожидание в очереди. +- Перепланирование освобождает ещё не начатые слоты сообщения; уже начатый airtime считается + потраченным. Истёкшее или потерявшее путь сообщение тоже освобождает будущие слоты. +- Выбор пути **не** учитывает бэклог, а перепланирование начинает с источника — ограничения. +- Метрики: `City::link_airtime_ms(kind)`, `City::link_backlog_ms(index)`, `slow_radio_airtime_ms`. + +## События будущей DES + +Сейчас время идёт шагами `tick`; полноценной очереди событий нет. План: + +| Event | Поля | +| --- | --- | +| `Announce` | node_id, iface, ttl | +| `LinkUp/LinkDown` | link_id, now_ms | +| `Send` | source, dest, bytes, traffic_class | +| `HopFinished` | message_id, hop_index | +| `Ack` | message_id, kind | +| `QueueExpire` | message_id, ttl | + +## Детерминизм + +- Одинаковые сценарий и последовательность действий дают одинаковый результат бит-в-бит + (случайности нет; **`seed` не реализован**). +- Ни один core алгоритм не вызывает `SystemTime` напрямую. +- GUI не ускоряет модель при изменении частоты кадров. diff --git a/docs/simulator/metrics.md b/docs/simulator/metrics.md new file mode 100644 index 0000000..eb873c6 --- /dev/null +++ b/docs/simulator/metrics.md @@ -0,0 +1,32 @@ +# Метрики и честность моделирования + +Цифры измерений — только в [STATUS](../STATUS.md). + +## Минимальный набор + +| Метрика | Смысл | Метод | +| --- | --- | --- | +| Delivery ratio | доставлено / создано | считать только `Delivered` | +| `first_route_ms` p50/p95 | **абсолютная** метка симулированного времени первого пути | не задержка: вычитания `created_ms` пока нет | +| Control airtime | эфир, занятый сообщениями класса Control по их маршрутам | сумма `transfer_ms + HOP_OVERHEAD_MS` по hop | +| `slow_radio_airtime_ms` | эфир, зарезервированный на slow radio всеми сообщениями | календарь слотов линков | +| Задержка поиска пути | реальное время CPU Dijkstra | `Instant` в `tests/scale.rs`, **debug**, не симуляция | +| RAM | реальная память процесса | procfs/OS вне симуляции; на 1000 узлов не измерено | + +`icenet_sim::metrics` считает состояния, delivery ratio, перцентили и airtime. +`messages_csv` и `scenario_json` дают детерминированный экспорт. + +## Условия воспроизводимости + +- Источник кода/commit, дата, топология, link profile, последовательность действий. +- Отдельно записать версию Rust и OS. `seed` не нужен, пока в модели нет случайности. +- Минимум 3 сценария: пустой эфир, заполненный эфир, отключение backbone. +- Изменённые параметры должны сохраняться в сценарии, не в GUI state. + +## Ограничения + +Время доставки учитывает последовательность hop и очередь на линке, но **не** включает +коллизии, hidden terminals, duty cycle, retransmission, FEC, TCP congestion control, радиолокацию, +OS scheduling и стоимость crypto. Выбор пути не знает о бэклоге. + +Нельзя из такого графа делать заявления «реальная сеть быстрее Reticulum». diff --git a/docs/simulator/scenarios.md b/docs/simulator/scenarios.md new file mode 100644 index 0000000..8911837 --- /dev/null +++ b/docs/simulator/scenarios.md @@ -0,0 +1,34 @@ +# Сценарии для City Lab и регрессионных тестов + +## S1 · LoRa discovery, Wi-Fi photo + +- A — клиент, B — реле, C — друг. +- A–B: SlowRadio, A–C: FastWireless, B–C: SlowRadio. +- Text A→C может идти напрямую или через B по метрике. +- Photo A→C **только** fast link; при отключении A–C фото QUEUED. + +## S2 · Городские две магистрали + +- 12 узлов: 8 клиентов, 2 relay, 2 backbone. +- У каждой магистрали резервное беспроводное ребро. +- Bulk идёт по fast сегментам, контрольные объявления лимитируются на slow. + +## S3 · Partition/merge + +- Граф из двух районов, между ними 1 bridge. +- После отключения bridge новые сообщения `Queued`, не `Delivered`. +- При восстановлении моста очередь переходит к доставке. + +## S4 · Злая нагрузка + +- 100 текстовых сообщений + 1 фото 5 MiB при медленном LoRa. +- Проверить, что фото не блокирует канал discovery: `slow_radio_airtime_ms` не содержит фото. +- Очередь на slow-линке растёт, часть текстов может истечь по TTL (`tests/capacity/`). +- Метрики: control airtime, бэклог линка, p95 поиска. Квоты control пока не реализованы. + +## S5 · Повторяемость + +- Одинаковый начальный граф и последовательность действий → одинаковые результаты и CSV. +- Случайных отказов и `seed` пока нет; когда появятся, seed обязан входить в сценарий. + +Не смешивать с реальными RF-измерениями. [Подробнее о метриках](metrics.md). diff --git a/workspace/.gitignore b/workspace/.gitignore new file mode 100644 index 0000000..dc85d26 --- /dev/null +++ b/workspace/.gitignore @@ -0,0 +1,7 @@ +/target/ +**/*.rs.bk +*.log +.env +.DS_Store +.idea/ +.vscode/ diff --git a/workspace/Cargo.lock b/workspace/Cargo.lock new file mode 100644 index 0000000..7da4e4b --- /dev/null +++ b/workspace/Cargo.lock @@ -0,0 +1,5424 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "annotate-snippets" +version = "0.12.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" +dependencies = [ + "anstyle", + "memchr", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.6", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.6", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.6", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "serde", + "unty", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "bytes", + "cfg_aliases", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "clru" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-field-offset" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d535c69e75b4e3c69e17205b5b37a91936c54086cecd339b70071500786acb9c" +dependencies = [ + "const-field-offset-macro", + "field-offset", +] + +[[package]] +name = "const-field-offset-macro" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d5848843a221ac268cfdd6bfd14e68d5d3dfa79d52c880aafab93f9517fb74" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "countme" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "ctor" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf" +dependencies = [ + "dtor", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.6", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + +[[package]] +name = "dtor" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "smallvec", + "writeable", +] + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "log", + "slotmap", + "tinyvec", +] + +[[package]] +name = "fontique" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "glow" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263218b0ba2b0715c3370fb04674f5f8aa331594b521c94ff0a8e4a8472d1386" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "grid" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "htmlparser" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" + +[[package]] +name = "i-slint-backend-linuxkms" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f519a8611a4982921e46e391015e5e40ceac5cc63813333ef91ada77df180d8" +dependencies = [ + "bytemuck", + "calloop 0.14.5", + "cfg_aliases", + "drm", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-software", + "memmap2", + "nix", +] + +[[package]] +name = "i-slint-backend-selector" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb974705d61ba56034f6129ff61f3e6282a2c0c07752f25e6cb417d81c0f0958" +dependencies = [ + "cfg-if", + "cfg_aliases", + "i-slint-backend-linuxkms", + "i-slint-backend-testing", + "i-slint-backend-winit", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", +] + +[[package]] +name = "i-slint-backend-testing" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01943d6c5ea5bc913d497bdaa423c309e7627afff47a6794bfd13be5c564209f" +dependencies = [ + "cfg_aliases", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-software", + "vtable", +] + +[[package]] +name = "i-slint-backend-winit" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae4fcf1b19e9cb109984d2af87d2b9485388c619265bff71dd523133888bee2" +dependencies = [ + "arboard", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "futures", + "glutin", + "glutin-winit", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "i-slint-renderer-skia", + "i-slint-renderer-software", + "imgref", + "lyon_path", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-ui-kit 0.3.2", + "pin-weak", + "raw-window-handle", + "rgb", + "scoped-tls-hkt", + "scopeguard", + "softbuffer", + "strum", + "vtable", + "wasm-bindgen", + "web-sys", + "webbrowser", + "windows", + "winit", + "zbus", +] + +[[package]] +name = "i-slint-common" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68a578f3e4b681b2b9cbd326d3be19716e2fac51d00a8a5b00c0ef4ae923b5e6" +dependencies = [ + "derive_more", + "fontique", + "htmlparser", + "icu_decimal", + "icu_locale_core", + "icu_provider", + "pulldown-cmark", + "resvg", + "skrifa", +] + +[[package]] +name = "i-slint-compiler" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55d48ebef05e2bf09ba5a1fc67bcb11033b9e12a2a50ed3105c7d25e2b539d0" +dependencies = [ + "annotate-snippets", + "by_address", + "data-url", + "derive_more", + "i-slint-common", + "icu_normalizer", + "icu_properties", + "image", + "indexmap", + "itertools 0.15.0", + "lyon_extra", + "lyon_path", + "num_enum", + "proc-macro2", + "quote", + "rayon", + "resvg", + "rowan", + "rspolib", + "skrifa", + "smol_str 0.3.7", + "strum", + "swash", + "typed-index-collections", + "unicode-segmentation", + "url", +] + +[[package]] +name = "i-slint-core" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2ea15059d70bc31b1a8b1eb4c34f2c5df04cb7e53f36179b43c0261231d646" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "chrono", + "clru", + "const-field-offset", + "derive_more", + "euclid", + "i-slint-common", + "i-slint-core-macros", + "icu_normalizer", + "image", + "js-sys", + "lyon_algorithms", + "lyon_extra", + "lyon_geom", + "lyon_path", + "num-traits", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "once_cell", + "parley", + "pin-project", + "pin-weak", + "portable-atomic", + "raw-window-handle", + "resvg", + "rgb", + "scopeguard", + "skrifa", + "slab", + "strum", + "swash", + "sys-locale", + "taffy", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", + "vtable", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows", +] + +[[package]] +name = "i-slint-core-macros" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f5a8a076de52f53be80caa826599ed2107b54c9d4a421e66dc06cf893a984c" +dependencies = [ + "quote", + "serde_json", + "syn 3.0.10", +] + +[[package]] +name = "i-slint-renderer-skia" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc9c1cf02385f1d26fc1f423544e52390a8e5c2d89420a8042aa94b4fe109d1f" +dependencies = [ + "bytemuck", + "cfg-if", + "cfg_aliases", + "clru", + "const-field-offset", + "glow", + "glutin", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "lyon_path", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "pin-weak", + "raw-window-handle", + "read-fonts", + "scoped-tls-hkt", + "skia-safe", + "softbuffer", + "spin_on", + "unicode-segmentation", + "vtable", + "wgpu", + "wgpu-hal", + "windows", + "windows-core", + "write-fonts", +] + +[[package]] +name = "i-slint-renderer-software" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f8c641e138a2cc96537cac4481f5c7c8bb8dcc66d09acaed269329c8738628a" +dependencies = [ + "bytemuck", + "clru", + "derive_more", + "euclid", + "i-slint-common", + "i-slint-core", + "lyon_path", + "num-traits", + "skrifa", + "swash", + "zeno", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icenet-city" +version = "0.0.1" +dependencies = [ + "icenet-core", + "icenet-sim", + "slint", + "slint-build", +] + +[[package]] +name = "icenet-core" +version = "0.0.1" + +[[package]] +name = "icenet-guard" +version = "0.0.1" +dependencies = [ + "icenet-core", +] + +[[package]] +name = "icenet-routing" +version = "0.0.1" +dependencies = [ + "icenet-core", +] + +[[package]] +name = "icenet-sdk" +version = "0.0.1" +dependencies = [ + "icenet-core", + "icenet-guard", + "icenet-transport", + "icenet-wire", +] + +[[package]] +name = "icenet-sim" +version = "0.0.1" +dependencies = [ + "icenet-core", + "icenet-routing", +] + +[[package]] +name = "icenet-transport" +version = "0.0.1" +dependencies = [ + "icenet-core", +] + +[[package]] +name = "icenet-wire" +version = "0.0.1" +dependencies = [ + "icenet-core", +] + +[[package]] +name = "icenetd" +version = "0.0.1" +dependencies = [ + "icenet-sdk", + "icenet-sim", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_decimal" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1150ad5e272740670464934ee76facda43ef2e11f85c27b7ba76ccb33edf2d05" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_plurals", + "icu_provider", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5595ab78370d48abd24a062f3db115d5108dd0b65634352036cae532aebb0df8" + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_plurals" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef046647b445acf95ce0f8083fa292467d3df649959fa9a20f3f8abfd957c5d" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43ff7df2c1a1d41588a6ddcba354d513d4a3e10eec22c06fe56d13c12a848ea" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.2", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lyon_algorithms" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805" +dependencies = [ + "lyon_path", + "num-traits", +] + +[[package]] +name = "lyon_extra" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7755f08423275157ad1680aaecc9ccb7e0cc633da3240fea2d1522935cc15c72" +dependencies = [ + "lyon_path", + "thiserror 2.0.21", +] + +[[package]] +name = "lyon_geom" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e" +dependencies = [ + "arrayvec", + "euclid", + "num-traits", +] + +[[package]] +name = "lyon_path" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" +dependencies = [ + "lyon_geom", + "num-traits", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "naga" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "natord" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308d96db8debc727c3fd9744aac51751243420e46edf401010908da7f8d5e57c" + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + +[[package]] +name = "parley" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22d2ff88bd3f7d68d1d9b09c7e6209f9a8e8c05088295140a2bcf2e9b17038c5" +dependencies = [ + "fontique", + "harfrust", + "hashbrown 0.17.1", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "skrifa", +] + +[[package]] +name = "parley_data" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1567535334d6ba2d3cde19221ba9a7bd0fabb3cbd99046ddfb10ae061cfcc889" +dependencies = [ + "icu_properties", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" + +[[package]] +name = "pin-weak" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b330c9d1b92dfe68442ca20b009c717d5f0b1e3cf4965e62f704c3c6e95a1305" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +dependencies = [ + "critical-section", +] + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pulldown-cmark" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "unicase", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.12.0", + "usvg", + "zune-jpeg", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "rowan" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b574c58582fa59fa43a2feb6608b8744184659f08a2e0117e4b8224d95ed61" +dependencies = [ + "countme", + "hashbrown 0.14.5", + "memoffset", + "rustc-hash 1.1.0", + "text-size", +] + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rspolib" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fda9a7796aff63a7b1b39ccc93fffaaf65e20042984b4843041a49ca4677535" +dependencies = [ + "lazy_static", + "natord", + "snafu", + "unicode-linebreak", + "unicode-width", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scoped-tls-hkt" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9603871ffe5df3ac39cb624790c296dbd47a400d202f56bf3e414045099524d" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia 0.11.4", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skia-bindings" +version = "0.153.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb325787c91b3f6c34a7c6f2b8a2297b20292d733ca53a08c233e5028aec49af" +dependencies = [ + "bindgen", + "cc", + "flate2", + "heck", + "pkg-config", + "regex", + "serde_json", + "tar", + "toml", +] + +[[package]] +name = "skia-safe" +version = "0.153.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61cb643dac43067f3eb76c866635a74377ac0abca0ff2590674e1e295514c3d" +dependencies = [ + "bitflags 2.13.2", + "skia-bindings", + "windows", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slint" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15e477d5ff6fec20909100ff8f7062432ebfbda7a62a0f37d0252aa126f38c83" +dependencies = [ + "const-field-offset", + "i-slint-backend-selector", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "i-slint-renderer-software", + "num-traits", + "once_cell", + "pin-weak", + "slint-macros", + "unicode-segmentation", + "vtable", +] + +[[package]] +name = "slint-build" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ea28d4e1ad47d829b91e227f17037fac07a8001668a93fee47ac04f88718ebc" +dependencies = [ + "derive_more", + "fontique", + "i-slint-compiler", + "spin_on", + "toml_edit", +] + +[[package]] +name = "slint-macros" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35e74b13d20884dc480ce37d0fabbf02cb4bc0df2a595434feac96ca7c2a0f15" +dependencies = [ + "i-slint-compiler", + "proc-macro2", + "quote", + "spin_on", +] + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "smol_str" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" +dependencies = [ + "borsh", + "serde_core", +] + +[[package]] +name = "snafu" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2" +dependencies = [ + "snafu-derive", +] + +[[package]] +name = "snafu-derive" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "as-raw-xcb-connection", + "bytemuck", + "fastrand", + "js-sys", + "memmap2", + "ndk", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "raw-window-handle", + "redox_syscall 0.5.18", + "rustix 1.1.6", + "tiny-xlib", + "tracing", + "wasm-bindgen", + "wayland-backend", + "wayland-client", + "wayland-sys", + "web-sys", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "spin_on" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076e103ed41b9864aa838287efe5f4e3a7a0362dd00671ae62a212e5e4612da2" +dependencies = [ + "pin-utils", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa", + "yazi", + "zeno", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "taffy" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aea22054047c16c3f34d3ac473a2170be1424b1115b2a3adcf28cfb067c88859" +dependencies = [ + "arrayvec", + "grid", + "serde", + "slotmap", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "text-size" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path 0.11.4", +] + +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-xlib" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" +dependencies = [ + "as-raw-xcb-connection", + "ctor", + "libloading", + "pkg-config", + "tracing", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "typed-index-collections" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898160f1dfd383b4e92e17f0512a7d62f3c51c44937b23b6ffc3a1614a8eaccd" +dependencies = [ + "bincode", + "serde", +] + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64", + "data-url", + "flate2", + "fontdb", + "harfrust", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "skrifa", + "strict-num", + "svgtypes", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtable" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "515a4b5b1399cc46fb0dc4081436cb40a3852a2d3e94fd1fa50bb68a334896eb" +dependencies = [ + "const-field-offset", + "portable-atomic", + "stable_deref_trait", + "vtable-macro", +] + +[[package]] +name = "vtable-macro" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8191d73ececf73fc94e65809bf0e667525a0bcff9aeeb8d042a4173a508332a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "log", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "gpu-allocator", + "hashbrown 0.17.1", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str 0.2.2", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.6", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "write-fonts" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae90d1d9f6d1d36ef116b0b1e651a6d7c12ba925439d4d06ff9adc94662a3d8" +dependencies = [ + "font-types", + "indexmap", + "kurbo", + "log", + "read-fonts", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.6", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix 1.1.6", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yazi" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] diff --git a/workspace/Cargo.toml b/workspace/Cargo.toml new file mode 100644 index 0000000..ffafdda --- /dev/null +++ b/workspace/Cargo.toml @@ -0,0 +1,16 @@ +[workspace] +resolver = "3" +members = ["crates/*", "apps/*"] +default-members = ["crates/icenet-sim", "apps/icenetd"] + +[workspace.package] +version = "0.0.1" +edition = "2024" +license = "LGPL-3.0-or-later" + +[profile.dev] +debug = 1 + +[profile.release] +lto = "thin" +codegen-units = 1 diff --git a/workspace/README.md b/workspace/README.md new file mode 100644 index 0000000..f9d4c36 --- /dev/null +++ b/workspace/README.md @@ -0,0 +1,32 @@ +# ICE-NET Rust workspace + +Исследовательский каркас, а не работающий сетевой протокол. Два приложения: +`icenet-city` (GUI графового эмулятора на Slint) и `icenetd` (CLI: route/send/sim/policy/wire +и UDP `serve`/`send-udp`). Что проверено и какие цифры — в [../docs/STATUS.md](../docs/STATUS.md). + +## Запуск на Arch + +```bash +rustup default stable # toolchain закреплён в rust-toolchain.toml +cd workspace +python3 tools/check_layout.py +cargo test -p icenet-sim -p icenet-routing +cargo run -p icenet-city # нужна графическая сессия +``` + +## Карта зависимостей + +`core` → `wire`, `guard`, `routing`, `transport` → `sdk` → `icenetd` + +`core + routing` → `sim` → `icenet-city`, `icenetd` + +`icenet-transport` содержит `MemoryTransport` (тесты) и неблокирующий `UdpTransport` на +`std::net`; loopback-тесты в `tests/udp.rs`. + +Тесты **не** внутри `src`, а в `tests/` каждого крейта. Лицензия: LGPL-3.0-or-later (`../LICENSE`). + +## Зависимости + +Прямые внешние: `slint` (runtime) и `slint-build` (build-time) только в `icenet-city`; +остальные крейты без внешних библиотек. `cargo test --workspace` собирает и Slint; для быстрой +проверки алгоритмов выбирай конкретные пакеты. `Cargo.lock` коммитится. diff --git a/workspace/apps/icenet-city/Cargo.toml b/workspace/apps/icenet-city/Cargo.toml new file mode 100644 index 0000000..bf886ed --- /dev/null +++ b/workspace/apps/icenet-city/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "icenet-city" +version.workspace = true +edition.workspace = true +license.workspace = true +build = "build.rs" + +[dependencies] +icenet-core = { path = "../../crates/icenet-core" } +icenet-sim = { path = "../../crates/icenet-sim" } +slint = { version = "=1.18.1", default-features = false, features = [ + "std", "backend-winit", "renderer-software", "compat-1-18", +] } + +[build-dependencies] +slint-build = "=1.18.1" diff --git a/workspace/apps/icenet-city/build.rs b/workspace/apps/icenet-city/build.rs new file mode 100644 index 0000000..6dd7b97 --- /dev/null +++ b/workspace/apps/icenet-city/build.rs @@ -0,0 +1,6 @@ +//! Compile the declarative interface without including GUI code in domain crates. + +/// Compiles the Slint UI into generated Rust bindings. +fn main() { + slint_build::compile("ui/main.slint").expect("Slint UI compilation failed"); +} diff --git a/workspace/apps/icenet-city/src/lib.rs b/workspace/apps/icenet-city/src/lib.rs new file mode 100644 index 0000000..b2058b1 --- /dev/null +++ b/workspace/apps/icenet-city/src/lib.rs @@ -0,0 +1,5 @@ +//! Slint application adapter for the deterministic ICE-NET city simulator. +pub mod state; +pub mod view; + +slint::include_modules!(); diff --git a/workspace/apps/icenet-city/src/main.rs b/workspace/apps/icenet-city/src/main.rs new file mode 100644 index 0000000..c5c80bb --- /dev/null +++ b/workspace/apps/icenet-city/src/main.rs @@ -0,0 +1,119 @@ +//! Standalone Slint GUI for offline ICE-NET city routing experiments. +use icenet_city::{CityWindow, state::UiState, view}; +use slint::{ComponentHandle, Weak}; +use std::{cell::RefCell, rc::Rc}; + +/// Performs a state command and refreshes the window, if it still exists. +fn apply(weak: &Weak, state: &Rc>, change: impl FnOnce(&mut UiState)) { + let mut state = state.borrow_mut(); + change(&mut state); + if let Some(ui) = weak.upgrade() { + view::refresh(&ui, &state); + } +} + +/// Registers UI callbacks without allowing the simulator to depend on Slint. +fn register_callbacks(ui: &CityWindow, state: Rc>) { + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_send_text(move || apply(&weak, &state, |s| s.send(false))); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_send_photo(move || apply(&weak, &state, |s| s.send(true))); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_export_csv(move || apply(&weak, &state, UiState::export_default_csv)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_export_json(move || apply(&weak, &state, UiState::export_default_json)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_next_from(move || apply(&weak, &state, |s| s.cycle_endpoint(true))); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_next_to(move || apply(&weak, &state, |s| s.cycle_endpoint(false))); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_next_role(move || apply(&weak, &state, UiState::cycle_role)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_next_link_kind(move || apply(&weak, &state, UiState::cycle_link_kind)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_add_node(move || apply(&weak, &state, UiState::add_node)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_connect_nodes(move || apply(&weak, &state, UiState::connect)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_toggle_node(move |id| apply(&weak, &state, |s| s.toggle_node(id))); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_toggle_link(move |index| apply(&weak, &state, |s| s.toggle_link(index))); + } + { + let state = state.clone(); + ui.on_drag_start(move |id, x, y| state.borrow_mut().start_drag(id, x, y)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_drag_move(move |x, y| { + let mut state = state.borrow_mut(); + state.drag_to(x, y); + if let Some(ui) = weak.upgrade() { + view::drag(&ui, &state); + } + }); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_drag_end(move || apply(&weak, &state, UiState::end_drag)); + } + { + let state = state.clone(); + let weak = ui.as_weak(); + ui.on_advance(move |elapsed| { + apply(&weak, &state, |s| { + s.city.tick(u64::try_from(elapsed).unwrap_or(0)); + }) + }); + } + { + let weak = ui.as_weak(); + ui.on_reset_city(move || apply(&weak, &state, |s| *s = UiState::default())); + } +} + +/// Starts the desktop simulator. The event loop is owned by Slint. +fn main() -> Result<(), slint::PlatformError> { + let ui = CityWindow::new()?; + let state = Rc::new(RefCell::new(UiState::default())); + view::refresh(&ui, &state.borrow()); + register_callbacks(&ui, state); + ui.run() +} diff --git a/workspace/apps/icenet-city/src/state.rs b/workspace/apps/icenet-city/src/state.rs new file mode 100644 index 0000000..4d88fd3 --- /dev/null +++ b/workspace/apps/icenet-city/src/state.rs @@ -0,0 +1,194 @@ +//! GUI-independent commands applied to the city simulator. +use std::{io, path::Path}; + +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_sim::{City, DeviceRole, metrics}; + +const CSV_FILE: &str = "icenet-metrics.csv"; +const JSON_FILE: &str = "icenet-scenario.json"; + +/// Grab state for stable pointer dragging of one node. +#[derive(Clone, Copy, Debug)] +pub struct Drag { + id: NodeId, + node_x: f32, + node_y: f32, + pointer_x: f32, + pointer_y: f32, +} + +/// Mutable state of the standalone city editor. +#[derive(Debug)] +pub struct UiState { + /// Deterministic offline city graph. + pub city: City, + /// Current sender in the sample graph. + pub from: NodeId, + /// Current recipient in the sample graph. + pub to: NodeId, + /// New node role selected in the editor. + pub role: DeviceRole, + /// New link technology selected in the editor. + pub link_kind: LinkKind, + /// Human-readable result of the last export action. + pub last_export: String, + drag: Option, +} + +impl Default for UiState { + fn default() -> Self { + Self { + city: City::demo(), + from: NodeId(1), + to: NodeId(3), + role: DeviceRole::Client, + link_kind: LinkKind::FastWireless, + last_export: String::new(), + drag: None, + } + } +} + +impl UiState { + /// Cycles through available sender or recipient IDs. + pub fn cycle_endpoint(&mut self, sender: bool) { + let current = if sender { self.from } else { self.to }; + let ids: Vec = self.city.devices.iter().map(|d| d.id).collect(); + if ids.is_empty() { + return; + } + let index = ids.iter().position(|id| *id == current).unwrap_or(0); + let next = ids[(index + 1) % ids.len()]; + if sender { + self.from = next; + } else { + self.to = next; + } + } + + /// Cycles among client, relay and backbone device roles. + pub fn cycle_role(&mut self) { + self.role = match self.role { + DeviceRole::Client => DeviceRole::Relay, + DeviceRole::Relay => DeviceRole::Backbone, + DeviceRole::Backbone => DeviceRole::Client, + }; + } + + /// Cycles among simulated radio, Wi-Fi, cable and internet links. + pub fn cycle_link_kind(&mut self) { + self.link_kind = match self.link_kind { + LinkKind::SlowRadio => LinkKind::FastWireless, + LinkKind::FastWireless => LinkKind::Wired, + LinkKind::Wired => LinkKind::Internet, + LinkKind::Internet => LinkKind::SlowRadio, + }; + } + + /// Adds a new device and selects it as recipient. + pub fn add_node(&mut self) { + let label = format!("New {:?} {}", self.role, self.city.devices.len() + 1); + self.to = self.city.add_device(label, self.role); + } + + /// Adds a link between the selected endpoints, if valid. + pub fn connect(&mut self) { + self.city.add_link(self.from, self.to, self.link_kind); + } + + /// Toggles a device's online state. + pub fn toggle_node(&mut self, id: i32) { + let update = self + .city + .devices + .iter() + .find(|d| d.id.0 == id as u64) + .map(|device| (device.id, !device.online)); + if let Some((id, online)) = update { + self.city.set_device_online(id, online); + } + } + + /// Toggles a link by its visible index. + pub fn toggle_link(&mut self, index: i32) { + if let Ok(index) = usize::try_from(index) + && let Some(enabled) = self.city.links.get(index).map(|link| !link.enabled) + { + self.city.set_link_enabled(index, enabled); + } + } + + /// Remembers the node and pointer position when a drag begins. + pub fn start_drag(&mut self, id: i32, pointer_x: f32, pointer_y: f32) { + let id = NodeId(id as u64); + if let Some(device) = self.city.devices.iter().find(|device| device.id == id) { + self.drag = Some(Drag { + id, + node_x: device.x, + node_y: device.y, + pointer_x, + pointer_y, + }); + } + } + + /// Moves the grabbed node by the pointer delta from the drag start. + pub fn drag_to(&mut self, pointer_x: f32, pointer_y: f32) { + if let Some(drag) = self.drag { + self.city.move_device( + drag.id, + (drag.node_x + pointer_x - drag.pointer_x).clamp(20.0, 520.0), + (drag.node_y + pointer_y - drag.pointer_y).clamp(20.0, 310.0), + ); + } + } + + /// Releases the current drag, if any. + pub fn end_drag(&mut self) { + self.drag = None; + } + + /// Sends synthetic text or bulk data; no real bytes leave this process. + pub fn send(&mut self, bulk: bool) { + let (kind, size) = if bulk { + (TrafficClass::Bulk, 5 * 1024 * 1024) + } else { + (TrafficClass::Text, 128) + }; + self.city.send(self.from, self.to, kind, size); + } + + /// Writes deterministic message metrics to `path`. + /// + /// # Errors + /// Returns the underlying I/O error when the file cannot be written. + pub fn export_csv(&mut self, path: &Path) -> io::Result<()> { + std::fs::write(path, metrics::messages_csv(&self.city))?; + self.last_export = format!("Exported {}", path.display()); + Ok(()) + } + + /// Writes the full scenario to `path` as deterministic JSON. + /// + /// # Errors + /// Returns the underlying I/O error when the file cannot be written. + pub fn export_json(&mut self, path: &Path) -> io::Result<()> { + std::fs::write(path, metrics::scenario_json(&self.city))?; + self.last_export = format!("Exported {}", path.display()); + Ok(()) + } + + /// Writes `icenet-metrics.csv` in the process working directory. + pub fn export_default_csv(&mut self) { + if let Err(error) = self.export_csv(Path::new(CSV_FILE)) { + self.last_export = format!("Export failed: {error}"); + } + } + + /// Writes `icenet-scenario.json` in the process working directory. + pub fn export_default_json(&mut self) { + if let Err(error) = self.export_json(Path::new(JSON_FILE)) { + self.last_export = format!("Export failed: {error}"); + } + } +} diff --git a/workspace/apps/icenet-city/src/view.rs b/workspace/apps/icenet-city/src/view.rs new file mode 100644 index 0000000..ad779dd --- /dev/null +++ b/workspace/apps/icenet-city/src/view.rs @@ -0,0 +1,140 @@ +//! Translate simulation state into Slint models without introducing UI into core crates. +use crate::{CityWindow, UiLink, UiNode, state::UiState}; +use icenet_core::NodeId; +use icenet_sim::{City, DeliveryState}; +use slint::{Color, Model, VecModel}; + +/// Updates node and link rows in place so an active drag is not interrupted. +pub fn drag(ui: &CityWindow, state: &UiState) { + if let Some(nodes) = ui.get_nodes().as_any().downcast_ref::>() { + for (index, device) in state.city.devices.iter().enumerate() { + let Some(mut node) = nodes.row_data(index) else { + continue; + }; + node.px = device.x; + node.py = device.y; + nodes.set_row_data(index, node); + } + } + if let Some(links) = ui.get_links().as_any().downcast_ref::>() { + for (index, link) in state.city.links.iter().enumerate() { + let Some(mut row) = links.row_data(index) else { + continue; + }; + let (Some(a), Some(b)) = (device(&state.city, link.a), device(&state.city, link.b)) + else { + continue; + }; + row.ax = a.x; + row.ay = a.y; + row.bx = b.x; + row.by = b.y; + links.set_row_data(index, row); + } + } +} + +fn device(city: &City, id: NodeId) -> Option<&icenet_sim::Device> { + city.devices.iter().find(|device| device.id == id) +} + +/// Applies one immutable simulator snapshot to the Slint window. +pub fn refresh(ui: &CityWindow, state: &UiState) { + let route = state + .city + .messages + .last() + .map(|m| m.route.as_slice()) + .unwrap_or(&[]); + let nodes: Vec = state + .city + .devices + .iter() + .map(|device| UiNode { + id: device.id.0 as i32, + label: device.label.as_str().into(), + px: device.x, + py: device.y, + online: device.online, + }) + .collect(); + ui.set_nodes(VecModel::from_slice(&nodes)); + + let links: Vec = state + .city + .links + .iter() + .map(|link| { + let a = state.city.devices.iter().find(|d| d.id == link.a); + let b = state.city.devices.iter().find(|d| d.id == link.b); + let (ax, ay, bx, by) = match (a, b) { + (Some(a), Some(b)) => (a.x, a.y, b.x, b.y), + _ => (0.0, 0.0, 0.0, 0.0), + }; + let enabled = + link.enabled && a.is_some_and(|n| n.online) && b.is_some_and(|n| n.online); + let highlighted = route + .windows(2) + .any(|hop| hop == [link.a, link.b] || hop == [link.b, link.a]); + UiLink { + ax, + ay, + bx, + by, + title: format!("{} — {} / {}", link.a.0, link.b.0, link.kind.label()).into(), + enabled, + highlighted, + color: if !enabled { + Color::from_rgb_u8(78, 88, 99) + } else { + link_color(link.kind.label()) + }, + } + }) + .collect(); + ui.set_links(VecModel::from_slice(&links)); + + let messages: Vec = state + .city + .messages + .iter() + .rev() + .take(12) + .map(|message| { + let status = match message.status { + DeliveryState::Queued => "QUEUED", + DeliveryState::InFlight => "IN_FLIGHT", + DeliveryState::Delivered => "DELIVERED", + DeliveryState::Expired => "EXPIRED", + }; + format!( + "#{} {} → {} | {:?} | {}", + message.id, message.from.0, message.to.0, message.class, status + ) + .into() + }) + .collect(); + ui.set_messages(VecModel::from_slice(&messages)); + ui.set_clock(format!("Virtual clock: {} ms", state.city.now_ms).into()); + ui.set_from_label(endpoint_name(&state.city, state.from).into()); + ui.set_to_label(endpoint_name(&state.city, state.to).into()); + ui.set_role_label(format!("Role: {:?}", state.role).into()); + ui.set_link_label(format!("New link: {}", state.link_kind.label()).into()); + ui.set_export_status(state.last_export.as_str().into()); +} + +fn endpoint_name(city: &City, id: NodeId) -> String { + city.devices.iter().find(|n| n.id == id).map_or_else( + || format!("#{:?}", id.0), + |n| format!("{} (#{})", n.label, id.0), + ) +} + +fn link_color(kind: &str) -> Color { + match kind { + "LoRa (slow)" => Color::from_rgb_u8(230, 177, 94), + "Wi-Fi (fast)" => Color::from_rgb_u8(89, 174, 250), + "Wired" => Color::from_rgb_u8(73, 222, 164), + _ => Color::from_rgb_u8(195, 145, 255), + } +} diff --git a/workspace/apps/icenet-city/tests/smoke.rs b/workspace/apps/icenet-city/tests/smoke.rs new file mode 100644 index 0000000..8e20472 --- /dev/null +++ b/workspace/apps/icenet-city/tests/smoke.rs @@ -0,0 +1,11 @@ +use icenet_core::{NodeId, TrafficClass}; +use icenet_sim::City; + +#[test] +fn city_example_contains_bulk_eligible_route() { + let city = City::demo(); + assert!( + city.route(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000) + .is_some() + ); +} diff --git a/workspace/apps/icenet-city/tests/state.rs b/workspace/apps/icenet-city/tests/state.rs new file mode 100644 index 0000000..bea069a --- /dev/null +++ b/workspace/apps/icenet-city/tests/state.rs @@ -0,0 +1,100 @@ +//! Regression tests for UI commands with no graphical backend. +use icenet_city::state::UiState; +use icenet_core::{NodeId, TrafficClass}; +use icenet_sim::DeliveryState; + +#[test] +fn photo_avoids_slow_radio_after_fast_links_are_disabled() { + let mut app = UiState::default(); + for index in [2, 3, 4, 5] { + app.city.set_link_enabled(index, false); + } + app.send(true); + assert_eq!( + app.city.messages.last().unwrap().status, + DeliveryState::Queued + ); + assert!( + app.city + .route(NodeId(1), NodeId(3), TrafficClass::Text, 128) + .is_some() + ); +} + +#[test] +fn toggling_a_device_and_restarting_are_deterministic() { + let mut app = UiState::default(); + app.toggle_node(2); + assert!( + !app.city + .devices + .iter() + .find(|d| d.id == NodeId(2)) + .unwrap() + .online + ); + app = UiState::default(); + assert!(app.city.devices.iter().all(|d| d.online)); +} + +#[test] +fn editor_adds_a_link_and_cycles_endpoints() { + let mut app = UiState::default(); + app.add_node(); + assert_eq!(app.to, NodeId(7)); + app.connect(); + assert!( + app.city + .links + .iter() + .any(|link| link.a == NodeId(1) && link.b == NodeId(7)) + ); +} + +#[test] +fn drag_uses_a_fixed_start_pointer_offset() { + let mut app = UiState::default(); + app.start_drag(1, 409.0, 186.0); + app.drag_to(470.0, 240.0); + app.drag_to(530.0, 290.0); + let node = app + .city + .devices + .iter() + .find(|device| device.id == NodeId(1)) + .expect("demo node"); + assert!((node.x - 191.0).abs() < f32::EPSILON); + assert!((node.y - 189.0).abs() < f32::EPSILON); + app.end_drag(); + app.drag_to(0.0, 0.0); + let node = app + .city + .devices + .iter() + .find(|device| device.id == NodeId(1)) + .expect("demo node"); + assert!((node.x - 191.0).abs() < f32::EPSILON); +} + +#[test] +fn exports_csv_and_json_to_requested_paths() { + let mut app = UiState::default(); + app.send(false); + let stamp = format!("icenet-test-{}", std::process::id()); + let csv_path = std::env::temp_dir().join(format!("{stamp}.csv")); + let json_path = std::env::temp_dir().join(format!("{stamp}.json")); + + app.export_csv(&csv_path).expect("csv export"); + let csv = std::fs::read_to_string(&csv_path).expect("read csv"); + assert!(csv.starts_with("id,from,to,class,bytes,status,")); + assert_eq!(csv.lines().count(), 2); + assert!(app.last_export.contains(&stamp)); + + app.export_json(&json_path).expect("json export"); + let json = std::fs::read_to_string(&json_path).expect("read json"); + assert!(json.contains("\"messages\"")); + assert!(json.contains("\"devices\"")); + + std::fs::remove_file(csv_path).expect("cleanup csv"); + std::fs::remove_file(json_path).expect("cleanup json"); +} diff --git a/workspace/apps/icenet-city/ui/main.slint b/workspace/apps/icenet-city/ui/main.slint new file mode 100644 index 0000000..cea7289 --- /dev/null +++ b/workspace/apps/icenet-city/ui/main.slint @@ -0,0 +1,206 @@ +// A desktop-only city topology editor; all networking logic stays in Rust crates. +import { Button, ScrollView } from "std-widgets.slint"; + +export struct UiNode { + id: int, + label: string, + px: float, + py: float, + online: bool, +} + +export struct UiLink { + ax: float, + ay: float, + bx: float, + by: float, + title: string, + enabled: bool, + highlighted: bool, + color: color, +} + +export component CityWindow inherits Window { + title: "ICE-NET City Lab | Slint"; + preferred-width: 1140px; + preferred-height: 760px; + background: #0c131b; + + in property <[UiNode]> nodes; + in property <[UiLink]> links; + in property <[string]> messages; + in property clock; + in property from-label; + in property to-label; + in property role-label; + in property link-label; + in property export-status; + + callback send-text(); + callback send-photo(); + callback export-csv(); + callback export-json(); + callback next-from(); + callback next-to(); + callback next-role(); + callback next-link-kind(); + callback add-node(); + callback connect-nodes(); + callback toggle-node(int); + callback toggle-link(int); + callback drag-start(int, float, float); + callback drag-move(float, float); + callback drag-end(); + callback advance(int); + callback reset-city(); + + HorizontalLayout { + padding: 16px; + spacing: 14px; + side := Rectangle { + width: 295px; + background: #172533; + border-radius: 12px; + VerticalLayout { + padding: 14px; + spacing: 9px; + Text { text: "ICE-NET / CITY LAB"; color: #6de0cb; font-size: 20px; font-weight: 700; } + Text { text: "Offline graph simulation • no real radio"; color: #adc0ce; font-size: 12px; } + Rectangle { height: 1px; background: #344557; } + Text { text: "ROUTE"; color: #6de0cb; font-size: 13px; font-weight: 700; } + Button { text: "From: " + root.from-label; clicked => { root.next-from(); } } + Button { text: "To: " + root.to-label; clicked => { root.next-to(); } } + HorizontalLayout { + spacing: 5px; + Button { text: "Text (128 B)"; clicked => { root.send-text(); } } + Button { text: "Photo (5 MiB)"; clicked => { root.send-photo(); } } + } + Rectangle { height: 1px; background: #344557; } + Text { text: "TOPOLOGY EDITOR"; color: #6de0cb; font-size: 13px; font-weight: 700; } + Button { text: root.role-label; clicked => { root.next-role(); } } + Button { text: "Add device"; clicked => { root.add-node(); } } + Button { text: root.link-label; clicked => { root.next-link-kind(); } } + Button { text: "Connect selected devices"; clicked => { root.connect-nodes(); } } + Text { text: "DEVICES (CLICK TO TOGGLE)"; color: #b5c9d5; font-size: 12px; } + ScrollView { + height: 92px; + VerticalLayout { + spacing: 3px; + for node in root.nodes: Button { + text: node.label + (node.online ? " [ON]" : " [OFF]"); + clicked => { root.toggle-node(node.id); } + } + } + } + Text { text: "LINKS (CLICK TO TOGGLE)"; color: #b5c9d5; font-size: 12px; } + ScrollView { + height: 82px; + VerticalLayout { + spacing: 3px; + for edge[index] in root.links: Button { + text: edge.title + (edge.enabled ? " ON" : " OFF"); + clicked => { root.toggle-link(index); } + } + } + } + Text { text: root.clock; color: #adc0ce; font-size: 12px; } + HorizontalLayout { + spacing: 5px; + Button { text: "+1 sec"; clicked => { root.advance(1000); } } + Button { text: "+1 min"; clicked => { root.advance(60000); } } + Button { text: "Reset"; clicked => { root.reset-city(); } } + } + HorizontalLayout { + spacing: 5px; + Button { text: "Export CSV"; clicked => { root.export-csv(); } } + Button { text: "Export JSON"; clicked => { root.export-json(); } } + } + Text { text: root.export-status; color: #6de0cb; font-size: 11px; } + } + } + content := Rectangle { + background: #17212e; + border-radius: 12px; + VerticalLayout { + padding: 16px; + spacing: 12px; + Text { text: "Network topology"; color: #e7f3f8; font-size: 21px; font-weight: 600; } + Text { text: "Drag nodes. Thick links show the last selected route."; color: #9cb2c6; } + graph := Rectangle { + height: 355px; + background: #101c29; + border-radius: 8px; + for edge in root.links: Path { + width: 100%; + height: 100%; + viewbox-x: 0; + viewbox-y: 0; + viewbox-width: parent.width / 1px; + viewbox-height: parent.height / 1px; + stroke: edge.highlighted ? #ffffff : edge.color; + stroke-width: edge.highlighted ? 4px : 2px; + MoveTo { x: edge.ax; y: edge.ay; } + LineTo { x: edge.bx; y: edge.by; } + } + for node in root.nodes: Rectangle { + x: (node.px - 17.0) * 1px; + y: (node.py - 17.0) * 1px; + width: 34px; + height: 34px; + border-radius: 17px; + background: node.online ? #235b66 : #35404c; + border-color: node.online ? #72d0e2 : #78808a; + border-width: 2px; + Text { + text: node.id; + color: #ffffff; + horizontal-alignment: center; + vertical-alignment: center; + font-size: 13px; + font-weight: 700; + } + TouchArea { + mouse-cursor: pointer; + pointer-event(event) => { + if (event.kind == PointerEventKind.down) { + root.drag-start(node.id, + (self.absolute-position.x + self.mouse-x) / 1px, + (self.absolute-position.y + self.mouse-y) / 1px); + } else if (event.kind == PointerEventKind.up) { + root.drag-end(); + } + } + moved => { + if (self.pressed) { + root.drag-move( + (self.absolute-position.x + self.mouse-x) / 1px, + (self.absolute-position.y + self.mouse-y) / 1px); + } + } + } + } + } + Text { text: "Message log"; color: #e7f3f8; font-size: 17px; font-weight: 600; } + ScrollView { + VerticalLayout { + spacing: 6px; + for line in root.messages: Rectangle { + height: 28px; + background: #233242; + border-radius: 5px; + Text { + x: 9px; + text: line; + color: #d8e4ed; + vertical-alignment: center; + font-size: 12px; + } + } + } + } + Text { text: "Synthetic transmission estimates; not an RF model or a live network."; + color: #91aabd; font-size: 11px; } + } + } + } +} diff --git a/workspace/apps/icenetd/Cargo.toml b/workspace/apps/icenetd/Cargo.toml new file mode 100644 index 0000000..3ca9d27 --- /dev/null +++ b/workspace/apps/icenetd/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "icenetd" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-sdk = { path = "../../crates/icenet-sdk" } +icenet-sim = { path = "../../crates/icenet-sim" } diff --git a/workspace/apps/icenetd/src/args.rs b/workspace/apps/icenetd/src/args.rs new file mode 100644 index 0000000..41111ce --- /dev/null +++ b/workspace/apps/icenetd/src/args.rs @@ -0,0 +1,148 @@ +//! Minimal dependency-free option parser for the offline CLI. +use std::collections::{BTreeMap, BTreeSet}; + +const VALUE_OPTIONS: [&str; 25] = [ + "from", + "to", + "class", + "size", + "ttl", + "ticks", + "disable", + "service", + "allow", + "max-size", + "text", + "hex", + "csv", + "json", + "peer", + "seq", + "now", + "queue", + "max-queue", + "rate", + "burst", + "window", + "bind", + "count", + "timeout", +]; +const FLAGS: [&str; 3] = ["unauthenticated", "help", "version"]; + +/// Parsed command line: one command name plus value options and boolean flags. +#[derive(Debug)] +pub struct Args { + command: String, + options: BTreeMap, + flags: BTreeSet, +} + +impl Args { + /// Parses arguments after the executable name. + /// + /// # Errors + /// Returns a message for a missing command, an unknown option, or a + /// value option without a value. + pub fn parse(argv: impl IntoIterator) -> Result { + let mut iter = argv.into_iter(); + let Some(command) = iter.next() else { + return Err("missing command; try `help`".to_owned()); + }; + let mut options = BTreeMap::new(); + let mut flags = BTreeSet::new(); + while let Some(token) = iter.next() { + let Some(name) = token.strip_prefix("--") else { + return Err(format!("unexpected argument `{token}`")); + }; + if name.is_empty() { + return Err("empty option name".to_owned()); + } + if FLAGS.contains(&name) { + flags.insert(name.to_owned()); + continue; + } + let Some(value) = iter.next() else { + return Err(format!("option `--{name}` needs a value")); + }; + if options.insert(name.to_owned(), value).is_some() { + return Err(format!("option `--{name}` was supplied more than once")); + } + } + for name in options.keys().chain(flags.iter()) { + if !VALUE_OPTIONS.contains(&name.as_str()) && !FLAGS.contains(&name.as_str()) { + return Err(format!("unknown option `--{name}`")); + } + } + Ok(Self { + command, + options, + flags, + }) + } + + /// Returns the command name. + pub fn command(&self) -> &str { + &self.command + } + + /// Returns an option value, if present. + pub fn value(&self, name: &str) -> Option<&str> { + self.options.get(name).map(String::as_str) + } + + /// Returns whether a boolean flag was supplied. + pub fn flag(&self, name: &str) -> bool { + self.flags.contains(name) + } + + /// Rejects options and flags that the current command does not implement. + /// + /// # Errors + /// Returns a message naming the first unsupported option. + pub fn only(&self, allowed: &[&str]) -> Result<(), String> { + for name in self.options.keys() { + if !allowed.contains(&name.as_str()) { + return Err(format!( + "option `--{name}` is not supported by `{}`", + self.command + )); + } + } + for name in &self.flags { + if name != "help" && name != "version" && !allowed.contains(&name.as_str()) { + return Err(format!( + "option `--{name}` is not supported by `{}`", + self.command + )); + } + } + Ok(()) + } + + /// Reads a required unsigned integer option. + /// + /// # Errors + /// Returns a message when the option is absent or not an integer. + pub fn u64(&self, name: &str) -> Result { + let value = self + .value(name) + .ok_or_else(|| format!("option `--{name}` is required"))?; + value + .parse() + .map_err(|_| format!("`--{name}` must be an unsigned integer, got `{value}`")) + } + + /// Reads an optional unsigned integer option or returns `default`. + /// + /// # Errors + /// Returns a message when the supplied value is not an integer. + pub fn u64_or(&self, name: &str, default: u64) -> Result { + match self.value(name) { + Some(value) => value + .parse() + .map_err(|_| format!("`--{name}` must be an unsigned integer, got `{value}`")), + None => Ok(default), + } + } +} diff --git a/workspace/apps/icenetd/src/commands/mod.rs b/workspace/apps/icenetd/src/commands/mod.rs new file mode 100644 index 0000000..6ed167a --- /dev/null +++ b/workspace/apps/icenetd/src/commands/mod.rs @@ -0,0 +1,178 @@ +//! Offline command implementations; no sockets, GUI or cryptography are used. +use icenet_sdk::{NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState, metrics}; + +use crate::args::Args; + +mod policy; +mod udp; +mod wire; + +/// A CLI failure with a usage/runtime distinction for exit codes. +#[derive(Debug)] +pub enum CommandError { + /// The caller supplied invalid arguments. + Usage(String), + /// A valid request failed at runtime. + Runtime(String), +} + +impl From for CommandError { + fn from(message: String) -> Self { + Self::Usage(message) + } +} + +/// Runs one subcommand. +/// +/// # Errors +/// Returns a usage or runtime failure with a human-readable message. +pub fn run(args: &Args) -> Result<(), CommandError> { + match args.command() { + "route" => route(args), + "send" => send(args), + "sim" => sim(args), + "policy" => policy::run(args), + "send-udp" => udp::send(args), + "serve" => udp::serve(args), + "wire-encode" => wire::encode(args), + "wire-decode" => wire::decode(args), + other => Err(CommandError::Usage(format!( + "unknown command `{other}`; try `help`" + ))), + } +} + +fn route(args: &Args) -> Result<(), CommandError> { + args.only(&["from", "to", "class", "size", "disable"])?; + let city = demo_city(args)?; + let class = class(args)?; + let size = args.u64_or("size", 128)?; + let from = NodeId(args.u64("from")?); + let to = NodeId(args.u64("to")?); + match city.route(from, to, class, size) { + Some(path) => { + println!("route: {}", join_nodes(&path.nodes)); + println!("estimated_ms: {}", path.estimated_ms); + } + None => println!("route: NO_ROUTE"), + } + Ok(()) +} + +fn send(args: &Args) -> Result<(), CommandError> { + args.only(&["from", "to", "class", "size", "disable", "ttl", "ticks"])?; + let mut city = demo_city(args)?; + let class = class(args)?; + let size = args.u64_or("size", 128)?; + let ttl = args.u64_or("ttl", City::DEFAULT_TTL_MS)?; + if ttl == 0 { + return Err(CommandError::Usage( + "`--ttl` must be at least 1 millisecond".to_owned(), + )); + } + let ticks = args.u64_or("ticks", 0)?; + let from = NodeId(args.u64("from")?); + let to = NodeId(args.u64("to")?); + let id = city.send_with_ttl(from, to, class, size, ttl); + city.tick(ticks); + let message = city + .messages + .iter() + .find(|message| message.id == id) + .ok_or_else(|| CommandError::Runtime("message was not recorded".to_owned()))?; + println!( + "message: id={} status={:?} class={:?} bytes={} created_ms={} expires_ms={} \ + first_route_ms={:?} due_ms={:?} route={}", + message.id, + message.status, + message.class, + message.bytes, + message.created_ms, + message.expires_ms, + message.first_route_ms, + message.due_ms, + join_nodes(&message.route) + ); + if message.status == DeliveryState::Queued { + println!("hint: QUEUED means no eligible path, not delivered"); + } + Ok(()) +} + +fn sim(args: &Args) -> Result<(), CommandError> { + args.only(&["csv", "json"])?; + let mut city = City::demo(); + set_link(&mut city, 2, false)?; + city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 1_000); + city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + city.tick(1_000); + set_link(&mut city, 2, true)?; + city.tick(120_000); + + let summary = metrics::summarize(&city); + println!( + "created={} delivered={} in_flight={} queued={} expired={} \ + delivery_ratio={:.2} first_route_p50_ms={:?} first_route_p95_ms={:?} control_airtime_ms={}", + summary.created, + summary.delivered, + summary.in_flight, + summary.queued, + summary.expired, + summary.delivery_ratio(), + summary.first_route_p50_ms, + summary.first_route_p95_ms, + summary.control_airtime_ms + ); + if let Some(path) = args.value("csv") { + std::fs::write(path, metrics::messages_csv(&city)) + .map_err(|error| CommandError::Runtime(format!("cannot write `{path}`: {error}")))?; + println!("csv: {path}"); + } + if let Some(path) = args.value("json") { + std::fs::write(path, metrics::scenario_json(&city)) + .map_err(|error| CommandError::Runtime(format!("cannot write `{path}`: {error}")))?; + println!("json: {path}"); + } + Ok(()) +} + +pub(crate) fn class(args: &Args) -> Result { + match args.value("class").unwrap_or("text") { + "control" => Ok(TrafficClass::Control), + "text" => Ok(TrafficClass::Text), + "bulk" => Ok(TrafficClass::Bulk), + other => Err(format!("unknown class `{other}`; use control|text|bulk")), + } +} + +pub(crate) fn join_nodes(nodes: &[NodeId]) -> String { + if nodes.is_empty() { + return "NO_ROUTE".to_owned(); + } + nodes + .iter() + .map(|node| node.0.to_string()) + .collect::>() + .join("-") +} + +fn demo_city(args: &Args) -> Result { + let mut city = City::demo(); + if let Some(list) = args.value("disable") { + for part in list.split(',') { + let index = part + .trim() + .parse::() + .map_err(|_| format!("invalid link index `{part}`"))?; + set_link(&mut city, index, false)?; + } + } + Ok(city) +} + +fn set_link(city: &mut City, index: usize, enabled: bool) -> Result<(), String> { + city.set_link_enabled(index, enabled) + .then_some(()) + .ok_or_else(|| format!("no link with index {index}")) +} diff --git a/workspace/apps/icenetd/src/commands/policy.rs b/workspace/apps/icenetd/src/commands/policy.rs new file mode 100644 index 0000000..1aed2b5 --- /dev/null +++ b/workspace/apps/icenetd/src/commands/policy.rs @@ -0,0 +1,67 @@ +//! Local Guard policy command. +use icenet_sdk::{Context, Guard, Limits, NodeId, ServiceId, Verdict}; + +use super::CommandError; +use crate::args::Args; + +/// Evaluates one local admission request and prints the verdict. +pub fn run(args: &Args) -> Result<(), CommandError> { + args.only(&[ + "service", + "size", + "allow", + "max-size", + "unauthenticated", + "peer", + "seq", + "now", + "queue", + "max-queue", + "rate", + "burst", + "window", + ])?; + let service = ServiceId(args.u64("service")?); + let payload_bytes = to_usize(args.u64_or("size", 0)?, "--size")?; + let limits = Limits { + max_payload_bytes: to_usize(args.u64_or("max-size", 4_096)?, "--max-size")?, + max_queue_depth: to_usize(args.u64_or("max-queue", 64)?, "--max-queue")?, + rate_per_second: args.u64_or("rate", 20)?, + burst: args.u64_or("burst", 10)?, + replay_window: args.u64_or("window", 64)?, + }; + let allowed = match args.value("allow") { + Some(list) => parse_services(list)?, + None => vec![service], + }; + let mut guard = Guard::new(allowed, limits); + let context = Context { + authenticated: !args.flag("unauthenticated"), + peer: NodeId(args.u64_or("peer", 1)?), + service, + payload_bytes, + sequence: args.u64_or("seq", 1)?, + now_ms: args.u64_or("now", 0)?, + queue_depth: to_usize(args.u64_or("queue", 0)?, "--queue")?, + }; + match guard.check(context) { + Verdict::Permit => println!("Permit"), + Verdict::Deny(reason) => println!("Deny({reason})"), + } + Ok(()) +} + +fn to_usize(value: u64, name: &str) -> Result { + usize::try_from(value).map_err(|_| format!("`{name}` is too large for this machine")) +} + +fn parse_services(list: &str) -> Result, String> { + list.split(',') + .map(|part| { + part.trim() + .parse::() + .map(ServiceId) + .map_err(|_| format!("invalid service id `{part}`")) + }) + .collect() +} diff --git a/workspace/apps/icenetd/src/commands/udp.rs b/workspace/apps/icenetd/src/commands/udp.rs new file mode 100644 index 0000000..565c734 --- /dev/null +++ b/workspace/apps/icenetd/src/commands/udp.rs @@ -0,0 +1,135 @@ +//! Real UDP frame exchange for local process-to-process experiments. +use std::io::{self, Write as _}; +use std::net::SocketAddr; +use std::time::{Duration, Instant}; + +use icenet_sdk::{Frame, ServiceId, Transport, UdpTransport, decode, encode}; + +use super::wire::hex_encode; +use super::{CommandError, class}; +use crate::args::Args; + +/// Encodes one frame and sends it to `--to`. +pub fn send(args: &Args) -> Result<(), CommandError> { + args.only(&["to", "service", "class", "text"])?; + let peer = address(required(args, "to")?)?; + let service = ServiceId(args.u64("service")?); + let class = class(args)?; + let text = args.value("text").unwrap_or(""); + let frame = Frame { + class, + service, + payload: text.as_bytes().to_vec(), + }; + let bytes = encode(&frame) + .map_err(|error| CommandError::Runtime(format!("encode failed: {error:?}")))?; + let transport = UdpTransport::bind("0.0.0.0:0") + .map_err(|error| CommandError::Runtime(format!("bind failed: {error}")))?; + let mut transport = transport + .connect(peer) + .map_err(|error| CommandError::Runtime(format!("connect failed: {error}")))?; + transport + .send(bytes) + .map_err(|error| CommandError::Runtime(format!("send failed: {error:?}")))?; + println!("sent: {} bytes to {peer}", frame.payload.len()); + Ok(()) +} + +/// Receives frames until `--count` is reached or `--timeout` elapses. +pub fn serve(args: &Args) -> Result<(), CommandError> { + args.only(&["bind", "count", "timeout"])?; + let bind = address(required(args, "bind")?)?; + let count = optional_count(args)?; + let timeout = optional_timeout(args)?; + let transport = UdpTransport::bind(bind) + .map_err(|error| CommandError::Runtime(format!("bind failed: {error}")))?; + let mut transport = transport; + let local = transport + .local_addr() + .map_err(|error| CommandError::Runtime(format!("local address failed: {error}")))?; + println!("listening: {local}"); + flush()?; + + let deadline = timeout.map(|duration| Instant::now() + duration); + let mut received = 0_usize; + loop { + if let Some(bytes) = transport + .recv() + .map_err(|error| CommandError::Runtime(format!("recv failed: {error:?}")))? + { + match decode(&bytes) { + Ok(frame) => { + received = received.saturating_add(1); + println!( + "frame: service={} class={:?} bytes={} payload={}", + frame.service.0, + frame.class, + frame.payload.len(), + printable(&frame.payload) + ); + flush()?; + if count.is_some_and(|limit| received >= limit) { + return Ok(()); + } + } + Err(error) => { + println!("malformed: {error:?}"); + flush()?; + } + } + } + if deadline.is_some_and(|limit| Instant::now() >= limit) { + let millis = timeout.unwrap_or_default().as_millis(); + return Err(CommandError::Runtime(format!( + "timeout after {millis} ms waiting for frames" + ))); + } + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn required<'a>(args: &'a Args, name: &str) -> Result<&'a str, CommandError> { + args.value(name) + .ok_or_else(|| CommandError::Usage(format!("option `--{name}` is required"))) +} + +fn address(value: &str) -> Result { + value + .parse() + .map_err(|_| format!("invalid socket address `{value}`; expected IP:PORT")) +} + +fn optional_count(args: &Args) -> Result, String> { + if args.value("count").is_none() { + return Ok(None); + } + let count = usize::try_from(args.u64("count")?).map_err(|_| "`--count` is too large")?; + if count == 0 { + return Err("`--count` must be at least 1".to_owned()); + } + Ok(Some(count)) +} + +fn optional_timeout(args: &Args) -> Result, String> { + if args.value("timeout").is_none() { + return Ok(None); + } + let millis = args.u64("timeout")?; + if millis == 0 { + return Err("`--timeout` must be at least 1 millisecond".to_owned()); + } + Ok(Some(Duration::from_millis(millis))) +} + +fn printable(payload: &[u8]) -> String { + match std::str::from_utf8(payload) { + Ok(text) if !text.chars().any(char::is_control) => text.to_owned(), + _ => format!("0x{}", hex_encode(payload)), + } +} + +fn flush() -> Result<(), CommandError> { + io::stdout() + .flush() + .map_err(|error| CommandError::Runtime(format!("stdout flush failed: {error}"))) +} diff --git a/workspace/apps/icenetd/src/commands/wire.rs b/workspace/apps/icenetd/src/commands/wire.rs new file mode 100644 index 0000000..46a5697 --- /dev/null +++ b/workspace/apps/icenetd/src/commands/wire.rs @@ -0,0 +1,64 @@ +//! Draft frame encoding and decoding commands. +use std::fmt::Write as _; + +use icenet_sdk::{Frame, ServiceId, decode as decode_frame, encode as encode_frame}; + +use super::{CommandError, class}; +use crate::args::Args; + +/// Encodes a draft frame and prints its hex bytes. +pub fn encode(args: &Args) -> Result<(), CommandError> { + args.only(&["service", "class", "text"])?; + let service = ServiceId(args.u64("service")?); + let class = class(args)?; + let text = args.value("text").unwrap_or(""); + let frame = Frame { + class, + service, + payload: text.as_bytes().to_vec(), + }; + let bytes = encode_frame(&frame).map_err(|error| format!("encode failed: {error:?}"))?; + println!("frame: {}", hex_encode(&bytes)); + Ok(()) +} + +/// Decodes a draft frame from hex and prints its fields. +pub fn decode(args: &Args) -> Result<(), CommandError> { + args.only(&["hex"])?; + let hex = args + .value("hex") + .ok_or_else(|| CommandError::Usage("option `--hex` is required".to_owned()))?; + let bytes = hex_decode(hex)?; + let frame = decode_frame(&bytes).map_err(|error| format!("decode failed: {error:?}"))?; + println!("service: {}", frame.service.0); + println!("class: {:?}", frame.class); + println!("payload_bytes: {}", frame.payload.len()); + match std::str::from_utf8(&frame.payload) { + Ok(text) if !text.chars().any(char::is_control) => println!("payload: {text}"), + _ => println!("payload_hex: {}", hex_encode(&frame.payload)), + } + Ok(()) +} + +pub(super) fn hex_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + write!(out, "{byte:02x}").expect("writing into a String cannot fail"); + } + out +} + +fn hex_decode(text: &str) -> Result, String> { + let clean = text.trim(); + if !clean.len().is_multiple_of(2) { + return Err("hex input must have an even number of digits".to_owned()); + } + let mut out = Vec::with_capacity(clean.len() / 2); + for index in (0..clean.len()).step_by(2) { + let pair = clean + .get(index..index + 2) + .ok_or_else(|| format!("invalid hex at byte {index}"))?; + out.push(u8::from_str_radix(pair, 16).map_err(|_| format!("invalid hex pair `{pair}`"))?); + } + Ok(out) +} diff --git a/workspace/apps/icenetd/src/help.rs b/workspace/apps/icenetd/src/help.rs new file mode 100644 index 0000000..f9c68fc --- /dev/null +++ b/workspace/apps/icenetd/src/help.rs @@ -0,0 +1,63 @@ +//! Usage text for the offline CLI. + +/// Prints the command reference. +pub fn print() { + println!("{USAGE}"); +} + +const USAGE: &str = "\ +icenetd — offline ICE-NET lab (no sockets, no GUI, no cryptography) + +USAGE: + icenetd [options] + +COMMANDS: + route Find a policy-eligible path in the demo topology + send Create one message, advance time, print its state + sim Run the deterministic demo scenario and export metrics + policy Evaluate the local Guard policy (ACL/size/queue/replay/rate) + send-udp Encode one frame and send it over UDP + serve Receive draft frames over UDP and print them + wire-encode Encode a draft frame and print its hex bytes + wire-decode Parse a draft frame from hex bytes + version Print the binary version + help Print this text + +OPTIONS: + --from N --to N node IDs for route/send (default none) + --class C control | text | bulk (default text) + --size N payload bytes (default 128; policy default 0) + --ttl MS message lifetime, at least 1 (default 86400000) + --ticks MS simulated time to advance after send + --disable I,J disable demo link indexes before routing + --service N service ID for policy/wire commands + --allow I,J allowed service IDs (default: requested service) + --max-size N guard payload cap (default 4096) + --unauthenticated simulate an unauthenticated caller + --peer N --seq N guard sender identity and replay sequence + --now MS guard monotonic time for rate limiting + --queue N --max-queue N current and maximum guard queue depth + --rate N --burst N guard sustained rate and burst (rate 0 disables; + burst 0 with rate > 0 blocks all traffic) + --window N guard replay window size (default 64) + --text TEXT frame payload for wire-encode + --hex HEX frame bytes for wire-decode + --to IP:PORT UDP peer for send-udp + --bind IP:PORT local UDP address for serve (port 0 = auto) + --count N serve: exit after N valid frames + --timeout MS serve: exit with code 1 after this idle time + --csv PATH --json PATH exports for the sim command + --help print this text + +EXAMPLES: + icenetd route --from 1 --to 3 --class bulk --size 5000000 + icenetd route --from 1 --to 3 --class bulk --size 5000000 --disable 2,3,4 + icenetd send --from 1 --to 3 --class text --size 128 --ticks 1000 + icenetd sim --csv metrics.csv --json scenario.json + icenetd policy --service 77777 --size 5 --allow 1 + icenetd wire-encode --service 7 --class text --text hello + icenetd serve --bind 127.0.0.1:9000 --count 1 --timeout 5000 + icenetd send-udp --to 127.0.0.1:9000 --service 7 --class text --text hello + +Reminder: the simulator is not an RF model and this CLI has no authentication. +"; diff --git a/workspace/apps/icenetd/src/main.rs b/workspace/apps/icenetd/src/main.rs new file mode 100644 index 0000000..3cf8621 --- /dev/null +++ b/workspace/apps/icenetd/src/main.rs @@ -0,0 +1,88 @@ +//! Offline command-line lab for the ICE-NET core crates. +//! +//! Besides offline route/send/sim/policy/wire commands it offers plain UDP +//! `serve`/`send-udp`; there is no GUI, cryptography or daemon loop yet. +use std::ffi::OsString; +use std::process::ExitCode; + +mod args; +mod commands; +mod help; + +use args::Args; +use commands::CommandError; + +/// Classifies CLI failures so usage mistakes exit with code 2. +enum Failure { + Usage(String), + Runtime(String), +} + +fn main() -> ExitCode { + let argv = match utf8_arguments(std::env::args_os().skip(1)) { + Ok(argv) => argv, + Err(message) => return exit(Failure::Usage(message)), + }; + match dispatch(argv) { + Ok(()) => ExitCode::SUCCESS, + Err(failure) => exit(failure), + } +} + +fn exit(failure: Failure) -> ExitCode { + match failure { + Failure::Usage(message) => { + eprintln!("error: {message}"); + eprintln!(); + help::print(); + ExitCode::from(2) + } + Failure::Runtime(message) => { + eprintln!("error: {message}"); + ExitCode::from(1) + } + } +} + +fn utf8_arguments(args: impl Iterator) -> Result, String> { + args.map(|arg| { + arg.into_string() + .map_err(|_| "command-line arguments must be valid UTF-8".to_owned()) + }) + .collect() +} + +fn dispatch(argv: Vec) -> Result<(), Failure> { + if argv.is_empty() { + help::print(); + return Ok(()); + } + match argv[0].as_str() { + "--help" | "-h" => { + help::print(); + return Ok(()); + } + "--version" => { + print_version(); + return Ok(()); + } + _ => {} + } + let args = Args::parse(argv).map_err(Failure::Usage)?; + if args.flag("help") || args.command() == "help" { + help::print(); + return Ok(()); + } + if args.flag("version") || args.command() == "version" { + print_version(); + return Ok(()); + } + commands::run(&args).map_err(|error| match error { + CommandError::Usage(message) => Failure::Usage(message), + CommandError::Runtime(message) => Failure::Runtime(message), + }) +} + +fn print_version() { + println!("icenetd {}", env!("CARGO_PKG_VERSION")); +} diff --git a/workspace/apps/icenetd/tests/cli.rs b/workspace/apps/icenetd/tests/cli.rs new file mode 100644 index 0000000..7e5fef4 --- /dev/null +++ b/workspace/apps/icenetd/tests/cli.rs @@ -0,0 +1,156 @@ +//! End-to-end route/send/sim/wire tests against the real `icenetd` binary. +mod common; + +use common::{run, stderr, stdout, temp}; + +#[test] +fn help_lists_all_commands() { + let output = run(&["help"]); + assert!(output.status.success()); + let text = stdout(&output); + for command in [ + "route", + "send", + "sim", + "policy", + "wire-encode", + "wire-decode", + ] { + assert!(text.contains(command), "missing {command} in help"); + } +} + +#[test] +fn bulk_route_avoids_slow_radio() { + let output = run(&[ + "route", "--from", "1", "--to", "3", "--class", "bulk", "--size", "5000000", + ]); + assert!(output.status.success(), "stderr: {}", stderr(&output)); + assert!(stdout(&output).contains("1-4-5-3")); +} + +#[test] +fn bulk_route_reports_no_route_without_fast_links() { + let output = run(&[ + "route", + "--from", + "1", + "--to", + "3", + "--class", + "bulk", + "--size", + "5000000", + "--disable", + "2,3,4", + ]); + assert!(output.status.success()); + assert!(stdout(&output).contains("NO_ROUTE")); +} + +#[test] +fn text_route_may_use_slow_radio() { + let output = run(&[ + "route", + "--from", + "1", + "--to", + "3", + "--class", + "text", + "--size", + "128", + "--disable", + "2,3,4", + ]); + assert!(output.status.success()); + assert!(stdout(&output).contains("1-2-3")); +} + +#[test] +fn send_reports_delivered_message() { + let output = run(&[ + "send", "--from", "1", "--to", "3", "--class", "text", "--size", "128", "--ticks", "1000", + ]); + assert!(output.status.success()); + assert!(stdout(&output).contains("status=Delivered")); +} + +#[test] +fn send_reports_expired_message() { + let output = run(&[ + "send", + "--from", + "1", + "--to", + "3", + "--class", + "bulk", + "--size", + "5000000", + "--disable", + "2,3,4", + "--ttl", + "1000", + "--ticks", + "2000", + ]); + assert!(output.status.success(), "stderr: {}", stderr(&output)); + assert!(stdout(&output).contains("status=Expired")); +} + +#[test] +fn sim_writes_csv_and_json_exports() { + let csv = temp("metrics.csv"); + let json = temp("scenario.json"); + let output = run(&[ + "sim", + "--csv", + csv.to_str().expect("utf8 path"), + "--json", + json.to_str().expect("utf8 path"), + ]); + assert!(output.status.success(), "stderr: {}", stderr(&output)); + assert!(stdout(&output).contains("expired=1")); + let csv_body = std::fs::read_to_string(&csv).expect("csv export"); + assert!(csv_body.starts_with("id,from,to,class,bytes,status,")); + let json_body = std::fs::read_to_string(&json).expect("json export"); + assert!(json_body.contains("\"messages\"")); + let _ = std::fs::remove_file(csv); + let _ = std::fs::remove_file(json); +} + +#[test] +fn wire_encoder_and_decoder_round_trip() { + let encoded = run(&[ + "wire-encode", + "--service", + "7", + "--class", + "text", + "--text", + "hello", + ]); + assert!(encoded.status.success(), "stderr: {}", stderr(&encoded)); + let text = stdout(&encoded); + let hex = text + .lines() + .find_map(|line| line.strip_prefix("frame: ")) + .expect("frame hex line") + .to_owned(); + let decoded = run(&["wire-decode", "--hex", &hex]); + assert!(decoded.status.success(), "stderr: {}", stderr(&decoded)); + let text = stdout(&decoded); + assert!(text.contains("class: Text")); + assert!(text.contains("service: 7")); + assert!(text.contains("payload: hello")); +} + +#[test] +fn wire_decode_escapes_control_bytes() { + let output = run(&["wire-decode", "--hex", "494e0101000000000000000700020102"]); + assert!(output.status.success(), "stderr: {}", stderr(&output)); + let text = stdout(&output); + assert!(text.contains("payload_hex: 0102")); + assert!(!text.contains('\u{1}')); +} diff --git a/workspace/apps/icenetd/tests/common/mod.rs b/workspace/apps/icenetd/tests/common/mod.rs new file mode 100644 index 0000000..0226947 --- /dev/null +++ b/workspace/apps/icenetd/tests/common/mod.rs @@ -0,0 +1,23 @@ +//! Shared helpers for CLI integration tests. +#![allow(dead_code)] +use std::path::PathBuf; +use std::process::{Command, Output}; + +pub fn run(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_icenetd")) + .args(args) + .output() + .expect("icenetd must start") +} + +pub fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +pub fn stderr(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +pub fn temp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("icenetd-{}-{name}", std::process::id())) +} diff --git a/workspace/apps/icenetd/tests/policy.rs b/workspace/apps/icenetd/tests/policy.rs new file mode 100644 index 0000000..ac184cf --- /dev/null +++ b/workspace/apps/icenetd/tests/policy.rs @@ -0,0 +1,104 @@ +//! Policy, usage and exit-code tests against the real `icenetd` binary. +mod common; + +use common::{run, stderr, stdout}; + +#[test] +fn policy_reports_acl_and_authentication_reasons() { + let permit = run(&["policy", "--service", "77777", "--size", "5"]); + assert!(permit.status.success()); + assert!(stdout(&permit).contains("Permit")); + + let denied = run(&[ + "policy", + "--service", + "77777", + "--size", + "5", + "--allow", + "1", + ]); + assert!(denied.status.success()); + assert!(stdout(&denied).contains("service_denied")); + + let anonymous = run(&[ + "policy", + "--service", + "77777", + "--size", + "5", + "--unauthenticated", + ]); + assert!(anonymous.status.success()); + assert!(stdout(&anonymous).contains("unauthenticated")); +} + +#[test] +fn policy_reports_rate_and_queue_reasons() { + let queue = run(&[ + "policy", + "--service", + "77777", + "--size", + "5", + "--queue", + "2", + "--max-queue", + "2", + ]); + assert!(queue.status.success()); + assert!(stdout(&queue).contains("queue_full")); + + let rate = run(&[ + "policy", + "--service", + "77777", + "--size", + "5", + "--rate", + "1", + "--burst", + "0", + ]); + assert!(rate.status.success()); + assert!(stdout(&rate).contains("rate_limited")); +} + +#[test] +fn help_and_version_flags_work_without_a_command() { + let help = run(&["--help"]); + assert!(help.status.success()); + assert!(stdout(&help).contains("USAGE")); + let version = run(&["--version"]); + assert!(version.status.success()); + assert!(stdout(&version).contains("icenetd")); +} + +#[test] +fn invalid_values_are_usage_errors_with_exit_two() { + let cases: Vec> = vec![ + vec!["route", "--from", "1"], + vec!["route", "--from", "1", "--to", "3", "--class", "Bulk"], + vec!["route", "--from", "1", "--to", "3", "--disable", "99"], + vec!["route", "--from", "1", "--to", "3", "--csv", "x.csv"], + vec!["send", "--from", "1", "--to", "3", "--ttl", "0"], + vec!["sim", "--disable", "0"], + vec!["route", "--from", "1", "--from", "3", "--to", "2"], + ]; + for case in cases { + let output = run(&case); + assert_eq!( + output.status.code(), + Some(2), + "case {case:?} stderr: {}", + stderr(&output) + ); + } +} + +#[test] +fn unknown_option_is_a_usage_error() { + let output = run(&["route", "--bogus", "1"]); + assert_eq!(output.status.code(), Some(2)); + assert!(stderr(&output).contains("unknown option")); +} diff --git a/workspace/apps/icenetd/tests/udp_cli.rs b/workspace/apps/icenetd/tests/udp_cli.rs new file mode 100644 index 0000000..cadf20c --- /dev/null +++ b/workspace/apps/icenetd/tests/udp_cli.rs @@ -0,0 +1,75 @@ +//! Process-to-process UDP tests for `icenetd send-udp` and `icenetd serve`. +mod common; + +use std::io::{BufRead, BufReader, Read}; +use std::process::{Command, Stdio}; + +use common::{run, stderr, stdout}; + +#[test] +fn serve_and_send_udp_exchange_a_frame() { + let mut server = Command::new(env!("CARGO_BIN_EXE_icenetd")) + .args([ + "serve", + "--bind", + "127.0.0.1:0", + "--count", + "1", + "--timeout", + "5000", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("serve starts"); + + let stdout_pipe = server.stdout.take().expect("server stdout"); + let mut reader = BufReader::new(stdout_pipe); + let mut first_line = String::new(); + reader.read_line(&mut first_line).expect("listening line"); + let address = first_line + .trim() + .strip_prefix("listening: ") + .expect("listening address") + .to_owned(); + + let sent = run(&[ + "send-udp", + "--to", + &address, + "--service", + "77777", + "--class", + "text", + "--text", + "hello-udp", + ]); + assert!(sent.status.success(), "stderr: {}", stderr(&sent)); + assert!(stdout(&sent).contains("sent:")); + + let mut received = String::new(); + reader.read_to_string(&mut received).expect("server output"); + let status = server.wait().expect("server exits"); + assert!(status.success(), "server stderr: {received}"); + assert!( + received.contains("service=77777 class=Text bytes=9 payload=hello-udp"), + "received: {received}" + ); +} + +#[test] +fn serve_times_out_when_no_frames_arrive() { + let output = Command::new(env!("CARGO_BIN_EXE_icenetd")) + .args(["serve", "--bind", "127.0.0.1:0", "--timeout", "200"]) + .output() + .expect("serve starts"); + assert_eq!(output.status.code(), Some(1)); + assert!(stderr(&output).contains("timeout after")); +} + +#[test] +fn send_udp_rejects_invalid_addresses() { + let output = run(&["send-udp", "--to", "not-an-address", "--text", "hello"]); + assert_eq!(output.status.code(), Some(2)); + assert!(stderr(&output).contains("invalid socket address")); +} diff --git a/workspace/crates/icenet-core/Cargo.toml b/workspace/crates/icenet-core/Cargo.toml new file mode 100644 index 0000000..e54d985 --- /dev/null +++ b/workspace/crates/icenet-core/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "icenet-core" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] diff --git a/workspace/crates/icenet-core/src/lib.rs b/workspace/crates/icenet-core/src/lib.rs new file mode 100644 index 0000000..15b70f2 --- /dev/null +++ b/workspace/crates/icenet-core/src/lib.rs @@ -0,0 +1,106 @@ +//! Shared, platform-independent types for ICE-NET prototypes. +//! +//! These numeric node IDs are simulation placeholders, not cryptographic IDs. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +/// An ICE-NET node identifier in the current prototype. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct NodeId(pub u64); + +/// An ICE-NET application service identifier; not a TCP/UDP port. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct ServiceId(pub u64); + +/// User-facing classes of traffic. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TrafficClass { + /// Tiny announcements and routing control messages. + Control, + /// Small user messages that may use a slow radio link. + Text, + /// Bulk transfers, including photos and files. + Bulk, +} + +impl TrafficClass { + /// Largest payload that may travel as [`TrafficClass::Control`]. + pub const CONTROL_MAX_BYTES: u64 = 256; + /// Largest payload that may travel as [`TrafficClass::Text`]. + /// + /// Equals the wire frame payload limit, so one text is one frame. + pub const TEXT_MAX_BYTES: u64 = 4_096; + + /// Returns whether slow radio links are eligible for this traffic class. + pub const fn allows_slow_radio(self) -> bool { + !matches!(self, Self::Bulk) + } + + /// Returns the class a payload of `bytes` is actually treated as. + /// + /// The label is chosen by the sender and cannot be trusted: an oversized + /// `Control` becomes `Text` and an oversized `Text` becomes `Bulk`, so a + /// large payload can never claim a slow radio. `Bulk` never shrinks. + pub const fn effective_for(self, bytes: u64) -> Self { + match self { + Self::Control if bytes <= Self::CONTROL_MAX_BYTES => Self::Control, + Self::Control | Self::Text if bytes <= Self::TEXT_MAX_BYTES => Self::Text, + _ => Self::Bulk, + } + } +} + +/// Abstract physical or tunnel link categories used by the simulator. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum LinkKind { + /// Low-throughput, long-range radio. + SlowRadio, + /// Directional Wi-Fi or comparable fast wireless communication. + FastWireless, + /// Wired fiber or Ethernet-style backhaul. + Wired, + /// A best-effort internet tunnel. + Internet, +} + +impl LinkKind { + /// Returns an illustrative bitrate, not a measured hardware capability. + pub const fn demo_bps(self) -> u64 { + match self { + Self::SlowRadio => 1_000, + Self::FastWireless => 20_000_000, + Self::Wired => 100_000_000, + Self::Internet => 10_000_000, + } + } + + /// Returns illustrative serialization time for `bytes`, rounded up. + /// + /// A zero-byte payload costs one byte, so the result is always at least + /// one millisecond for a nonzero bitrate. + pub const fn transfer_ms(self, bytes: u64) -> u64 { + let bitrate = self.demo_bps() as u128; + if bitrate == 0 { + return u64::MAX; + } + let transfer = ((if bytes == 0 { 1 } else { bytes }) as u128) + .saturating_mul(8_000) + .saturating_add(bitrate - 1) + / bitrate; + if transfer > u64::MAX as u128 { + u64::MAX + } else { + transfer as u64 + } + } + + /// Returns a short display name. + pub const fn label(self) -> &'static str { + match self { + Self::SlowRadio => "LoRa (slow)", + Self::FastWireless => "Wi-Fi (fast)", + Self::Wired => "Wired", + Self::Internet => "Internet", + } + } +} diff --git a/workspace/crates/icenet-core/tests/types.rs b/workspace/crates/icenet-core/tests/types.rs new file mode 100644 index 0000000..fb9d7ca --- /dev/null +++ b/workspace/crates/icenet-core/tests/types.rs @@ -0,0 +1,41 @@ +use icenet_core::{LinkKind, NodeId, ServiceId, TrafficClass}; + +#[test] +fn slow_radio_is_not_allowed_for_bulk() { + assert!(TrafficClass::Text.allows_slow_radio()); + assert!(TrafficClass::Control.allows_slow_radio()); + assert!(!TrafficClass::Bulk.allows_slow_radio()); +} + +#[test] +fn service_id_is_not_limited_to_tcp_ports() { + assert!(ServiceId(77_777).0 > 65_535); + assert_eq!(NodeId(42), NodeId(42)); + assert!(LinkKind::FastWireless.demo_bps() > LinkKind::SlowRadio.demo_bps()); +} + +#[test] +fn transfer_time_uses_ceiling_and_a_nonzero_minimum() { + assert_eq!(LinkKind::SlowRadio.transfer_ms(1), 8); + assert_eq!(LinkKind::Wired.transfer_ms(1), 1); + assert_eq!(LinkKind::FastWireless.transfer_ms(0), 1); + assert_eq!(LinkKind::SlowRadio.transfer_ms(1_000), 8_000); +} + +#[test] +fn class_is_derived_from_size_not_only_from_the_label() { + use TrafficClass::{Bulk, Control, Text}; + assert_eq!( + Control.effective_for(TrafficClass::CONTROL_MAX_BYTES), + Control + ); + assert_eq!( + Control.effective_for(TrafficClass::CONTROL_MAX_BYTES + 1), + Text + ); + assert_eq!(Text.effective_for(TrafficClass::TEXT_MAX_BYTES), Text); + assert_eq!(Text.effective_for(TrafficClass::TEXT_MAX_BYTES + 1), Bulk); + assert_eq!(Control.effective_for(5_000_000), Bulk); + // A Bulk label never shrinks, however small the payload is. + assert_eq!(Bulk.effective_for(1), Bulk); +} diff --git a/workspace/crates/icenet-guard/Cargo.toml b/workspace/crates/icenet-guard/Cargo.toml new file mode 100644 index 0000000..ab74450 --- /dev/null +++ b/workspace/crates/icenet-guard/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "icenet-guard" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } diff --git a/workspace/crates/icenet-guard/src/lib.rs b/workspace/crates/icenet-guard/src/lib.rs new file mode 100644 index 0000000..ca046fd --- /dev/null +++ b/workspace/crates/icenet-guard/src/lib.rs @@ -0,0 +1,131 @@ +//! Deterministic local admission policy: ACL, size, queue, replay and rate. +//! +//! This crate provides no cryptographic authentication. `authenticated` is a +//! test-only input until a reviewed handshake exists. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use std::collections::{BTreeMap, BTreeSet}; + +use icenet_core::{NodeId, ServiceId}; + +mod rate; +mod replay; + +use rate::TokenBucket; +use replay::ReplayWindow; + +/// Configurable local limits for one guard instance. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// Largest accepted payload in bytes. + pub max_payload_bytes: usize, + /// Queue depth at which new work is denied. + pub max_queue_depth: usize, + /// Sustained accepted messages per second; `0` disables rate limiting. + pub rate_per_second: u64, + /// Messages that may be accepted back-to-back after an idle period. + pub burst: u64, + /// Number of recent sequence numbers remembered per peer. + pub replay_window: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_payload_bytes: 4_096, + max_queue_depth: 64, + rate_per_second: 20, + burst: 10, + replay_window: 64, + } + } +} + +/// Input metadata for a local access decision. +#[derive(Clone, Copy, Debug)] +pub struct Context { + /// A test-only authorization hint; NOT real signature verification. + pub authenticated: bool, + /// Sender identity used to scope replay and rate state. + pub peer: NodeId, + /// The requested application service. + pub service: ServiceId, + /// The declared payload size in bytes. + pub payload_bytes: usize, + /// Monotonic sender sequence number for replay protection. + pub sequence: u64, + /// Caller-supplied monotonic time in milliseconds. + pub now_ms: u64, + /// Current pending messages for this peer or service. + pub queue_depth: usize, +} + +/// The local decision and a stable reason identifier. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Verdict { + /// The request passes the configured local policy. + Permit, + /// The request is denied for a deterministic reason. + Deny(&'static str), +} + +/// An allow-list plus bounded replay, rate and queue state. +#[derive(Debug, Clone)] +pub struct Guard { + allowed: BTreeSet, + limits: Limits, + replay: BTreeMap, + buckets: BTreeMap, +} + +impl Guard { + /// Creates a guard with an allowed-service list and explicit limits. + pub fn new(allowed: impl IntoIterator, limits: Limits) -> Self { + Self { + allowed: allowed.into_iter().collect(), + limits, + replay: BTreeMap::new(), + buckets: BTreeMap::new(), + } + } + + /// Checks local policy and consumes replay/rate state only on `Permit`. + /// + /// # Arguments + /// - `context`: sender, service, size, sequence, time and queue pressure. + /// + /// # Returns + /// `Permit` or `Deny(reason)`; denied requests do not consume state. + pub fn check(&mut self, context: Context) -> Verdict { + let limits = self.limits; + if !context.authenticated { + return Verdict::Deny("unauthenticated"); + } + if context.payload_bytes > limits.max_payload_bytes { + return Verdict::Deny("oversized"); + } + if !self.allowed.contains(&context.service) { + return Verdict::Deny("service_denied"); + } + if context.queue_depth >= limits.max_queue_depth { + return Verdict::Deny("queue_full"); + } + let replay = self + .replay + .entry(context.peer) + .or_insert_with(|| ReplayWindow::new(limits.replay_window)); + if !replay.would_admit(context.sequence) { + return Verdict::Deny("replay"); + } + let bucket = self + .buckets + .entry(context.peer) + .or_insert_with(|| TokenBucket::new(limits.burst)); + if !bucket.take(context.now_ms, limits.rate_per_second, limits.burst) { + return Verdict::Deny("rate_limited"); + } + replay.admit(context.sequence); + Verdict::Permit + } +} diff --git a/workspace/crates/icenet-guard/src/rate.rs b/workspace/crates/icenet-guard/src/rate.rs new file mode 100644 index 0000000..c413416 --- /dev/null +++ b/workspace/crates/icenet-guard/src/rate.rs @@ -0,0 +1,38 @@ +//! Deterministic per-peer token bucket using caller-supplied monotonic time. + +/// Allows bursts while enforcing a sustained per-second message rate. +#[derive(Clone, Debug)] +pub(crate) struct TokenBucket { + tokens_milli: u64, + last_ms: u64, +} + +impl TokenBucket { + /// Creates a full bucket that can immediately spend `burst` messages. + pub fn new(burst: u64) -> Self { + Self { + tokens_milli: burst.saturating_mul(1_000), + last_ms: 0, + } + } + + /// Tries to spend one message; a zero rate disables limiting. + pub fn take(&mut self, now_ms: u64, rate_per_second: u64, burst: u64) -> bool { + if rate_per_second == 0 { + return true; + } + let capacity = burst.saturating_mul(1_000); + let elapsed = now_ms.saturating_sub(self.last_ms); + self.tokens_milli = self + .tokens_milli + .saturating_add(elapsed.saturating_mul(rate_per_second)) + .min(capacity); + self.last_ms = self.last_ms.max(now_ms); + if self.tokens_milli >= 1_000 { + self.tokens_milli -= 1_000; + true + } else { + false + } + } +} diff --git a/workspace/crates/icenet-guard/src/replay.rs b/workspace/crates/icenet-guard/src/replay.rs new file mode 100644 index 0000000..db1b461 --- /dev/null +++ b/workspace/crates/icenet-guard/src/replay.rs @@ -0,0 +1,52 @@ +//! Per-peer anti-replay sliding window over monotonic sequence numbers. +use std::collections::BTreeSet; + +/// Remembers the newest sequence numbers accepted from one peer. +#[derive(Clone, Debug)] +pub(crate) struct ReplayWindow { + window: u64, + highest: Option, + seen: BTreeSet, +} + +impl ReplayWindow { + /// Creates a window of at least one sequence slot. + pub fn new(window: u64) -> Self { + Self { + window: window.max(1), + highest: None, + seen: BTreeSet::new(), + } + } + + /// Returns whether `sequence` would be accepted without changing state. + pub fn would_admit(&self, sequence: u64) -> bool { + let Some(highest) = self.highest else { + return true; + }; + if sequence > highest { + return true; + } + let cutoff = highest.saturating_sub(self.window - 1); + sequence >= cutoff && !self.seen.contains(&sequence) + } + + /// Records an accepted sequence and prunes entries outside the window. + pub fn admit(&mut self, sequence: u64) { + match self.highest { + None => { + self.highest = Some(sequence); + self.seen.insert(sequence); + } + Some(highest) if sequence > highest => { + self.highest = Some(sequence); + self.seen.insert(sequence); + let cutoff = sequence.saturating_sub(self.window - 1); + self.seen.retain(|value| *value >= cutoff); + } + Some(_) => { + self.seen.insert(sequence); + } + } + } +} diff --git a/workspace/crates/icenet-guard/tests/policy.rs b/workspace/crates/icenet-guard/tests/policy.rs new file mode 100644 index 0000000..9b90da7 --- /dev/null +++ b/workspace/crates/icenet-guard/tests/policy.rs @@ -0,0 +1,46 @@ +use icenet_core::{NodeId, ServiceId}; +use icenet_guard::{Context, Guard, Limits, Verdict}; + +fn context() -> Context { + Context { + authenticated: true, + peer: NodeId(1), + service: ServiceId(77_777), + payload_bytes: 5, + sequence: 1, + now_ms: 0, + queue_depth: 0, + } +} + +fn limits() -> Limits { + Limits { + max_payload_bytes: 128, + ..Limits::default() + } +} + +#[test] +fn denies_untrusted_and_unknown_service() { + let mut guard = Guard::new([ServiceId(77_777)], limits()); + let mut request = context(); + request.authenticated = false; + assert_eq!(guard.check(request), Verdict::Deny("unauthenticated")); + request.authenticated = true; + request.service = ServiceId(1); + assert_eq!(guard.check(request), Verdict::Deny("service_denied")); +} + +#[test] +fn permits_bounded_known_service() { + let mut guard = Guard::new([ServiceId(77_777)], limits()); + assert_eq!(guard.check(context()), Verdict::Permit); +} + +#[test] +fn denies_oversized_payload() { + let mut guard = Guard::new([ServiceId(77_777)], limits()); + let mut request = context(); + request.payload_bytes = 129; + assert_eq!(guard.check(request), Verdict::Deny("oversized")); +} diff --git a/workspace/crates/icenet-guard/tests/queue.rs b/workspace/crates/icenet-guard/tests/queue.rs new file mode 100644 index 0000000..5dd9108 --- /dev/null +++ b/workspace/crates/icenet-guard/tests/queue.rs @@ -0,0 +1,37 @@ +use icenet_core::{NodeId, ServiceId}; +use icenet_guard::{Context, Guard, Limits, Verdict}; + +fn context(queue_depth: usize, sequence: u64) -> Context { + Context { + authenticated: true, + peer: NodeId(1), + service: ServiceId(7), + payload_bytes: 1, + sequence, + now_ms: 0, + queue_depth, + } +} + +#[test] +fn full_queue_is_denied_before_accepting_more_work() { + let limits = Limits { + max_queue_depth: 2, + rate_per_second: 0, + ..Limits::default() + }; + let mut guard = Guard::new([ServiceId(7)], limits); + assert_eq!(guard.check(context(1, 1)), Verdict::Permit); + assert_eq!(guard.check(context(2, 2)), Verdict::Deny("queue_full")); +} + +#[test] +fn empty_queue_below_the_cap_is_permitted() { + let limits = Limits { + max_queue_depth: 2, + rate_per_second: 0, + ..Limits::default() + }; + let mut guard = Guard::new([ServiceId(7)], limits); + assert_eq!(guard.check(context(0, 1)), Verdict::Permit); +} diff --git a/workspace/crates/icenet-guard/tests/rate.rs b/workspace/crates/icenet-guard/tests/rate.rs new file mode 100644 index 0000000..353fa36 --- /dev/null +++ b/workspace/crates/icenet-guard/tests/rate.rs @@ -0,0 +1,52 @@ +use icenet_core::{NodeId, ServiceId}; +use icenet_guard::{Context, Guard, Limits, Verdict}; + +fn limits(rate: u64, burst: u64) -> Limits { + Limits { + rate_per_second: rate, + burst, + replay_window: 64, + ..Limits::default() + } +} + +fn context(peer: u64, sequence: u64, now_ms: u64) -> Context { + Context { + authenticated: true, + peer: NodeId(peer), + service: ServiceId(7), + payload_bytes: 1, + sequence, + now_ms, + queue_depth: 0, + } +} + +#[test] +fn burst_is_allowed_then_requests_are_limited_until_refill() { + let mut guard = Guard::new([ServiceId(7)], limits(2, 2)); + assert_eq!(guard.check(context(1, 1, 0)), Verdict::Permit); + assert_eq!(guard.check(context(1, 2, 0)), Verdict::Permit); + assert_eq!(guard.check(context(1, 3, 0)), Verdict::Deny("rate_limited")); + assert_eq!(guard.check(context(1, 4, 500)), Verdict::Permit); + assert_eq!( + guard.check(context(1, 5, 500)), + Verdict::Deny("rate_limited") + ); +} + +#[test] +fn rate_buckets_are_per_peer() { + let mut guard = Guard::new([ServiceId(7)], limits(1, 1)); + assert_eq!(guard.check(context(1, 1, 0)), Verdict::Permit); + assert_eq!(guard.check(context(1, 2, 0)), Verdict::Deny("rate_limited")); + assert_eq!(guard.check(context(2, 1, 0)), Verdict::Permit); +} + +#[test] +fn zero_rate_disables_limiting() { + let mut guard = Guard::new([ServiceId(7)], limits(0, 0)); + for sequence in 0..50 { + assert_eq!(guard.check(context(1, sequence, 0)), Verdict::Permit); + } +} diff --git a/workspace/crates/icenet-guard/tests/replay.rs b/workspace/crates/icenet-guard/tests/replay.rs new file mode 100644 index 0000000..0d5df32 --- /dev/null +++ b/workspace/crates/icenet-guard/tests/replay.rs @@ -0,0 +1,54 @@ +use icenet_core::{NodeId, ServiceId}; +use icenet_guard::{Context, Guard, Limits, Verdict}; + +fn limits(window: u64) -> Limits { + Limits { + replay_window: window, + rate_per_second: 0, + ..Limits::default() + } +} + +fn context(peer: u64, sequence: u64) -> Context { + Context { + authenticated: true, + peer: NodeId(peer), + service: ServiceId(7), + payload_bytes: 1, + sequence, + now_ms: 0, + queue_depth: 0, + } +} + +#[test] +fn duplicate_sequence_is_denied() { + let mut guard = Guard::new([ServiceId(7)], limits(4)); + assert_eq!(guard.check(context(1, 1)), Verdict::Permit); + assert_eq!(guard.check(context(1, 1)), Verdict::Deny("replay")); +} + +#[test] +fn sequence_below_the_window_is_denied() { + let mut guard = Guard::new([ServiceId(7)], limits(4)); + assert_eq!(guard.check(context(1, 10)), Verdict::Permit); + assert_eq!(guard.check(context(1, 6)), Verdict::Deny("replay")); + assert_eq!(guard.check(context(1, 7)), Verdict::Permit); +} + +#[test] +fn higher_sequence_advances_and_prunes_the_window() { + let mut guard = Guard::new([ServiceId(7)], limits(4)); + assert_eq!(guard.check(context(1, 4)), Verdict::Permit); + assert_eq!(guard.check(context(1, 5)), Verdict::Permit); + assert_eq!(guard.check(context(1, 1)), Verdict::Deny("replay")); + assert_eq!(guard.check(context(1, 2)), Verdict::Permit); +} + +#[test] +fn replay_state_is_per_peer() { + let mut guard = Guard::new([ServiceId(7)], limits(4)); + assert_eq!(guard.check(context(1, 5)), Verdict::Permit); + assert_eq!(guard.check(context(2, 5)), Verdict::Permit); + assert_eq!(guard.check(context(2, 5)), Verdict::Deny("replay")); +} diff --git a/workspace/crates/icenet-routing/Cargo.toml b/workspace/crates/icenet-routing/Cargo.toml new file mode 100644 index 0000000..1cbd462 --- /dev/null +++ b/workspace/crates/icenet-routing/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "icenet-routing" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } diff --git a/workspace/crates/icenet-routing/src/lib.rs b/workspace/crates/icenet-routing/src/lib.rs new file mode 100644 index 0000000..f072df3 --- /dev/null +++ b/workspace/crates/icenet-routing/src/lib.rs @@ -0,0 +1,138 @@ +//! Deterministic, constrained shortest-path selection for graph experiments. +//! +//! This crate does not claim to predict radio-wave propagation. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use std::cmp::Reverse; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; + +use icenet_core::{LinkKind, NodeId, TrafficClass}; + +/// Fixed per-hop framing and turnaround cost, in milliseconds of airtime. +pub const HOP_OVERHEAD_MS: u64 = 10; + +/// An undirected available/disabled link in the simulated topology. +#[derive(Clone, Copy, Debug)] +pub struct Link { + /// First endpoint. + pub a: NodeId, + /// Second endpoint. + pub b: NodeId, + /// Category used for eligibility and nominal throughput. + pub kind: LinkKind, + /// Whether the link is currently available. + pub enabled: bool, +} + +/// Result of a constrained route lookup. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Path { + /// Ordered endpoint IDs, including source and destination. + pub nodes: Vec, + /// Index into the `links` slice of every hop, in travel order. + /// + /// Parallel links between the same two nodes stay distinguishable. + pub links: Vec, + /// Illustrative serialization latency, not a real RTT estimate. + pub estimated_ms: u64, +} + +/// Returns a deterministic eligible path, or `None` when disconnected. +/// +/// # Arguments +/// - `nodes`: Active node IDs in the simulated graph. +/// - `links`: Candidate undirected links. +/// - `class`: Declared class; it is raised to the size-derived effective class +/// (see [`TrafficClass::effective_for`]) before slow radio links are judged. +/// - `size_bytes`: Data size for illustrative weighted costs. +/// +/// # Returns +/// A path optimized for approximate serialization cost. +#[must_use] +pub fn choose_path( + nodes: &[NodeId], + links: &[Link], + source: NodeId, + destination: NodeId, + class: TrafficClass, + size_bytes: u64, +) -> Option { + let class = class.effective_for(size_bytes); + let active: BTreeSet = nodes.iter().copied().collect(); + if !active.contains(&source) || !active.contains(&destination) { + return None; + } + let mut distances = BTreeMap::::new(); + let mut previous = BTreeMap::::new(); + let mut seen = BTreeSet::::new(); + let mut frontier = BinaryHeap::>::new(); + let mut adjacency = BTreeMap::>::new(); + for (index, link) in links.iter().enumerate().filter(|(_, link)| link.enabled) { + if !active.contains(&link.a) || !active.contains(&link.b) { + continue; + } + adjacency + .entry(link.a) + .or_default() + .push((link.b, link.kind, index)); + adjacency + .entry(link.b) + .or_default() + .push((link.a, link.kind, index)); + } + distances.insert(source, 0); + frontier.push(Reverse((0, source))); + while let Some(Reverse((cost, current))) = frontier.pop() { + if !seen.insert(current) { + continue; + } + if current == destination { + break; + } + let Some(neighbours) = adjacency.get(¤t) else { + continue; + }; + for &(next, kind, index) in neighbours { + if kind == LinkKind::SlowRadio && !class.allows_slow_radio() { + continue; + } + if seen.contains(&next) { + continue; + } + let transfer_ms = u128::from(kind.transfer_ms(size_bytes)); + let proposed = cost + .saturating_add(transfer_ms) + .saturating_add(u128::from(HOP_OVERHEAD_MS)); + let known = distances.get(&next).copied(); + if known.is_none_or(|value| proposed < value) { + distances.insert(next, proposed); + previous.insert(next, (current, index)); + frontier.push(Reverse((proposed, next))); + } else if known == Some(proposed) + && previous + .get(&next) + .is_some_and(|&(parent, parent_link)| (current, index) < (parent, parent_link)) + { + previous.insert(next, (current, index)); + } + } + } + let cost = *distances.get(&destination)?; + let mut steps = vec![destination]; + let mut used = Vec::new(); + let mut node = destination; + while node != source { + let &(parent, link) = previous.get(&node)?; + node = parent; + steps.push(node); + used.push(link); + } + steps.reverse(); + used.reverse(); + Some(Path { + nodes: steps, + links: used, + estimated_ms: u64::try_from(cost).unwrap_or(u64::MAX), + }) +} diff --git a/workspace/crates/icenet-routing/tests/routing.rs b/workspace/crates/icenet-routing/tests/routing.rs new file mode 100644 index 0000000..b7593ac --- /dev/null +++ b/workspace/crates/icenet-routing/tests/routing.rs @@ -0,0 +1,111 @@ +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_routing::{Link, choose_path}; + +#[test] +fn bulk_never_uses_slow_radio() { + let nodes = [NodeId(1), NodeId(2), NodeId(3)]; + let links = [ + Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::SlowRadio, + enabled: true, + }, + Link { + a: nodes[1], + b: nodes[2], + kind: LinkKind::SlowRadio, + enabled: true, + }, + ]; + assert!( + choose_path( + &nodes, + &links, + nodes[0], + nodes[2], + TrafficClass::Bulk, + 50_000 + ) + .is_none() + ); + assert!(choose_path(&nodes, &links, nodes[0], nodes[2], TrafficClass::Text, 10).is_some()); +} + +#[test] +fn chooses_fast_route_when_bulk_is_allowed() { + let nodes = [NodeId(1), NodeId(2), NodeId(3)]; + let links = [ + Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::FastWireless, + enabled: true, + }, + Link { + a: nodes[1], + b: nodes[2], + kind: LinkKind::Wired, + enabled: true, + }, + ]; + let chosen = choose_path( + &nodes, + &links, + nodes[0], + nodes[2], + TrafficClass::Bulk, + 5_000_000, + ); + assert_eq!(chosen.expect("connected").nodes, nodes); +} + +#[test] +fn disabled_bridge_breaks_route() { + let nodes = [NodeId(1), NodeId(2)]; + let links = [Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::Wired, + enabled: false, + }]; + assert!(choose_path(&nodes, &links, nodes[0], nodes[1], TrafficClass::Text, 5).is_none()); +} + +#[test] +fn equal_cost_paths_use_a_stable_lexicographic_tie_break() { + let nodes = [NodeId(1), NodeId(2), NodeId(3), NodeId(4)]; + let forward = [ + Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::Wired, + enabled: true, + }, + Link { + a: nodes[1], + b: nodes[3], + kind: LinkKind::Wired, + enabled: true, + }, + Link { + a: nodes[0], + b: nodes[2], + kind: LinkKind::Wired, + enabled: true, + }, + Link { + a: nodes[2], + b: nodes[3], + kind: LinkKind::Wired, + enabled: true, + }, + ]; + let mut reversed = forward; + reversed.reverse(); + for links in [&forward, &reversed] { + let path = choose_path(&nodes, links, nodes[0], nodes[3], TrafficClass::Text, 10) + .expect("diamond is connected"); + assert_eq!(path.nodes, [NodeId(1), NodeId(2), NodeId(4)]); + } +} diff --git a/workspace/crates/icenet-routing/tests/size_limits.rs b/workspace/crates/icenet-routing/tests/size_limits.rs new file mode 100644 index 0000000..4c13095 --- /dev/null +++ b/workspace/crates/icenet-routing/tests/size_limits.rs @@ -0,0 +1,79 @@ +//! Size limits: a payload label cannot smuggle bulk data onto a slow radio. +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_routing::{Link, choose_path}; + +fn slow_pair() -> ([NodeId; 2], [Link; 1]) { + let nodes = [NodeId(1), NodeId(2)]; + let links = [Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::SlowRadio, + enabled: true, + }]; + (nodes, links) +} + +#[test] +fn oversized_text_is_treated_as_bulk_and_refused_on_slow_radio() { + let (nodes, links) = slow_pair(); + let at_limit = TrafficClass::TEXT_MAX_BYTES; + assert!( + choose_path( + &nodes, + &links, + nodes[0], + nodes[1], + TrafficClass::Text, + at_limit + ) + .is_some() + ); + assert!( + choose_path( + &nodes, + &links, + nodes[0], + nodes[1], + TrafficClass::Text, + at_limit + 1 + ) + .is_none() + ); +} + +#[test] +fn oversized_control_is_treated_as_text_then_bulk() { + let (nodes, links) = slow_pair(); + let control = TrafficClass::Control; + let just_over = TrafficClass::CONTROL_MAX_BYTES + 1; + assert!(choose_path(&nodes, &links, nodes[0], nodes[1], control, just_over).is_some()); + assert!(choose_path(&nodes, &links, nodes[0], nodes[1], control, 1_000_000).is_none()); +} + +#[test] +fn path_reports_the_index_of_every_link_it_uses() { + let nodes = [NodeId(1), NodeId(2), NodeId(3)]; + let links = [ + Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::SlowRadio, + enabled: false, + }, + Link { + a: nodes[0], + b: nodes[1], + kind: LinkKind::Wired, + enabled: true, + }, + Link { + a: nodes[1], + b: nodes[2], + kind: LinkKind::Wired, + enabled: true, + }, + ]; + let path = + choose_path(&nodes, &links, nodes[0], nodes[2], TrafficClass::Text, 10).expect("connected"); + assert_eq!(path.links, [1, 2]); +} diff --git a/workspace/crates/icenet-sdk/Cargo.toml b/workspace/crates/icenet-sdk/Cargo.toml new file mode 100644 index 0000000..257cf8e --- /dev/null +++ b/workspace/crates/icenet-sdk/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "icenet-sdk" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } +icenet-wire = { path = "../icenet-wire" } +icenet-guard = { path = "../icenet-guard" } +icenet-transport = { path = "../icenet-transport" } diff --git a/workspace/crates/icenet-sdk/src/lib.rs b/workspace/crates/icenet-sdk/src/lib.rs new file mode 100644 index 0000000..0c4f8ba --- /dev/null +++ b/workspace/crates/icenet-sdk/src/lib.rs @@ -0,0 +1,28 @@ +//! An early public facade for application developers. +//! +//! There is no networking daemon or authenticated handshake in this scaffold. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub use icenet_core::{NodeId, ServiceId, TrafficClass}; +pub use icenet_guard::{Context, Guard, Limits, Verdict}; +pub use icenet_transport::{ + MAX_DATAGRAM_BYTES, MemoryTransport, Transport, TransportError, UdpTransport, +}; +pub use icenet_wire::{Frame, FrameError, decode, encode}; + +/// Builds an encoded *local test* message without cryptographic protection. +/// +/// # Errors +/// Returns a `FrameError` for oversized frames. +pub fn encode_message( + service: ServiceId, + class: TrafficClass, + text: &[u8], +) -> Result, FrameError> { + icenet_wire::encode(&Frame { + service, + class, + payload: text.to_vec(), + }) +} diff --git a/workspace/crates/icenet-sdk/tests/facade.rs b/workspace/crates/icenet-sdk/tests/facade.rs new file mode 100644 index 0000000..68ab066 --- /dev/null +++ b/workspace/crates/icenet-sdk/tests/facade.rs @@ -0,0 +1,7 @@ +use icenet_sdk::{ServiceId, TrafficClass, encode_message}; + +#[test] +fn sdk_constructs_bounded_frames() { + let bytes = encode_message(ServiceId(77_777), TrafficClass::Text, b"hi").unwrap(); + assert!(!bytes.is_empty()); +} diff --git a/workspace/crates/icenet-sdk/tests/udp_roundtrip.rs b/workspace/crates/icenet-sdk/tests/udp_roundtrip.rs new file mode 100644 index 0000000..035c926 --- /dev/null +++ b/workspace/crates/icenet-sdk/tests/udp_roundtrip.rs @@ -0,0 +1,33 @@ +//! End-to-end frame exchange over a real UDP loopback pair. +use std::time::{Duration, Instant}; + +use icenet_sdk::{Frame, ServiceId, TrafficClass, Transport, UdpTransport, decode, encode}; + +#[test] +fn encoded_frame_survives_a_udp_round_trip() { + let first = UdpTransport::bind("127.0.0.1:0").expect("bind first"); + let second = UdpTransport::bind("127.0.0.1:0").expect("bind second"); + let first_addr = first.local_addr().expect("first address"); + let second_addr = second.local_addr().expect("second address"); + let mut sender = first.connect(second_addr).expect("connect sender"); + let mut receiver = second.connect(first_addr).expect("connect receiver"); + + let frame = Frame { + class: TrafficClass::Text, + service: ServiceId(77_777), + payload: b"hello over udp".to_vec(), + }; + sender.send(encode(&frame).expect("encode")).expect("send"); + + let deadline = Instant::now() + Duration::from_secs(2); + let mut received = None; + while Instant::now() < deadline { + if let Some(bytes) = receiver.recv().expect("recv") { + received = Some(bytes); + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + let bytes = received.expect("frame within deadline"); + assert_eq!(decode(&bytes), Ok(frame)); +} diff --git a/workspace/crates/icenet-sim/Cargo.toml b/workspace/crates/icenet-sim/Cargo.toml new file mode 100644 index 0000000..aea448c --- /dev/null +++ b/workspace/crates/icenet-sim/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "icenet-sim" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } +icenet-routing = { path = "../icenet-routing" } diff --git a/workspace/crates/icenet-sim/src/engine/ledger.rs b/workspace/crates/icenet-sim/src/engine/ledger.rs new file mode 100644 index 0000000..cbd38da --- /dev/null +++ b/workspace/crates/icenet-sim/src/engine/ledger.rs @@ -0,0 +1,101 @@ +//! Per-link airtime reservations: a link carries one transmission at a time. +use icenet_routing::HOP_OVERHEAD_MS; + +use crate::SimLink; + +/// One reserved transmission interval on a link. +#[derive(Clone, Copy, Debug)] +struct Slot { + begin: u64, + end: u64, + owner: u64, +} + +/// Reservation calendar for every link, indexed like `City::links`. +/// +/// Slots on one link never overlap and are kept sorted by start time, so +/// later reservations queue behind earlier ones and may reuse freed gaps. +#[derive(Clone, Debug, Default)] +pub(super) struct LinkLedger { + slots: Vec>, + spent_ms: Vec, +} + +impl LinkLedger { + /// Reserves each hop in order and returns the arrival time at the end. + /// + /// The result is always at least one millisecond after `start_ms`. + pub fn reserve_path( + &mut self, + links: &[SimLink], + hops: &[usize], + bytes: u64, + start_ms: u64, + owner: u64, + ) -> u64 { + let mut ready = start_ms; + for &index in hops { + let hop_ms = links[index] + .kind + .transfer_ms(bytes) + .saturating_add(HOP_OVERHEAD_MS); + ready = self.reserve(index, ready, hop_ms, owner); + } + ready.max(start_ms.saturating_add(1)) + } + + /// Frees the not-yet-started slots of `owner`; started airtime stays spent. + pub fn release(&mut self, owner: u64, now_ms: u64) { + for (slots, spent) in self.slots.iter_mut().zip(self.spent_ms.iter_mut()) { + slots.retain(|slot| { + let free = slot.owner == owner && slot.begin >= now_ms; + if free { + *spent = spent.saturating_sub(slot.end - slot.begin); + } + !free + }); + } + } + + /// Forgets slots that finished at or before `now_ms`; totals are kept. + pub fn prune(&mut self, now_ms: u64) { + for slots in &mut self.slots { + slots.retain(|slot| slot.end > now_ms); + } + } + + /// Total airtime reserved on one link, in milliseconds. + pub fn airtime_ms(&self, link: usize) -> u64 { + self.spent_ms.get(link).copied().unwrap_or(0) + } + + /// Milliseconds from `now_ms` until the last reservation on `link` ends. + pub fn backlog_ms(&self, link: usize, now_ms: u64) -> u64 { + let last = self.slots.get(link).and_then(|slots| slots.last()); + last.map_or(0, |slot| slot.end.saturating_sub(now_ms)) + } + + fn reserve(&mut self, link: usize, ready_ms: u64, duration_ms: u64, owner: u64) -> u64 { + if self.slots.len() <= link { + self.slots.resize_with(link + 1, Vec::new); + self.spent_ms.resize(link + 1, 0); + } + let slots = &mut self.slots[link]; + let mut begin = ready_ms; + let mut position = slots.len(); + for (index, slot) in slots.iter().enumerate() { + if slot.end <= begin { + continue; + } + if slot.begin >= begin.saturating_add(duration_ms) { + position = index; + break; + } + begin = slot.end; + } + let end = begin.saturating_add(duration_ms); + slots.insert(position, Slot { begin, end, owner }); + self.spent_ms[link] = self.spent_ms[link].saturating_add(duration_ms); + end + } +} diff --git a/workspace/crates/icenet-sim/src/engine/mod.rs b/workspace/crates/icenet-sim/src/engine/mod.rs new file mode 100644 index 0000000..ecf0add --- /dev/null +++ b/workspace/crates/icenet-sim/src/engine/mod.rs @@ -0,0 +1,169 @@ +//! Virtual time and deterministic state transitions for the city model. +use crate::{DeliveryState, Device, DeviceRole, Message, SimLink}; +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_routing::{Link, Path, choose_path}; + +mod ledger; +mod tick; + +use ledger::LinkLedger; + +/// Mutable state of one in-memory city simulation. +#[derive(Clone, Debug)] +pub struct City { + /// Available virtual devices. + pub devices: Vec, + /// Simulated point-to-point links. + pub links: Vec, + /// Recorded synthetic application messages. + pub messages: Vec, + /// Current deterministic simulation time in milliseconds. + pub now_ms: u64, + next_message_id: u64, + ledger: LinkLedger, +} + +impl City { + /// Default message lifetime: 24 simulated hours. + pub const DEFAULT_TTL_MS: u64 = 86_400_000; + + /// Returns an empty simulation for custom scenario construction. + pub fn empty() -> Self { + Self { + devices: Vec::new(), + links: Vec::new(), + messages: Vec::new(), + now_ms: 0, + next_message_id: 1, + ledger: LinkLedger::default(), + } + } + + /// Returns a six-device topology with redundant slow and fast paths. + pub fn demo() -> Self { + let spec = [ + (1, "Phone A", 70.0, 85.0, DeviceRole::Client), + (2, "LoRa relay", 175.0, 70.0, DeviceRole::Relay), + (3, "Friend B", 410.0, 95.0, DeviceRole::Client), + (4, "Rooftop", 185.0, 205.0, DeviceRole::Relay), + (5, "Backbone", 335.0, 200.0, DeviceRole::Backbone), + (6, "Remote", 480.0, 230.0, DeviceRole::Client), + ]; + let devices = spec + .into_iter() + .map(|(id, name, x, y, role)| Device { + id: NodeId(id), + label: name.to_owned(), + x, + y, + role, + online: true, + }) + .collect(); + let links = [ + (1, 2, LinkKind::SlowRadio), + (2, 3, LinkKind::SlowRadio), + (1, 4, LinkKind::FastWireless), + (4, 5, LinkKind::Wired), + (5, 3, LinkKind::FastWireless), + (5, 6, LinkKind::FastWireless), + (2, 4, LinkKind::SlowRadio), + ] + .into_iter() + .map(|(a, b, kind)| SimLink { + a: NodeId(a), + b: NodeId(b), + kind, + enabled: true, + }) + .collect(); + Self { + devices, + links, + messages: Vec::new(), + now_ms: 0, + next_message_id: 1, + ledger: LinkLedger::default(), + } + } + + /// Returns a route for a class and size under the current topology. + pub fn route(&self, from: NodeId, to: NodeId, class: TrafficClass, bytes: u64) -> Option { + let active: Vec = self + .devices + .iter() + .filter(|d| d.online) + .map(|d| d.id) + .collect(); + let links = self + .links + .iter() + .map(|link| Link { + a: link.a, + b: link.b, + kind: link.kind, + enabled: link.enabled, + }) + .collect::>(); + choose_path(&active, &links, from, to, class, bytes) + } + + /// Creates a message with the default lifetime and queues it when necessary. + pub fn send(&mut self, from: NodeId, to: NodeId, class: TrafficClass, bytes: u64) -> u64 { + self.send_with_ttl(from, to, class, bytes, Self::DEFAULT_TTL_MS) + } + + /// Creates a message with an explicit lifetime in simulated milliseconds. + /// + /// An undelivered message expires once `now_ms` reaches + /// `created_ms + ttl_ms`; expired messages are never retried. The declared + /// `class` is raised to the size-derived class before routing. + pub fn send_with_ttl( + &mut self, + from: NodeId, + to: NodeId, + class: TrafficClass, + bytes: u64, + ttl_ms: u64, + ) -> u64 { + let id = self.next_message_id; + self.next_message_id = self.next_message_id.saturating_add(1); + self.messages.push(Message { + id, + from, + to, + class, + bytes, + status: DeliveryState::Queued, + created_ms: self.now_ms, + expires_ms: self.now_ms.saturating_add(ttl_ms.max(1)), + first_route_ms: None, + estimated_ms: 0, + due_ms: None, + route: Vec::new(), + route_links: Vec::new(), + }); + if let Some(path) = self.route(from, to, class, bytes) { + self.schedule(self.messages.len() - 1, path); + } + id + } + + /// Returns the airtime ever reserved on links of `kind`, in milliseconds. + /// + /// Reservations released before they started are not counted. + pub fn link_airtime_ms(&self, kind: LinkKind) -> u64 { + let mut total = 0_u64; + for (index, link) in self.links.iter().enumerate() { + if link.kind == kind { + total = total.saturating_add(self.ledger.airtime_ms(index)); + } + } + total + } + + /// Returns how long link `index` stays busy from now, in milliseconds. + pub fn link_backlog_ms(&self, index: usize) -> u64 { + self.ledger.backlog_ms(index, self.now_ms) + } +} diff --git a/workspace/crates/icenet-sim/src/engine/tick.rs b/workspace/crates/icenet-sim/src/engine/tick.rs new file mode 100644 index 0000000..6fa9401 --- /dev/null +++ b/workspace/crates/icenet-sim/src/engine/tick.rs @@ -0,0 +1,114 @@ +//! Time advance: delivery, expiry, re-planning and queueing of messages. +use icenet_core::{LinkKind, NodeId}; +use icenet_routing::Path; + +use super::City; +use crate::{DeliveryState, Message}; + +impl City { + /// Advances virtual time and updates delivery state without sleeping. + /// + /// Topology edits only happen between ticks, so the topology seen here has + /// held for the whole elapsed interval. A message is therefore delivered + /// only if its planned route is still usable now; a coarse step can never + /// jump over a link cut into a false `Delivered`. + pub fn tick(&mut self, elapsed_ms: u64) { + self.now_ms = self.now_ms.saturating_add(elapsed_ms); + self.ledger.prune(self.now_ms); + for index in 0..self.messages.len() { + let message = &self.messages[index]; + if matches!( + message.status, + DeliveryState::Delivered | DeliveryState::Expired + ) { + continue; + } + let usable = message.status == DeliveryState::InFlight && self.route_is_usable(message); + let (id, expires_ms, due_ms) = (message.id, message.expires_ms, message.due_ms); + // Arrival at or before the deadline wins even when one coarse tick + // jumps past both timestamps, provided the route survived. + if usable && due_ms.is_some_and(|due| due <= self.now_ms && due <= expires_ms) { + self.messages[index].status = DeliveryState::Delivered; + continue; + } + if self.now_ms >= expires_ms { + self.ledger.release(id, self.now_ms); + let message = &mut self.messages[index]; + message.status = DeliveryState::Expired; + message.clear_plan(); + continue; + } + let message = &self.messages[index]; + let fresh = self.route(message.from, message.to, message.class, message.bytes); + match fresh { + None => { + self.ledger.release(id, self.now_ms); + let message = &mut self.messages[index]; + message.status = DeliveryState::Queued; + message.clear_plan(); + } + Some(path) => { + let message = &self.messages[index]; + let unchanged = message.status == DeliveryState::InFlight + && usable + && path.nodes == message.route + && path.links == message.route_links + && path.estimated_ms == message.estimated_ms; + if !unchanged { + self.schedule(index, path); + } + } + } + } + } + + /// Plans `path` for message `index`, replacing any earlier reservation. + /// + /// A re-plan restarts the transfer from the source: airtime already spent + /// is not refunded, and only slots that have not started are released. + pub(super) fn schedule(&mut self, index: usize, path: Path) { + let (id, bytes) = (self.messages[index].id, self.messages[index].bytes); + self.ledger.release(id, self.now_ms); + let due = self + .ledger + .reserve_path(&self.links, &path.links, bytes, self.now_ms, id); + let message = &mut self.messages[index]; + message.status = DeliveryState::InFlight; + if message.first_route_ms.is_none() { + message.first_route_ms = Some(self.now_ms); + } + message.estimated_ms = path.estimated_ms; + message.due_ms = Some(due); + message.route = path.nodes; + message.route_links = path.links; + } + + /// Returns whether every device and link of the planned route is usable now. + fn route_is_usable(&self, message: &Message) -> bool { + let route = &message.route; + let hops = &message.route_links; + if route.is_empty() || route.len() != hops.len() + 1 { + return false; + } + let class = message.class.effective_for(message.bytes); + let online = |id: &NodeId| self.devices.iter().any(|d| d.id == *id && d.online); + route.iter().all(online) + && route.windows(2).zip(hops).all(|(pair, &index)| { + self.links.get(index).is_some_and(|link| { + let joins = (link.a == pair[0] && link.b == pair[1]) + || (link.a == pair[1] && link.b == pair[0]); + let eligible = class.allows_slow_radio() || link.kind != LinkKind::SlowRadio; + link.enabled && joins && eligible + }) + }) + } +} + +impl Message { + fn clear_plan(&mut self) { + self.due_ms = None; + self.estimated_ms = 0; + self.route.clear(); + self.route_links.clear(); + } +} diff --git a/workspace/crates/icenet-sim/src/lib.rs b/workspace/crates/icenet-sim/src/lib.rs new file mode 100644 index 0000000..b4d8a49 --- /dev/null +++ b/workspace/crates/icenet-sim/src/lib.rs @@ -0,0 +1,14 @@ +//! Deterministic graph simulator for ICE-NET traffic policies. +//! +//! Links carry one transmission at a time (see `City::link_airtime_ms`). +//! RF physics, cryptography, NAT and real sockets are out of scope. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod engine; +pub mod metrics; +mod model; +mod topology; + +pub use engine::City; +pub use model::{DeliveryState, Device, DeviceRole, Message, SimLink}; diff --git a/workspace/crates/icenet-sim/src/metrics/export.rs b/workspace/crates/icenet-sim/src/metrics/export.rs new file mode 100644 index 0000000..30337ec --- /dev/null +++ b/workspace/crates/icenet-sim/src/metrics/export.rs @@ -0,0 +1,171 @@ +//! Deterministic CSV and JSON serialization for city experiments. +use std::fmt::Write as _; + +use icenet_core::{LinkKind, TrafficClass}; + +use crate::{City, DeliveryState, DeviceRole, Message}; + +/// Exports one CSV row per message in creation order. +pub fn messages_csv(city: &City) -> String { + let mut out = String::from( + "id,from,to,class,bytes,status,created_ms,expires_ms,first_route_ms,due_ms,route\n", + ); + for message in &city.messages { + let route = message + .route + .iter() + .map(|node| node.0.to_string()) + .collect::>() + .join("-"); + writeln!( + out, + "{},{},{},{},{},{},{},{},{},{},{}", + message.id, + message.from.0, + message.to.0, + class_name(message.class), + message.bytes, + status_name(message.status), + message.created_ms, + message.expires_ms, + optional(message.first_route_ms), + optional(message.due_ms), + route + ) + .expect("writing into a String cannot fail"); + } + out +} + +/// Exports the whole scenario as deterministic, dependency-free JSON. +pub fn scenario_json(city: &City) -> String { + let mut out = String::from("{\n"); + writeln!(out, " \"now_ms\": {},", city.now_ms).expect("String write"); + out.push_str(" \"devices\": ["); + for (index, device) in city.devices.iter().enumerate() { + out.push_str(if index == 0 { "\n" } else { ",\n" }); + write!( + out, + " {{\"id\":{},\"label\":\"{}\",\"x\":{},\"y\":{},\"role\":\"{}\",\"online\":{}}}", + device.id.0, + escape(&device.label), + coordinate(device.x), + coordinate(device.y), + role_name(device.role), + device.online + ) + .expect("String write"); + } + out.push_str("\n ],\n \"links\": ["); + for (index, link) in city.links.iter().enumerate() { + out.push_str(if index == 0 { "\n" } else { ",\n" }); + write!( + out, + " {{\"a\":{},\"b\":{},\"kind\":\"{}\",\"enabled\":{}}}", + link.a.0, + link.b.0, + link_kind_name(link.kind), + link.enabled + ) + .expect("String write"); + } + out.push_str("\n ],\n \"messages\": ["); + for (index, message) in city.messages.iter().enumerate() { + out.push_str(if index == 0 { "\n" } else { ",\n" }); + write!(out, " {}", message_json(message)).expect("String write"); + } + out.push_str("\n ]\n}\n"); + out +} + +fn message_json(message: &Message) -> String { + let route = message + .route + .iter() + .map(|node| node.0.to_string()) + .collect::>() + .join(","); + format!( + "{{\"id\":{},\"from\":{},\"to\":{},\"class\":\"{}\",\"bytes\":{},\"status\":\"{}\",\ + \"created_ms\":{},\"expires_ms\":{},\"first_route_ms\":{},\"due_ms\":{},\"route\":[{}]}}", + message.id, + message.from.0, + message.to.0, + class_name(message.class), + message.bytes, + status_name(message.status), + message.created_ms, + message.expires_ms, + json_option(message.first_route_ms), + json_option(message.due_ms), + route + ) +} + +fn json_option(value: Option) -> String { + value.map_or_else(|| "null".to_owned(), |number| number.to_string()) +} + +fn optional(value: Option) -> String { + value.map_or_else(String::new, |number| number.to_string()) +} + +fn coordinate(value: f32) -> String { + if value.is_finite() { + format!("{value:.1}") + } else { + "null".to_owned() + } +} + +fn class_name(class: TrafficClass) -> &'static str { + match class { + TrafficClass::Control => "Control", + TrafficClass::Text => "Text", + TrafficClass::Bulk => "Bulk", + } +} + +fn status_name(status: DeliveryState) -> &'static str { + match status { + DeliveryState::Queued => "Queued", + DeliveryState::InFlight => "InFlight", + DeliveryState::Delivered => "Delivered", + DeliveryState::Expired => "Expired", + } +} + +fn role_name(role: DeviceRole) -> &'static str { + match role { + DeviceRole::Client => "Client", + DeviceRole::Relay => "Relay", + DeviceRole::Backbone => "Backbone", + } +} + +fn link_kind_name(kind: LinkKind) -> &'static str { + match kind { + LinkKind::SlowRadio => "SlowRadio", + LinkKind::FastWireless => "FastWireless", + LinkKind::Wired => "Wired", + LinkKind::Internet => "Internet", + } +} + +fn escape(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for character in value.chars() { + match character { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + control if control.is_control() => { + write!(out, "\\u{:04x}", u32::from(control)).expect("String write"); + } + other => out.push(other), + } + } + out +} diff --git a/workspace/crates/icenet-sim/src/metrics/mod.rs b/workspace/crates/icenet-sim/src/metrics/mod.rs new file mode 100644 index 0000000..063e806 --- /dev/null +++ b/workspace/crates/icenet-sim/src/metrics/mod.rs @@ -0,0 +1,109 @@ +//! Deterministic aggregate metrics for the city simulator. +//! +//! These helpers never read wall-clock time, so identical simulations produce +//! identical summaries. +use icenet_core::{LinkKind, TrafficClass}; +use icenet_routing::HOP_OVERHEAD_MS; + +use crate::{City, DeliveryState, Message}; + +mod export; +pub use export::{messages_csv, scenario_json}; + +/// Aggregate counters for one simulation snapshot. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Summary { + /// Messages submitted by the application. + pub created: usize, + /// Messages whose transmission completed. + pub delivered: usize, + /// Messages currently waiting for an eligible path. + pub queued: usize, + /// Messages with a scheduled transmission. + pub in_flight: usize, + /// Messages whose lifetime elapsed before delivery. + pub expired: usize, + /// Median simulated timestamp when a path first became available. + pub first_route_p50_ms: Option, + /// 95th percentile simulated timestamp when a path first became available. + pub first_route_p95_ms: Option, + /// Approximate control-message airtime across all route hops. + pub control_airtime_ms: u64, + /// Airtime reserved on slow radio links by all messages, in milliseconds. + pub slow_radio_airtime_ms: u64, +} + +impl Summary { + /// Returns delivered messages divided by created messages. + /// + /// The ratio is `0.0` for an empty simulation. + pub fn delivery_ratio(&self) -> f64 { + if self.created == 0 { + return 0.0; + } + self.delivered as f64 / self.created as f64 + } +} + +/// Summarizes delivery states, first-route latency and control airtime. +pub fn summarize(city: &City) -> Summary { + let mut summary = Summary { + created: city.messages.len(), + delivered: 0, + queued: 0, + in_flight: 0, + expired: 0, + first_route_p50_ms: None, + first_route_p95_ms: None, + control_airtime_ms: 0, + slow_radio_airtime_ms: city.link_airtime_ms(LinkKind::SlowRadio), + }; + let mut first_route_samples = Vec::new(); + for message in &city.messages { + match message.status { + DeliveryState::Delivered => summary.delivered += 1, + DeliveryState::Queued => summary.queued += 1, + DeliveryState::InFlight => summary.in_flight += 1, + DeliveryState::Expired => summary.expired += 1, + } + if let Some(sample) = message.first_route_ms { + first_route_samples.push(sample); + } + if message.class == TrafficClass::Control { + summary.control_airtime_ms = summary + .control_airtime_ms + .saturating_add(airtime_ms(city, message)); + } + } + summary.first_route_p50_ms = percentile(&mut first_route_samples, 50); + summary.first_route_p95_ms = percentile(&mut first_route_samples, 95); + summary +} + +/// Returns the nearest-rank percentile, sorting `samples` in place. +/// +/// `percent` is clamped to `1..=100`. An empty slice returns `None`. +pub fn percentile(samples: &mut [u64], percent: u8) -> Option { + if samples.is_empty() { + return None; + } + samples.sort_unstable(); + let rank = usize::from(percent.clamp(1, 100)); + let index = (rank.saturating_mul(samples.len())) + .div_ceil(100) + .saturating_sub(1); + samples.get(index).copied() +} + +fn airtime_ms(city: &City, message: &Message) -> u64 { + message + .route_links + .iter() + .filter_map(|&index| city.links.get(index)) + .map(|link| { + link.kind + .transfer_ms(message.bytes) + .saturating_add(HOP_OVERHEAD_MS) + }) + .fold(0, u64::saturating_add) +} diff --git a/workspace/crates/icenet-sim/src/model.rs b/workspace/crates/icenet-sim/src/model.rs new file mode 100644 index 0000000..a8a3402 --- /dev/null +++ b/workspace/crates/icenet-sim/src/model.rs @@ -0,0 +1,87 @@ +//! Plain state structures for the city graph simulator. +use icenet_core::{LinkKind, NodeId, TrafficClass}; + +/// Logical role of one virtual city device. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DeviceRole { + /// A battery-powered or user-facing endpoint. + Client, + /// A transit node forwarding messages. + Relay, + /// A normally available backbone node. + Backbone, +} + +/// A visible node in the city diagram. +#[derive(Clone, Debug)] +pub struct Device { + /// Numeric simulator node ID. + pub id: NodeId, + /// Display label shown by the city GUI. + pub label: String, + /// Horizontal map coordinate (not longitude). + pub x: f32, + /// Vertical map coordinate (not latitude). + pub y: f32, + /// Whether this device is available. + pub online: bool, + /// Intended role in the city. + pub role: DeviceRole, +} + +/// A simulated undirected point-to-point connection. +#[derive(Clone, Copy, Debug)] +pub struct SimLink { + /// First endpoint ID. + pub a: NodeId, + /// Second endpoint ID. + pub b: NodeId, + /// Link class used for rough capacity. + pub kind: LinkKind, + /// Whether this connection is currently available. + pub enabled: bool, +} + +/// Current delivery state; queued is never equivalent to delivered. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DeliveryState { + /// No eligible path exists, or a path failed. + Queued, + /// A simulated transmission has been scheduled. + InFlight, + /// The simulator has completed transmission. + Delivered, + /// The message lifetime elapsed before delivery. + Expired, +} + +/// One synthetic application message. +#[derive(Clone, Debug)] +pub struct Message { + /// Monotonic message identifier for this simulation. + pub id: u64, + /// Message origin. + pub from: NodeId, + /// Destination. + pub to: NodeId, + /// Traffic class governing link eligibility. + pub class: TrafficClass, + /// Synthetic payload size, no byte payload is stored. + pub bytes: u64, + /// Current delivery state. + pub status: DeliveryState, + /// Simulated time when the application submitted this message. + pub created_ms: u64, + /// Simulated time after which an undelivered message expires. + pub expires_ms: u64, + /// Simulated time when a path first became available. + pub first_route_ms: Option, + /// Illustrative serialization time of the current route. + pub estimated_ms: u64, + /// The expected end of transmission in simulated time. + pub due_ms: Option, + /// Current ordered route through the graph. + pub route: Vec, + /// Index into [`City::links`](crate::City) of every hop of `route`. + pub route_links: Vec, +} diff --git a/workspace/crates/icenet-sim/src/topology.rs b/workspace/crates/icenet-sim/src/topology.rs new file mode 100644 index 0000000..513aa2a --- /dev/null +++ b/workspace/crates/icenet-sim/src/topology.rs @@ -0,0 +1,87 @@ +//! Topology editing operations for the city simulator. +use crate::{City, Device, DeviceRole, SimLink}; +use icenet_core::{LinkKind, NodeId}; + +impl City { + /// Appends a virtual device and returns its new simulator ID. + pub fn add_device(&mut self, label: String, role: DeviceRole) -> NodeId { + let id = NodeId(self.devices.iter().map(|d| d.id.0).max().unwrap_or(0) + 1); + let n = self.devices.len() as f32; + self.devices.push(Device { + id, + label, + x: 65.0 + (n * 57.0) % 420.0, + y: 70.0 + (n * 41.0) % 200.0, + online: true, + role, + }); + id + } + + /// Adds a simulated link if both endpoints exist and are distinct. + pub fn add_link(&mut self, a: NodeId, b: NodeId, kind: LinkKind) -> bool { + let exists = |id| self.devices.iter().any(|device| device.id == id); + if a == b || !exists(a) || !exists(b) { + return false; + } + if self + .links + .iter() + .any(|link| (link.a == a && link.b == b) || (link.a == b && link.b == a)) + { + return false; + } + self.links.push(SimLink { + a, + b, + kind, + enabled: true, + }); + true + } + + /// Changes a link category while retaining its endpoints. + pub fn set_link_kind(&mut self, index: usize, kind: LinkKind) -> bool { + match self.links.get_mut(index) { + Some(link) => { + link.kind = kind; + true + } + None => false, + } + } + + /// Updates a link by list index. Returns false when the index is invalid. + pub fn set_link_enabled(&mut self, index: usize, enabled: bool) -> bool { + match self.links.get_mut(index) { + Some(link) => { + link.enabled = enabled; + true + } + None => false, + } + } + + /// Updates the availability of one device. + pub fn set_device_online(&mut self, id: NodeId, online: bool) -> bool { + match self.devices.iter_mut().find(|device| device.id == id) { + Some(device) => { + device.online = online; + true + } + None => false, + } + } + + /// Moves a device on the map without changing routing eligibility. + pub fn move_device(&mut self, id: NodeId, x: f32, y: f32) -> bool { + match self.devices.iter_mut().find(|device| device.id == id) { + Some(device) => { + device.x = x; + device.y = y; + true + } + None => false, + } + } +} diff --git a/workspace/crates/icenet-sim/tests/capacity/main.rs b/workspace/crates/icenet-sim/tests/capacity/main.rs new file mode 100644 index 0000000..86d867c --- /dev/null +++ b/workspace/crates/icenet-sim/tests/capacity/main.rs @@ -0,0 +1,101 @@ +//! Link capacity: transmissions share a link in FIFO order instead of overlapping. +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState, DeviceRole, metrics}; + +fn pair(kind: LinkKind) -> (City, NodeId, NodeId) { + let mut city = City::empty(); + let a = city.add_device("a".to_owned(), DeviceRole::Client); + let b = city.add_device("b".to_owned(), DeviceRole::Client); + assert!(city.add_link(a, b, kind)); + (city, a, b) +} + +fn delivered(city: &City) -> usize { + city.messages + .iter() + .filter(|m| m.status == DeliveryState::Delivered) + .count() +} + +#[test] +fn texts_queue_behind_each_other_on_one_slow_link() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + // 200 B at 1 kbit/s is 1600 ms of airtime plus 10 ms overhead each. + for _ in 0..100 { + city.send(a, b, TrafficClass::Text, 200); + } + city.tick(2_000); + assert_eq!(delivered(&city), 1, "only one 1610 ms frame fits in 2 s"); + city.tick(161_000 - 2_000); + assert_eq!(delivered(&city), 100); +} + +#[test] +fn due_times_are_strictly_ordered_by_link_reservation() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + let first = city.send(a, b, TrafficClass::Text, 200); + let second = city.send(a, b, TrafficClass::Text, 200); + let due = |id| { + city.messages + .iter() + .find(|m| m.id == id) + .and_then(|m| m.due_ms) + }; + assert_eq!(due(first), Some(1_610)); + assert_eq!(due(second), Some(3_220)); +} + +#[test] +fn an_idle_link_does_not_delay_the_next_message() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + city.send(a, b, TrafficClass::Text, 200); + city.tick(10_000); + let id = city.send(a, b, TrafficClass::Text, 200); + let message = city.messages.iter().find(|m| m.id == id).expect("message"); + assert_eq!(message.due_ms, Some(10_000 + 1_610)); +} + +#[test] +fn backlog_can_push_a_message_past_its_ttl() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + for _ in 0..3 { + city.send(a, b, TrafficClass::Text, 200); + } + let late = city.send_with_ttl(a, b, TrafficClass::Text, 200, 5_000); + city.tick(5_000); + let status = city + .messages + .iter() + .find(|m| m.id == late) + .expect("late") + .status; + assert_eq!( + status, + DeliveryState::Expired, + "airtime backlog ate the TTL" + ); +} + +#[test] +fn oversized_text_never_consumes_slow_radio_airtime() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + let id = city.send(a, b, TrafficClass::Text, 5_000_000); + let status = city + .messages + .iter() + .find(|m| m.id == id) + .expect("message") + .status; + assert_eq!(status, DeliveryState::Queued); + assert_eq!(city.link_airtime_ms(LinkKind::SlowRadio), 0); + assert_eq!(metrics::summarize(&city).slow_radio_airtime_ms, 0); +} + +#[test] +fn airtime_is_reported_per_link_kind() { + let (mut city, a, b) = pair(LinkKind::SlowRadio); + city.send(a, b, TrafficClass::Text, 200); + assert_eq!(city.link_airtime_ms(LinkKind::SlowRadio), 1_610); + assert_eq!(city.link_airtime_ms(LinkKind::Wired), 0); + assert_eq!(metrics::summarize(&city).slow_radio_airtime_ms, 1_610); +} diff --git a/workspace/crates/icenet-sim/tests/city.rs b/workspace/crates/icenet-sim/tests/city.rs new file mode 100644 index 0000000..ba590ab --- /dev/null +++ b/workspace/crates/icenet-sim/tests/city.rs @@ -0,0 +1,140 @@ +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState, DeviceRole, metrics}; + +#[test] +fn bulk_is_queued_when_only_slow_links_remain() { + let mut city = City::demo(); + assert!(city.set_link_enabled(2, false)); + let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + assert_eq!( + city.messages.iter().find(|m| m.id == id).unwrap().status, + DeliveryState::Queued + ); +} + +#[test] +fn message_delivers_after_virtual_time_advance() { + let mut city = City::demo(); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 50_000); + city.tick(200_000); + assert_eq!(city.messages[0].status, DeliveryState::Delivered); +} + +#[test] +fn queued_message_recovers_when_fast_link_returns() { + let mut city = City::demo(); + city.set_link_enabled(2, false); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 100); + assert_eq!(city.messages[0].status, DeliveryState::Queued); + city.set_link_enabled(2, true); + city.tick(1); + assert_eq!(city.messages[0].status, DeliveryState::InFlight); +} + +#[test] +fn slower_link_kind_reschedules_an_in_flight_message() { + let mut city = City::demo(); + let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + let before = city.messages[0].due_ms.expect("scheduled"); + assert!(city.set_link_kind(3, LinkKind::Internet)); + city.tick(1); + let after = city.messages[0].due_ms.expect("still scheduled"); + assert!(after > before, "due {after} must move past {before}"); + assert_eq!(city.messages[0].id, id); +} + +#[test] +fn first_route_timestamp_is_not_restamped_after_requeue() { + let mut city = City::demo(); + assert!(city.set_link_enabled(2, false)); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 100); + city.tick(1_000); + assert!(city.set_link_enabled(2, true)); + city.tick(1); + let first = city.messages[0].first_route_ms; + assert_eq!(first, Some(1_001)); + assert!(city.set_link_enabled(2, false)); + city.tick(1); + assert_eq!(city.messages[0].status, DeliveryState::Queued); + assert!(city.set_link_enabled(2, true)); + city.tick(1); + assert_eq!(city.messages[0].first_route_ms, first); +} + +#[test] +fn empty_city_has_no_devices_links_or_messages() { + let city = City::empty(); + assert!(city.devices.is_empty()); + assert!(city.links.is_empty()); + assert!(city.messages.is_empty()); + assert_eq!(city.now_ms, 0); +} + +#[test] +fn identical_action_scripts_produce_byte_identical_exports() { + let first = run_script(); + let second = run_script(); + assert_eq!( + metrics::messages_csv(&first), + metrics::messages_csv(&second) + ); + assert_eq!( + metrics::scenario_json(&first), + metrics::scenario_json(&second) + ); + assert_eq!(metrics::summarize(&first), metrics::summarize(&second)); +} + +fn run_script() -> City { + let mut city = City::demo(); + assert!(city.set_link_enabled(2, false)); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + city.tick(1_000); + assert!(city.set_link_enabled(2, true)); + city.tick(120_000); + let extra = city.add_device("Extra".to_owned(), DeviceRole::Client); + assert!(city.add_link(extra, NodeId(5), LinkKind::Internet)); + city.send_with_ttl(extra, NodeId(6), TrafficClass::Bulk, 1_000, 1); + city.tick(10); + city +} + +#[test] +fn cutting_the_route_before_a_coarse_tick_never_yields_delivered() { + let mut city = City::demo(); + let id = city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + for index in 0..city.links.len() { + assert!(city.set_link_enabled(index, false)); + } + // One huge step jumps far past `due_ms`; the cut still happened first. + city.tick(1_000_000); + let status = city.messages.iter().find(|m| m.id == id).unwrap().status; + assert_eq!(status, DeliveryState::Queued); +} + +#[test] +fn taking_a_relay_offline_before_arrival_does_not_deliver() { + let mut city = City::demo(); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + assert!(city.set_device_online(NodeId(5), false)); + city.tick(1_000_000); + assert_ne!(city.messages[0].status, DeliveryState::Delivered); +} + +#[test] +fn a_still_valid_route_is_delivered_normally_after_a_coarse_tick() { + let mut city = City::demo(); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + city.tick(1_000_000); + assert_eq!(city.messages[0].status, DeliveryState::Delivered); +} + +#[test] +fn a_cut_that_is_repaired_before_the_tick_reroutes_without_false_delivery() { + let mut city = City::demo(); + city.send(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000); + assert!(city.set_link_enabled(3, false)); + city.tick(1); + assert_ne!(city.messages[0].status, DeliveryState::Delivered); +} diff --git a/workspace/crates/icenet-sim/tests/metrics.rs b/workspace/crates/icenet-sim/tests/metrics.rs new file mode 100644 index 0000000..96da974 --- /dev/null +++ b/workspace/crates/icenet-sim/tests/metrics.rs @@ -0,0 +1,114 @@ +//! Deterministic metrics and export formats for offline experiments. +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState, metrics}; + +#[test] +fn summary_counts_states_and_excludes_expired_from_delivery_ratio() { + let mut city = City::demo(); + for index in [2, 3, 4] { + assert!(city.set_link_enabled(index, false)); + } + city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 1_000); + city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + city.tick(5_000); + let summary = metrics::summarize(&city); + assert_eq!(summary.created, 2); + assert_eq!(summary.delivered, 1); + assert_eq!(summary.expired, 1); + assert_eq!(summary.queued, 0); + assert!((summary.delivery_ratio() - 0.5).abs() < f64::EPSILON); + assert!(summary.first_route_p50_ms.is_some()); + assert!(summary.first_route_p95_ms.is_some()); +} + +#[test] +fn nearest_rank_percentiles_are_deterministic() { + let mut samples = [40, 10, 30, 20]; + assert_eq!(metrics::percentile(&mut samples, 50), Some(20)); + assert_eq!(metrics::percentile(&mut samples, 95), Some(40)); + assert_eq!(metrics::percentile(&mut [], 50), None); + assert_eq!(metrics::percentile(&mut [7], 99), Some(7)); +} + +#[test] +fn control_airtime_is_counted_from_the_last_route() { + let mut city = City::demo(); + let id = city.send(NodeId(1), NodeId(3), TrafficClass::Control, 100); + city.tick(60_000); + assert_eq!(status_of(&city, id), DeliveryState::Delivered); + assert!(metrics::summarize(&city).control_airtime_ms > 0); +} + +#[test] +fn csv_export_has_stable_header_and_one_row_per_message() { + let mut city = City::demo(); + city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + let csv = metrics::messages_csv(&city); + let mut lines = csv.lines(); + assert_eq!( + lines.next(), + Some("id,from,to,class,bytes,status,created_ms,expires_ms,first_route_ms,due_ms,route") + ); + assert_eq!(lines.clone().count(), 1); + assert!(lines.next().is_some_and(|row| row.contains(",Text,"))); +} + +#[test] +fn json_scenario_is_deterministic_and_escapes_labels() { + let mut first = City::demo(); + first.devices[0].label = "A \"quoted\" \\ path".to_owned(); + first.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + let mut second = first.clone(); + second.tick(1_000); + + let first_json = metrics::scenario_json(&first); + let first_again = metrics::scenario_json(&first); + assert_eq!(first_json, first_again); + assert!(first_json.contains(r#""label":"A \"quoted\" \\ path""#)); + assert!(first_json.contains(r#""status":"InFlight""#)); + assert!(second_json_after_tick(&second).contains("Delivered")); +} + +#[test] +fn json_escapes_control_characters() { + let mut city = City::demo(); + city.devices[0].label = "a\u{1}b".to_owned(); + let json = metrics::scenario_json(&city); + assert!(json.contains(r#""label":"a\u0001b""#), "json: {json}"); +} + +#[test] +fn json_uses_null_for_non_finite_coordinates() { + let mut city = City::demo(); + city.devices[0].x = f32::NAN; + city.devices[0].y = f32::INFINITY; + let json = metrics::scenario_json(&city); + assert!(json.contains("\"x\":null,\"y\":null"), "json: {json}"); +} + +#[test] +fn json_encodes_every_supported_link_kind() { + for kind in [ + LinkKind::SlowRadio, + LinkKind::FastWireless, + LinkKind::Wired, + LinkKind::Internet, + ] { + let mut city = City::demo(); + city.links[0].kind = kind; + let json = metrics::scenario_json(&city); + assert!(json.contains(&format!("\"kind\":\"{kind:?}\""))); + } +} + +fn status_of(city: &City, id: u64) -> DeliveryState { + city.messages + .iter() + .find(|message| message.id == id) + .expect("recorded message") + .status +} + +fn second_json_after_tick(city: &City) -> String { + metrics::scenario_json(city) +} diff --git a/workspace/crates/icenet-sim/tests/scale.rs b/workspace/crates/icenet-sim/tests/scale.rs new file mode 100644 index 0000000..e97c1ac --- /dev/null +++ b/workspace/crates/icenet-sim/tests/scale.rs @@ -0,0 +1,68 @@ +//! Scale smoke tests: 100 and 1000 virtual nodes on a deterministic grid. +use std::time::Instant; + +use icenet_core::{LinkKind, NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState, DeviceRole, metrics}; + +#[test] +fn hundred_node_grid_delivers_bulk_with_full_ratio() { + let mut city = grid(10, 10); + let source = city.devices.first().expect("grid nodes").id; + let destination = city.devices.last().expect("grid nodes").id; + let id = city.send(source, destination, TrafficClass::Bulk, 5_000_000); + city.tick(200_000); + assert_eq!(status_of(&city, id), DeliveryState::Delivered); + let summary = metrics::summarize(&city); + assert_eq!(summary.created, 1); + assert!((summary.delivery_ratio() - 1.0).abs() < f64::EPSILON); +} + +#[test] +fn thousand_node_grid_reports_route_latency() { + let city = grid(40, 25); + let nodes: Vec = city.devices.iter().map(|device| device.id).collect(); + let mut samples = Vec::with_capacity(200); + let mut state = 0x2545_f491_4f6c_dd1d_u64; + for _ in 0..200 { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + let from = nodes[(state as usize) % nodes.len()]; + let to = nodes[((state >> 32) as usize) % nodes.len()]; + let started = Instant::now(); + let path = city.route(from, to, TrafficClass::Text, 128); + samples.push(u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)); + assert!(path.is_some(), "grid must stay connected"); + } + let p50 = metrics::percentile(&mut samples.clone(), 50).expect("samples"); + let p95 = metrics::percentile(&mut samples, 95).expect("samples"); + println!("1000-node route search (release-independent debug build): p50={p50}us p95={p95}us"); + assert!(p50 <= p95); +} + +fn grid(columns: usize, rows: usize) -> City { + let mut city = City::empty(); + let ids: Vec = (0..columns * rows) + .map(|index| city.add_device(format!("n{index}"), DeviceRole::Relay)) + .collect(); + for row in 0..rows { + for column in 0..columns { + let index = row * columns + column; + if column + 1 < columns { + assert!(city.add_link(ids[index], ids[index + 1], LinkKind::FastWireless)); + } + if row + 1 < rows { + assert!(city.add_link(ids[index], ids[index + columns], LinkKind::FastWireless)); + } + } + } + city +} + +fn status_of(city: &City, id: u64) -> DeliveryState { + city.messages + .iter() + .find(|message| message.id == id) + .expect("recorded message") + .status +} diff --git a/workspace/crates/icenet-sim/tests/ttl.rs b/workspace/crates/icenet-sim/tests/ttl.rs new file mode 100644 index 0000000..72def89 --- /dev/null +++ b/workspace/crates/icenet-sim/tests/ttl.rs @@ -0,0 +1,83 @@ +//! Store-and-forward lifetime behaviour: queued work must expire, never fake delivery. +use icenet_core::{NodeId, TrafficClass}; +use icenet_sim::{City, DeliveryState}; + +fn city_without_bulk_path() -> City { + let mut city = City::demo(); + for index in [2, 3, 4] { + assert!(city.set_link_enabled(index, false)); + } + city +} + +#[test] +fn queued_message_expires_after_its_ttl() { + let mut city = city_without_bulk_path(); + let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 5_000); + city.tick(4_999); + assert_eq!(message_status(&city, id), DeliveryState::Queued); + city.tick(1); + assert_eq!(message_status(&city, id), DeliveryState::Expired); +} + +#[test] +fn in_flight_message_expires_when_ttl_is_shorter_than_transfer() { + let mut city = City::demo(); + let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 10); + city.tick(11); + assert_eq!(message_status(&city, id), DeliveryState::Expired); +} + +#[test] +fn arrival_at_expiry_is_delivered_but_one_ms_earlier_expires() { + let mut delivered = City::demo(); + let estimate = delivered + .route(NodeId(1), NodeId(3), TrafficClass::Text, 128) + .expect("route") + .estimated_ms; + let id = delivered.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, estimate); + delivered.tick(estimate); + assert_eq!(message_status(&delivered, id), DeliveryState::Delivered); + + let mut expired = City::demo(); + let id = expired.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, estimate - 1); + expired.tick(estimate - 1); + assert_eq!(message_status(&expired, id), DeliveryState::Expired); +} + +#[test] +fn expired_message_never_revives_when_a_path_returns() { + let mut city = city_without_bulk_path(); + let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Bulk, 5_000_000, 1_000); + city.tick(2_000); + assert_eq!(message_status(&city, id), DeliveryState::Expired); + assert!(city.set_link_enabled(2, true)); + city.tick(60_000); + assert_eq!(message_status(&city, id), DeliveryState::Expired); +} + +#[test] +fn zero_ttl_gets_the_shortest_positive_lifetime() { + let mut city = City::demo(); + let id = city.send_with_ttl(NodeId(1), NodeId(3), TrafficClass::Text, 128, 0); + city.tick(0); + assert_eq!(message_status(&city, id), DeliveryState::InFlight); + city.tick(1); + assert_eq!(message_status(&city, id), DeliveryState::Expired); +} + +#[test] +fn default_send_uses_the_documented_default_ttl() { + let mut city = City::demo(); + let id = city.send(NodeId(1), NodeId(3), TrafficClass::Text, 128); + let message = city.messages.iter().find(|m| m.id == id).expect("message"); + assert_eq!(message.expires_ms, City::DEFAULT_TTL_MS); +} + +fn message_status(city: &City, id: u64) -> DeliveryState { + city.messages + .iter() + .find(|message| message.id == id) + .expect("recorded message") + .status +} diff --git a/workspace/crates/icenet-transport/Cargo.toml b/workspace/crates/icenet-transport/Cargo.toml new file mode 100644 index 0000000..59a4a74 --- /dev/null +++ b/workspace/crates/icenet-transport/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "icenet-transport" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } diff --git a/workspace/crates/icenet-transport/src/lib.rs b/workspace/crates/icenet-transport/src/lib.rs new file mode 100644 index 0000000..3c47124 --- /dev/null +++ b/workspace/crates/icenet-transport/src/lib.rs @@ -0,0 +1,56 @@ +//! Dependency-free transport boundary, in-memory and UDP adapters. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use std::collections::VecDeque; + +mod udp; +pub use udp::UdpTransport; + +/// Largest draft frame accepted by these adapters (payload cap plus wire header). +pub const MAX_DATAGRAM_BYTES: usize = 4_096 + 14; + +/// Errors produced by a transport implementation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TransportError { + /// This implementation will not accept a frame of this size. + TooLarge, + /// The socket is temporarily unable to send or receive. + Unavailable, +} + +/// A small synchronous transport interface for early experiments. +pub trait Transport { + /// Sends one bounded frame; ownership moves into the transport. + /// + /// # Errors + /// Returns an error if local transport limits reject this frame. + fn send(&mut self, frame: Vec) -> Result<(), TransportError>; + + /// Receives the next available frame without blocking. + /// + /// # Errors + /// Returns `Unavailable` when the socket fails; `Ok(None)` means no frame + /// is ready yet. + fn recv(&mut self) -> Result>, TransportError>; +} + +/// A loopback transport used only for controlled tests. +#[derive(Debug, Default)] +pub struct MemoryTransport { + queue: VecDeque>, +} + +impl Transport for MemoryTransport { + fn send(&mut self, frame: Vec) -> Result<(), TransportError> { + if frame.len() > MAX_DATAGRAM_BYTES { + return Err(TransportError::TooLarge); + } + self.queue.push_back(frame); + Ok(()) + } + + fn recv(&mut self) -> Result>, TransportError> { + Ok(self.queue.pop_front()) + } +} diff --git a/workspace/crates/icenet-transport/src/udp.rs b/workspace/crates/icenet-transport/src/udp.rs new file mode 100644 index 0000000..9a93e05 --- /dev/null +++ b/workspace/crates/icenet-transport/src/udp.rs @@ -0,0 +1,68 @@ +//! Non-blocking UDP adapter for one connected peer. +use std::io; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; + +use crate::{MAX_DATAGRAM_BYTES, Transport, TransportError}; + +/// A non-blocking UDP socket connected to one peer address. +#[derive(Debug)] +pub struct UdpTransport { + socket: UdpSocket, +} + +impl UdpTransport { + /// Binds a local address and makes the socket non-blocking. + /// + /// # Errors + /// Returns the underlying socket error when binding or configuration fails. + pub fn bind(address: impl ToSocketAddrs) -> io::Result { + let socket = UdpSocket::bind(address)?; + socket.set_nonblocking(true)?; + Ok(Self { socket }) + } + + /// Connects this socket to one peer. + /// + /// # Errors + /// Returns the underlying socket error when connecting fails. + pub fn connect(self, peer: impl ToSocketAddrs) -> io::Result { + self.socket.connect(peer)?; + Ok(self) + } + + /// Returns the local socket address, including an OS-assigned port. + /// + /// # Errors + /// Returns the underlying socket error when the address is unavailable. + pub fn local_addr(&self) -> io::Result { + self.socket.local_addr() + } +} + +impl Transport for UdpTransport { + fn send(&mut self, frame: Vec) -> Result<(), TransportError> { + if frame.len() > MAX_DATAGRAM_BYTES { + return Err(TransportError::TooLarge); + } + match self.socket.send(&frame) { + Ok(_) => Ok(()), + Err(_) => Err(TransportError::Unavailable), + } + } + + fn recv(&mut self) -> Result>, TransportError> { + let mut buffer = [0_u8; MAX_DATAGRAM_BYTES]; + match self.socket.recv(&mut buffer) { + Ok(size) => Ok(Some(buffer[..size].to_vec())), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ) => + { + Ok(None) + } + Err(_) => Err(TransportError::Unavailable), + } + } +} diff --git a/workspace/crates/icenet-transport/tests/memory.rs b/workspace/crates/icenet-transport/tests/memory.rs new file mode 100644 index 0000000..98109b1 --- /dev/null +++ b/workspace/crates/icenet-transport/tests/memory.rs @@ -0,0 +1,11 @@ +use icenet_transport::{MemoryTransport, Transport}; + +#[test] +fn memory_transport_preserves_frame_order() { + let mut transport = MemoryTransport::default(); + transport.send(vec![1]).unwrap(); + transport.send(vec![2]).unwrap(); + assert_eq!(transport.recv(), Ok(Some(vec![1]))); + assert_eq!(transport.recv(), Ok(Some(vec![2]))); + assert_eq!(transport.recv(), Ok(None)); +} diff --git a/workspace/crates/icenet-transport/tests/udp.rs b/workspace/crates/icenet-transport/tests/udp.rs new file mode 100644 index 0000000..9271032 --- /dev/null +++ b/workspace/crates/icenet-transport/tests/udp.rs @@ -0,0 +1,45 @@ +use std::time::{Duration, Instant}; + +use icenet_transport::{Transport, TransportError, UdpTransport}; + +fn connected_pair() -> (UdpTransport, UdpTransport) { + let first = UdpTransport::bind("127.0.0.1:0").expect("bind first"); + let second = UdpTransport::bind("127.0.0.1:0").expect("bind second"); + let first_addr = first.local_addr().expect("first address"); + let second_addr = second.local_addr().expect("second address"); + ( + first.connect(second_addr).expect("connect first"), + second.connect(first_addr).expect("connect second"), + ) +} + +fn receive(transport: &mut UdpTransport) -> Vec { + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + if let Some(frame) = transport.recv().expect("recv") { + return frame; + } + std::thread::sleep(Duration::from_millis(5)); + } + panic!("no UDP frame within the deadline"); +} + +#[test] +fn udp_transport_round_trips_frames() { + let (mut first, mut second) = connected_pair(); + first.send(b"hello over udp".to_vec()).expect("send"); + assert_eq!(receive(&mut second), b"hello over udp"); +} + +#[test] +fn udp_transport_rejects_oversized_frames() { + let (mut first, _second) = connected_pair(); + let oversized = vec![0; 8_192]; + assert_eq!(first.send(oversized), Err(TransportError::TooLarge)); +} + +#[test] +fn empty_udp_socket_returns_no_frame() { + let (mut first, _second) = connected_pair(); + assert_eq!(first.recv().expect("recv"), None); +} diff --git a/workspace/crates/icenet-wire/Cargo.toml b/workspace/crates/icenet-wire/Cargo.toml new file mode 100644 index 0000000..2f21466 --- /dev/null +++ b/workspace/crates/icenet-wire/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "icenet-wire" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +icenet-core = { path = "../icenet-core" } diff --git a/workspace/crates/icenet-wire/src/lib.rs b/workspace/crates/icenet-wire/src/lib.rs new file mode 100644 index 0000000..d424326 --- /dev/null +++ b/workspace/crates/icenet-wire/src/lib.rs @@ -0,0 +1,106 @@ +//! An intentionally minimal, unauthenticated wire-format experiment. +//! +//! Do not use this framing for live, untrusted network traffic before review. +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use icenet_core::{ServiceId, TrafficClass}; + +/// Magic bytes of the experimental frame layout. +pub const MAGIC: [u8; 2] = *b"IN"; +/// The current (experimental) wire layout version. +pub const VERSION: u8 = 1; +/// Maximum application payload of one example frame. +pub const MAX_PAYLOAD_BYTES: usize = 4_096; +const HEADER_BYTES: usize = 14; + +/// A bounded message frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + /// The class assigned to this payload. + pub class: TrafficClass, + /// Destination service on a remote node. + pub service: ServiceId, + /// Application payload, not encrypted by this crate. + pub payload: Vec, +} + +/// Parse or serialization errors. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameError { + /// Insufficient bytes for the header or declared payload. + Truncated, + /// The magic marker or protocol version is not recognized. + InvalidHeader, + /// Class byte is not recognized. + InvalidClass, + /// A frame exceeded the configured size budget. + TooLarge, + /// Additional bytes follow the declared payload. + TrailingBytes, +} + +/// Serializes an experimental frame with a checked payload cap. +/// +/// # Errors +/// Returns `TooLarge` when the payload exceeds the configured limit. +pub fn encode(frame: &Frame) -> Result, FrameError> { + if frame.payload.len() > MAX_PAYLOAD_BYTES { + return Err(FrameError::TooLarge); + } + let class = match frame.class { + TrafficClass::Control => 0, + TrafficClass::Text => 1, + TrafficClass::Bulk => 2, + }; + let mut bytes = Vec::with_capacity(HEADER_BYTES + frame.payload.len()); + bytes.extend(MAGIC); + bytes.push(VERSION); + bytes.push(class); + bytes.extend(frame.service.0.to_be_bytes()); + let length = u16::try_from(frame.payload.len()).map_err(|_| FrameError::TooLarge)?; + bytes.extend(length.to_be_bytes()); + bytes.extend(&frame.payload); + Ok(bytes) +} + +/// Parses an experimental frame, rejecting malformed and oversized packets. +/// +/// # Errors +/// Returns a typed error for malformed or unsupported input. +pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() < HEADER_BYTES { + return Err(FrameError::Truncated); + } + if &bytes[0..2] != MAGIC.as_slice() || bytes[2] != VERSION { + return Err(FrameError::InvalidHeader); + } + let class = match bytes[3] { + 0 => TrafficClass::Control, + 1 => TrafficClass::Text, + 2 => TrafficClass::Bulk, + _ => return Err(FrameError::InvalidClass), + }; + let service = ServiceId(u64::from_be_bytes( + bytes[4..12].try_into().map_err(|_| FrameError::Truncated)?, + )); + let count = usize::from(u16::from_be_bytes( + bytes[12..14] + .try_into() + .map_err(|_| FrameError::Truncated)?, + )); + if count > MAX_PAYLOAD_BYTES { + return Err(FrameError::TooLarge); + } + if bytes.len() < HEADER_BYTES + count { + return Err(FrameError::Truncated); + } + if bytes.len() > HEADER_BYTES + count { + return Err(FrameError::TrailingBytes); + } + Ok(Frame { + class, + service, + payload: bytes[HEADER_BYTES..].to_vec(), + }) +} diff --git a/workspace/crates/icenet-wire/tests/frames.rs b/workspace/crates/icenet-wire/tests/frames.rs new file mode 100644 index 0000000..e6d0da2 --- /dev/null +++ b/workspace/crates/icenet-wire/tests/frames.rs @@ -0,0 +1,36 @@ +use icenet_core::{ServiceId, TrafficClass}; +use icenet_wire::{Frame, FrameError, MAX_PAYLOAD_BYTES, decode, encode}; + +#[test] +fn frame_round_trip() { + let frame = Frame { + class: TrafficClass::Text, + service: ServiceId(77_777), + payload: b"hello".to_vec(), + }; + let packed = encode(&frame).expect("valid frame"); + assert_eq!(decode(&packed), Ok(frame)); +} + +#[test] +fn rejects_invalid_lengths_and_invalid_classes() { + assert_eq!(decode(b"hi"), Err(FrameError::Truncated)); + let mut frame = encode(&Frame { + class: TrafficClass::Control, + service: ServiceId(1), + payload: vec![], + }) + .unwrap(); + frame[3] = 255; + assert_eq!(decode(&frame), Err(FrameError::InvalidClass)); +} + +#[test] +fn refuses_oversized_payload() { + let frame = Frame { + class: TrafficClass::Bulk, + service: ServiceId(1), + payload: vec![0; MAX_PAYLOAD_BYTES + 1], + }; + assert_eq!(encode(&frame), Err(FrameError::TooLarge)); +} diff --git a/workspace/crates/icenet-wire/tests/fuzz.rs b/workspace/crates/icenet-wire/tests/fuzz.rs new file mode 100644 index 0000000..b48270c --- /dev/null +++ b/workspace/crates/icenet-wire/tests/fuzz.rs @@ -0,0 +1,60 @@ +//! Deterministic parser smoke-fuzz: random bytes must never panic. +use icenet_core::{ServiceId, TrafficClass}; +use icenet_wire::{Frame, FrameError, MAX_PAYLOAD_BYTES, decode, encode}; + +#[test] +fn random_bytes_never_panic() { + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + for _ in 0..10_000 { + state = next(state); + let length = usize::try_from(state % 96).expect("small length"); + let mut bytes = Vec::with_capacity(length); + for _ in 0..length { + state = next(state); + bytes.push((state >> 24) as u8); + } + if let Ok(frame) = decode(&bytes) { + assert!(frame.payload.len() <= MAX_PAYLOAD_BYTES); + } + } +} + +#[test] +fn valid_frames_round_trip_at_payload_boundaries() { + for size in [0, 1, 4_095, MAX_PAYLOAD_BYTES] { + let frame = Frame { + class: TrafficClass::Bulk, + service: ServiceId(42), + payload: vec![0xab; size], + }; + let bytes = encode(&frame).expect("boundary frame encodes"); + assert_eq!(decode(&bytes), Ok(frame)); + } +} + +#[test] +fn malformed_headers_and_trailing_bytes_are_rejected() { + let frame = Frame { + class: TrafficClass::Text, + service: ServiceId(7), + payload: b"hello".to_vec(), + }; + let valid = encode(&frame).expect("frame"); + let mut bad_magic = valid.clone(); + bad_magic[0] = b'X'; + assert_eq!(decode(&bad_magic), Err(FrameError::InvalidHeader)); + + let mut bad_version = valid.clone(); + bad_version[2] = 99; + assert_eq!(decode(&bad_version), Err(FrameError::InvalidHeader)); + + let mut trailing = valid; + trailing.push(0); + assert_eq!(decode(&trailing), Err(FrameError::TrailingBytes)); +} + +fn next(state: u64) -> u64 { + state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407) +} diff --git a/workspace/rust-toolchain.toml b/workspace/rust-toolchain.toml new file mode 100644 index 0000000..3417ee5 --- /dev/null +++ b/workspace/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.95.0" +components = ["rustfmt", "clippy"] +profile = "minimal" diff --git a/workspace/tools/check_all.sh b/workspace/tools/check_all.sh new file mode 100755 index 0000000..889a0bb --- /dev/null +++ b/workspace/tools/check_all.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Validate authored files and Rust code. Use --full to include Slint GUI. +set -eu +cd "$(dirname "$0")/.." +python3 tools/check_layout.py +cargo fmt --all -- --check +if [ "${1:-}" = "--full" ]; then + cargo clippy --workspace --all-targets -- -D warnings + cargo test --workspace +else + cargo clippy -p icenet-routing -p icenet-sim --all-targets -- -D warnings + cargo test -p icenet-routing -p icenet-sim +fi diff --git a/workspace/tools/check_layout.py b/workspace/tools/check_layout.py new file mode 100644 index 0000000..fa4e132 --- /dev/null +++ b/workspace/tools/check_layout.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Validate ICE-NET repository layout constraints without third-party modules.""" +from __future__ import annotations +import pathlib +import re +import sys + +ROOT = pathlib.Path(__file__).resolve().parents[2] +TEXT_EXT = {'.md', '.rs', '.slint', '.toml', '.py', '.yml', '.yaml', '.sh', '.json', '.txt'} + + +def check() -> list[str]: + """Return all layout violations, including forbidden tests inside source files.""" + errors: list[str] = [] + for folder in sorted(p for p in ROOT.rglob('*') if p.is_dir()): + if any(part in {'target', '.git', '__pycache__'} for part in folder.parts): + continue + direct_files = [p for p in folder.iterdir() if p.is_file()] + # Cargo.lock and OS/editor metadata are generated or ecosystem files. + counted = [p for p in direct_files if p.name not in {'Cargo.lock', '.gitignore', '.DS_Store'}] + if len(counted) > 4: + errors.append(f'{folder.relative_to(ROOT)}: {len(counted)} source files, max 4') + for path in sorted(p for p in ROOT.rglob('*') if p.is_file()): + if any(part in {'target', '.git', '__pycache__'} for part in path.parts): + continue + if path.suffix not in TEXT_EXT and path.name != '.gitignore': + continue + # Verbatim license texts are not authored files; keep them unmodified. + if 'LICENSES' in path.relative_to(ROOT).parts: + continue + try: + body = path.read_text(encoding='utf8') + except UnicodeError: + errors.append(f'{path.relative_to(ROOT)}: not UTF-8') + continue + lines = len(body.splitlines()) + if lines > 250: + errors.append(f'{path.relative_to(ROOT)}: {lines} lines, max 250') + if path.suffix == '.rs' and '/src/' in path.as_posix(): + if re.search(r'#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]', body): + errors.append(f'{path.relative_to(ROOT)}: inline tests are forbidden') + return errors + + +if __name__ == '__main__': + errors = check() + if errors: + print('\n'.join('ERROR: ' + error for error in errors), file=sys.stderr) + raise SystemExit(1) + print('PASS: text <=250 lines, <=4 owned files/directory (lock excluded), external tests')