├── .bazelrc ├── .github └── issue_template.md ├── .gitignore ├── .travis.yml ├── CI ├── checkLogs.sh ├── cleanUp.sh ├── inMemoryBootstrap.sh ├── inMemoryRestart.sh ├── remoteLayerCalculation.sh ├── remoteRestart.sh ├── setupTests.sh └── startIRI.sh ├── LICENSE ├── README.md ├── Security.MD ├── WORKSPACE ├── compass ├── BUILD ├── Coordinator.java ├── LayersCalculator.java ├── ShadowingCoordinator.java ├── conf │ ├── BUILD │ ├── BaseConfiguration.java │ ├── CoordinatorConfiguration.java │ ├── CoordinatorState.java │ ├── InMemorySignatureSourceConfiguration.java │ ├── LayersCalculatorConfiguration.java │ ├── POWModeValidator.java │ ├── RemoteSignatureSourceConfiguration.java │ ├── ShadowingCoordinatorConfiguration.java │ ├── SignatureSourceServerConfiguration.java │ ├── SignatureSourceTypeConverter.java │ ├── SpongeModeConverter.java │ └── URLConverter.java ├── crypto │ ├── BUILD │ ├── Hasher.java │ ├── ISS.java │ ├── ISSInPlace.java │ ├── IotaRemotePoW.java │ ├── KerlPoW.java │ └── RemoteCURLP81PoW.java ├── exceptions │ ├── BUILD │ └── TimeoutException.java ├── milestone │ ├── BUILD │ ├── MilestoneDatabase.java │ ├── MilestoneSource.java │ └── MilestoneTest.java ├── sign │ ├── BUILD │ ├── InMemorySignatureSource.java │ ├── RemoteSignatureSource.java │ ├── SignatureSource.java │ ├── SignatureSourceHelper.java │ ├── SignatureSourceServer.java │ └── SignatureSourceType.java ├── simplelogger.properties └── test │ ├── BUILD │ └── TestUtil.java ├── docker └── BUILD ├── docs ├── HOWTO_private_tangle.md └── private_tangle │ ├── .gitignore │ ├── 01_calculate_layers.sh │ ├── 02_run_iri.sh │ ├── 03_run_coordinator.sh │ ├── 11_run_signature_source_server.sh │ ├── 12_run_coordinator_remote.sh │ ├── 21_calculate_layers_remote.sh │ ├── config.example.json │ ├── lib.sh │ └── snapshot.example.txt ├── proto ├── BUILD └── signature_source.proto └── third-party ├── BUILD └── maven_deps.bzl /.bazelrc: -------------------------------------------------------------------------------- 1 | build:check --all_incompatible_changes 2 | 3 | common:ci --color=no 4 | build:ci --verbose_failures 5 | build:ci --sandbox_debug 6 | build:ci --spawn_strategy=standalone 7 | build:ci --genrule_strategy=standalone 8 | test:ci --test_strategy=standalone 9 | test:ci --test_output=errors 10 | -------------------------------------------------------------------------------- /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | The issue tracker is only for reporting bugs or submitting feature requests. 4 | If you need technical assistance for running a node please consult the #fullnode channel on Discord (https://discord.gg/jrxApWC) or https://forum.helloiota.com/Technology/Help. 5 | If you have general questions on IOTA you can go to https://iota.stackexchange.com/, https://helloiota.com/, or browse Discord channels (https://discord.gg/C88Wexg). 6 | 7 | 8 | 9 | ### Bug description 10 | A general description of the bug. 11 | 12 | ### Hardware Spec 13 | On what hardware is the node running on? 14 | 15 | ### Steps To Reproduce 16 | 1. 17 | 2. 18 | 3. 19 | 20 | ### Expected behaviour 21 | What should happen. 22 | 23 | ### Actual behaviour 24 | What really happened. 25 | 26 | ### Errors 27 | Paste any errors that you see. 28 | 29 | 30 | 31 | 32 | *Note* 33 | The feature request will probably be integrated faster if you do a pull request for it. 34 | If you want to discuss the feature before you actually write the code you are welcome to do it by first submitting an issue. 35 | 36 | ### Description 37 | Briefly describe the feature you want. 38 | 39 | ### Motivation 40 | Explain why this feature is needed. 41 | 42 | ### Requirements 43 | Create a list of what you want this feature request to fulfill. 44 | 45 | ### Open Questions (optional) 46 | Anything you want to discuss. 47 | 48 | ### Am I planning to do it myself with a PR? 49 | Yes/No. 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .meghanada/ 2 | bazel-* 3 | bazel-*/ 4 | target/ 5 | .ijwb/ 6 | 7 | layers/ 8 | addresses.csv 9 | 10 | *.iml 11 | *.csv 12 | 13 | .gradle 14 | /build/ 15 | /out/ 16 | 17 | # Ignore Gradle GUI config 18 | gradle-app.setting 19 | 20 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 21 | !gradle-wrapper.jar 22 | 23 | # Cache of project 24 | .gradletasknamecache 25 | 26 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 27 | # gradle/wrapper/gradle-wrapper.properties 28 | 29 | # Compiled class file 30 | *.class 31 | 32 | # Log file 33 | *.log 34 | 35 | # BlueJ files 36 | *.ctxt 37 | 38 | # Mobile Tools for Java (J2ME) 39 | .mtj.tmp/ 40 | 41 | # Package Files # 42 | *.jar 43 | *.war 44 | *.ear 45 | *.zip 46 | *.tar.gz 47 | *.rar 48 | 49 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 50 | hs_err_pid* 51 | 52 | .idea 53 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # trusty beta image has jdk8, gcc4.8.4 2 | dist: trusty 3 | sudo: required 4 | # xcode8 has jdk8 5 | osx_image: xcode8.3 6 | # Not technically required but suppresses 'Ruby' in Job status message. 7 | language: java 8 | 9 | os: 10 | - linux 11 | # - osx 12 | 13 | env: 14 | global: 15 | - V=0.28.0 16 | matrix: 17 | - TEST=bazel 18 | - TEST=inMemoryBootstrap 19 | - TEST=inMemoryRestart 20 | - TEST=remoteRestart 21 | - TEST=remoteLayerCalculation 22 | 23 | 24 | addons: 25 | apt: 26 | packages: 27 | - jq 28 | 29 | before_install: 30 | - | 31 | if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then 32 | OS=darwin 33 | else 34 | OS=linux 35 | fi 36 | URL="https://github.com/bazelbuild/bazel/releases/download/${V}/bazel-${V}-installer-${OS}-x86_64.sh" 37 | wget -O install.sh "${URL}" 38 | chmod +x install.sh 39 | ./install.sh --user 40 | rm -f install.sh 41 | 42 | script: 43 | - | 44 | if [[ "${TEST}" == "bazel" ]]; then 45 | bazel \ 46 | --output_base=$HOME/.cache/bazel \ 47 | --host_jvm_args=-Xmx500m \ 48 | --host_jvm_args=-Xms500m \ 49 | test \ 50 | --config=ci \ 51 | --experimental_repository_cache="$HOME/.bazel_repository_cache" \ 52 | --local_resources=400,1,1.0 \ 53 | //... 54 | fi 55 | # run HOW TO steps 56 | - | 57 | if [[ "${TEST}" != "bazel" ]]; then 58 | /bin/sh CI/setupTests.sh; 59 | /bin/sh CI/${TEST}.sh; 60 | sudo /bin/sh CI/cleanUp.sh; 61 | fi 62 | 63 | notifications: 64 | email: false 65 | -------------------------------------------------------------------------------- /CI/checkLogs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | scriptdir=$(dirname "$(readlink -f "$0")") 3 | 4 | echo "checking containers are running" 5 | if ! [ `docker ps | grep iri | cut -f1 -d\ ` ]; then 6 | echo "IRI exited, see logs" 7 | exit 255 8 | fi 9 | 10 | if ! [ `docker ps | grep coordinator | cut -f1 -d\ ` ]; then 11 | echo "Compass exited, see logs" 12 | exit 255 13 | fi 14 | 15 | echo "scanning logs for errors" 16 | if docker logs $(docker ps | grep iri | cut -f1 -d\ ) | grep -i 'error'; then 17 | echo "IRI threw errors, see logs" 18 | exit 255 19 | fi 20 | if docker logs $(docker ps | grep coordinator | cut -f1 -d\ ) | grep -i 'error'; then 21 | echo "Compass threw errors, see logs" 22 | exit 255 23 | fi -------------------------------------------------------------------------------- /CI/cleanUp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "cleaning up" 4 | COO_CONTAINER=`docker ps | grep coordinator | cut -f1 -d\ ` 5 | if [ "$COO_CONTAINER" ]; then 6 | docker kill $COO_CONTAINER 7 | fi 8 | 9 | IRI_CONTAINER=`docker ps | grep iri | cut -f1 -d\ ` 10 | if [ "$IRI_CONTAINER" ]; then 11 | docker kill $IRI_CONTAINER 12 | fi 13 | 14 | SIG_SOURCE_SERVER_CONTAINER=`docker ps | grep signature_source_server | cut -f1 -d\ ` 15 | if [ "$SIG_SOURCE_SERVER_CONTAINER" ]; then 16 | docker kill $SIG_SOURCE_SERVER_CONTAINER 17 | fi 18 | 19 | rm -rf docs/private_tangle/data 20 | rm -rf docs/private_tangle/db 21 | 22 | -------------------------------------------------------------------------------- /CI/inMemoryBootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | scriptdir=$(dirname "$(readlink -f "$0")") 3 | 4 | if ! /bin/sh ${scriptdir}/startIRI.sh; then 5 | exit 255 6 | fi 7 | 8 | 9 | 10 | cd docs/private_tangle 11 | 12 | echo "starting Compass bootstrap" 13 | ./03_run_coordinator.sh -bootstrap -broadcast & 14 | #let compass run for a while 15 | sleep 30 16 | 17 | if ! /bin/sh ${scriptdir}/checkLogs.sh; then 18 | exit 255 19 | fi 20 | 21 | cd ../.. -------------------------------------------------------------------------------- /CI/inMemoryRestart.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | scriptdir=$(dirname "$(readlink -f "$0")") 3 | 4 | if ! /bin/sh ${scriptdir}/startIRI.sh; then 5 | exit 255 6 | fi 7 | 8 | cd docs/private_tangle 9 | 10 | echo "starting Compass bootstrap" 11 | ./03_run_coordinator.sh -bootstrap -broadcast & 12 | sleep 20 13 | 14 | echo "restarting Compass" 15 | docker kill $(docker ps | grep coordinator | cut -f1 -d\ ) 16 | while [ `docker ps | grep coordinator | cut -f1 -d\ ` ]; do 17 | sleep 1; 18 | done 19 | sleep 2 20 | 21 | ./03_run_coordinator.sh -broadcast & 22 | sleep 20 23 | 24 | if ! /bin/sh ${scriptdir}/checkLogs.sh; then 25 | exit 255 26 | fi 27 | 28 | cd ../.. -------------------------------------------------------------------------------- /CI/remoteLayerCalculation.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd docs/private_tangle 3 | 4 | ROOT_TREE_LOCAL=`cat data/layers/layer.0.csv` 5 | echo "starting Signing server" 6 | ./11_run_signature_source_server.sh & 7 | sleep 10 8 | 9 | echo "starting remote layer calculation" 10 | ./21_calculate_layers_remote.sh 11 | 12 | echo "compare results" 13 | ROOT_TREE_REMOTE=`cat data/layers/layer.0.csv` 14 | if [ ${ROOT_TREE_REMOTE} = ${ROOT_TREE_LOCAL} ]; then 15 | echo "same"; 16 | else 17 | >&2 echo "different: ${ROOT_TREE_REMOTE} != ${ROOT_TREE_LOCAL}" 18 | exit 255 19 | fi 20 | 21 | cd ../.. 22 | -------------------------------------------------------------------------------- /CI/remoteRestart.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | scriptdir=$(dirname "$(readlink -f "$0")") 3 | 4 | if ! /bin/sh ${scriptdir}/startIRI.sh; then 5 | exit 255 6 | fi 7 | 8 | cd docs/private_tangle 9 | 10 | echo "starting Signing server" 11 | ./11_run_signature_source_server.sh & 12 | sleep 10 13 | 14 | echo "starting Compass bootstrap" 15 | ./12_run_coordinator_remote.sh -bootstrap -broadcast & 16 | sleep 20 17 | 18 | echo "restarting Compass" 19 | docker kill $(docker ps | grep coordinator | cut -f1 -d\ ) 20 | while [ `docker ps | grep coordinator | cut -f1 -d\ ` ]; do 21 | sleep 1; 22 | done 23 | sleep 2 24 | 25 | ./12_run_coordinator_remote.sh -broadcast & 26 | sleep 20 27 | 28 | if ! /bin/sh ${scriptdir}/checkLogs.sh; then 29 | exit 255 30 | fi 31 | 32 | cd ../.. -------------------------------------------------------------------------------- /CI/setupTests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | scriptdir=$(dirname "$(readlink -f "$0")") 3 | 4 | #prep environment 5 | echo "building docker images" 6 | bazel run //docker:coordinator 7 | bazel run //docker:layers_calculator 8 | bazel run //docker:signature_source_server 9 | 10 | echo "setting up configs" 11 | cd docs/private_tangle 12 | cat config.example.json| jq '.tick = 5000' > config.json 13 | cp snapshot.example.txt snapshot.txt 14 | 15 | echo "calculating merkle tree" 16 | ./01_calculate_layers.sh 17 | 18 | cd ${scriptdir} -------------------------------------------------------------------------------- /CI/startIRI.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd docs/private_tangle 3 | 4 | echo "starting IRI" 5 | ./02_run_iri.sh & 6 | until [ `docker ps | grep iri | cut -f1 -d\ ` ]; do 7 | sleep 1; 8 | done 9 | 10 | echo "waiting for IRI to start" 11 | while ! curl http://localhost:14265 -X POST -H 'Content-Type: application/json' -H 'X-IOTA-API-Version: 1' -d '{"command": "getNodeInfo"}'; do 12 | echo "API not ready" 13 | sleep 1; 14 | if ! [ `docker ps | grep iri | cut -f1 -d\ ` ]; then 15 | echo "IRI failed to initialize" 16 | exit 255 17 | fi 18 | done 19 | echo "" 20 | echo "IRI initialized" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Deprecated 2 | ============================= 3 | 4 | This solution has been deprecated. Please use [Hornet coordinator plug-in](https://docs.iota.org/docs/hornet/1.1/tutorials/set-up-a-private-tangle-hornet) when setting up a private Tangle instead. 5 | 6 | # Compass 7 | 8 | Compass is an open-source implementation of an IOTA Network coordinator. 9 | 10 | ## Getting started 11 | 1. Install bazel 0.28.1 from https://bazel.build 12 | 2. Build & install the Compass docker image via `bazel run //docker:coordinator` 13 | 3. Build & install the LayerCalculator docker image via `bazel run //docker:layers_calculator` 14 | 3. Look at the run scripts in [docs/private_tangle](docs/private_tangle) to get you started. 15 | 16 | There also exists a more detailed howto for setting up private Tangle networks in [docs/HOWTO_private_tangle.md](docs/HOWTO_private_tangle.md) 17 | 18 | -------------------------------------------------------------------------------- /Security.MD: -------------------------------------------------------------------------------- 1 |

Responsible disclosure policy

2 | 3 | At the IOTA Foundation, we consider the security of our systems a top priority. But no matter how much effort we put into system security, there can still be vulnerabilities present. If you've discovered a vulnerability, please follow the guidelines below to report it to our security team: 4 |
    5 |
  • E-mail your findings to secops@iota.org. If the report contains highly sensitive information, please consider encrypting your findings using our contact@iota.org (466385BD0B40D9550F93C04746A440CCE5664A64) PGP key.
  • 6 |
7 | Please follow these rules when testing/reporting vulnerabilities: 8 |
    9 |
  • Do not take advantage of the vulnerability you have discovered, for example by downloading more data than is necessary to demonstrate the vulnerability.
  • 10 |
  • Do not read, modify or delete data that isn't your own.
  • 11 |
  • We ask that you do not to disclose the problem to third parties until it has been resolved.
  • 12 |
  • The scope of the program is limited to technical vulnerabilities in IOTA Foundations's web applications and open source software packages distributed through GitHub, please do not try to test physical security or attempt phishing attacks against our employees, and so on.
  • 13 |
  • Out of concern for the availability of our services to all users, please do not attempt to carry out DoS attacks, leverage black hat SEO techniques, spam people or any other mischief (follow the golden rule). We also discourage the use of any vulnerability testing tools that automatically generate significant volumes of traffic.
  • 14 |
15 | What we promise: 16 |
    17 |
  • We will respond to your report within 3 business days with our evaluation of the report and an expected resolution date.
  • 18 |
  • If you have followed the instructions above, we will not take any legal action against you in regard to the report.
  • 19 |
  • We will keep you informed during all stages of resolving the problem.
  • 20 |
  • To show our appreciation for your effort and cooperation during the report, we will list your name and a link to a personal website/social network profile on the page below so that the public can know you've helped keep the IOTA Foundation secure.
  • 21 |
22 | We sincerely appreciate the efforts of security researchers in keeping our community safe. 23 | 24 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- 1 | workspace(name = "org_iota_compass") 2 | 3 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 4 | 5 | http_archive( 6 | name = "io_bazel_rules_docker", 7 | sha256 = "e513c0ac6534810eb7a14bf025a0f159726753f97f74ab7863c650d26e01d677", 8 | strip_prefix = "rules_docker-0.9.0", 9 | urls = ["https://github.com/bazelbuild/rules_docker/releases/download/v0.9.0/rules_docker-v0.9.0.tar.gz"], 10 | ) 11 | 12 | load( 13 | "@io_bazel_rules_docker//repositories:repositories.bzl", 14 | container_repositories = "repositories", 15 | ) 16 | 17 | container_repositories() 18 | 19 | load( 20 | "@io_bazel_rules_docker//repositories:deps.bzl", 21 | container_deps = "deps") 22 | 23 | container_deps() 24 | 25 | load( 26 | "@io_bazel_rules_docker//container:container.bzl", 27 | "container_pull", 28 | ) 29 | 30 | container_pull( 31 | name = "java_base", 32 | digest = 33 | "sha256:bb1c9179c2263733f235291998cb849d52fb730743125420cf4f97a362d6a6dd", 34 | registry = "gcr.io", 35 | repository = "distroless/java", 36 | ) 37 | 38 | # Java dependencies 39 | 40 | load("//third-party:maven_deps.bzl", "maven_jars") 41 | 42 | maven_jars() 43 | 44 | # Protobuf 45 | PROTOBUF_REV = "3.9.1" 46 | 47 | PROTOBUF_PREFIX = "protobuf-%s" % PROTOBUF_REV 48 | 49 | PROTOBUF_URL = "https://github.com/protocolbuffers/protobuf/releases/download/v{}/protobuf-java-{}.zip".format(PROTOBUF_REV, PROTOBUF_REV) 50 | 51 | PROTOBUF_SHA = "6a875dc8f90c801bf55fb05e528941cda4c82d77f4f81229810bb05ea43b96e0" 52 | 53 | http_archive( 54 | name = "com_google_protobuf", 55 | sha256 = PROTOBUF_SHA, 56 | strip_prefix = PROTOBUF_PREFIX, 57 | urls = [PROTOBUF_URL], 58 | ) 59 | 60 | http_archive( 61 | name = "com_google_protobuf_java", 62 | sha256 = PROTOBUF_SHA, 63 | strip_prefix = PROTOBUF_PREFIX, 64 | urls = [PROTOBUF_URL], 65 | ) 66 | 67 | http_archive( 68 | name = "com_google_protobuf_deps", 69 | sha256 = PROTOBUF_SHA, 70 | strip_prefix = PROTOBUF_PREFIX, 71 | urls = [PROTOBUF_URL], 72 | ) 73 | 74 | load("@com_google_protobuf_deps//:protobuf_deps.bzl", "protobuf_deps") 75 | 76 | # Load common dependencies. 77 | protobuf_deps() 78 | 79 | http_archive( 80 | name = "io_grpc_grpc_java", 81 | sha256 = "2829057f3ae349d85c4494411d9e2d2d130ff199f94622de01c6632c2187c2b6", 82 | strip_prefix = "grpc-java-1.26.1", 83 | urls = ["https://github.com/grpc/grpc-java/archive/v1.26.1.zip"], 84 | ) 85 | 86 | load("@io_grpc_grpc_java//:repositories.bzl", "grpc_java_repositories") 87 | 88 | grpc_java_repositories( 89 | omit_com_google_code_findbugs_jsr305 = True, 90 | omit_com_google_code_gson = True, 91 | omit_com_google_errorprone_error_prone_annotations = True, 92 | omit_com_google_guava = True, 93 | omit_com_google_j2objc_j2objc_annotations = True, 94 | omit_com_google_protobuf = True, 95 | omit_com_squareup_okio = True, 96 | omit_junit_junit = True, 97 | omit_org_apache_commons_lang3 = True, 98 | omit_org_codehaus_mojo_animal_sniffer_annotations = True, 99 | ) 100 | -------------------------------------------------------------------------------- /compass/BUILD: -------------------------------------------------------------------------------- 1 | COORDINATOR_RUNTIME_DEPS = [ 2 | "@org_slf4j_slf4j_simple//jar", 3 | "@com_squareup_okhttp3_okhttp//jar", 4 | "@com_squareup_retrofit2_converter_gson//jar", 5 | "@com_squareup_retrofit2_retrofit//jar", 6 | "@com_squareup_okio_okio//jar", 7 | "@io_netty_netty_tcnative_boringssl_static//jar", 8 | ] 9 | 10 | java_binary( 11 | name = "layers_calculator", 12 | srcs = ["LayersCalculator.java"], 13 | classpath_resources = ["simplelogger.properties"], 14 | main_class = "org.iota.compass.LayersCalculator", 15 | visibility = ["//visibility:public"], 16 | runtime_deps = COORDINATOR_RUNTIME_DEPS, 17 | deps = [ 18 | "//compass/conf", 19 | "//compass/milestone", 20 | "//compass/sign:common", 21 | "//compass/sign:helper", 22 | "@com_beust_jcommander//jar", 23 | "@com_google_guava_guava//jar", 24 | "@org_iota_jota//jar", 25 | "@org_slf4j_slf4j_api//jar", 26 | ], 27 | ) 28 | 29 | java_binary( 30 | name = "shadowing_coordinator", 31 | srcs = ["ShadowingCoordinator.java"], 32 | classpath_resources = ["simplelogger.properties"], 33 | main_class = "org.iota.compass.ShadowingCoordinator", 34 | visibility = ["//visibility:public"], 35 | runtime_deps = COORDINATOR_RUNTIME_DEPS, 36 | deps = [ 37 | "//compass/conf", 38 | "//compass/crypto", 39 | "//compass/milestone", 40 | "//compass/sign:common", 41 | "//compass/sign:helper", 42 | "@com_beust_jcommander//jar", 43 | "@org_apache_commons_commons_lang3//jar", 44 | "@org_iota_jota//jar", 45 | "@org_slf4j_slf4j_api//jar", 46 | ], 47 | ) 48 | 49 | java_binary( 50 | name = "coordinator", 51 | srcs = ["Coordinator.java"], 52 | classpath_resources = ["simplelogger.properties"], 53 | main_class = "org.iota.compass.Coordinator", 54 | visibility = ["//visibility:public"], 55 | runtime_deps = COORDINATOR_RUNTIME_DEPS, 56 | deps = [ 57 | "//compass/conf", 58 | "//compass/exceptions", 59 | "//compass/milestone", 60 | "//compass/sign:common", 61 | "//compass/sign:helper", 62 | "//compass/sign:remote", 63 | "@com_beust_jcommander//jar", 64 | "@org_iota_jota//jar", 65 | "@org_slf4j_slf4j_api//jar", 66 | ], 67 | ) 68 | -------------------------------------------------------------------------------- /compass/Coordinator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.beust.jcommander.JCommander; 29 | 30 | import com.beust.jcommander.ParameterException; 31 | import org.iota.jota.pow.SpongeFactory; 32 | import org.iota.compass.conf.CoordinatorConfiguration; 33 | import org.iota.compass.conf.CoordinatorState; 34 | import org.iota.compass.exceptions.TimeoutException; 35 | import org.slf4j.Logger; 36 | import org.slf4j.LoggerFactory; 37 | 38 | import java.io.*; 39 | import java.net.URI; 40 | import java.net.URL; 41 | import java.rmi.Remote; 42 | import java.security.Security; 43 | import java.util.List; 44 | import java.util.Objects; 45 | import java.util.stream.Collectors; 46 | 47 | import org.iota.jota.IotaAPI; 48 | import org.iota.jota.dto.response.CheckConsistencyResponse; 49 | import org.iota.jota.dto.response.GetNodeInfoResponse; 50 | import org.iota.jota.dto.response.GetTransactionsToApproveResponse; 51 | import org.iota.jota.error.ArgumentException; 52 | import org.iota.jota.model.Transaction; 53 | 54 | public class Coordinator { 55 | private static final Logger log = LoggerFactory.getLogger(Coordinator.class); 56 | private final MilestoneSource db; 57 | private final IotaAPI api; 58 | private final CoordinatorConfiguration config; 59 | private CoordinatorState state; 60 | private List validatorAPIs; 61 | private Thread workerThread; 62 | private boolean shutdown; 63 | 64 | private long milestoneTick; 65 | private int depth; 66 | 67 | private Coordinator(CoordinatorConfiguration config, CoordinatorState state, SignatureSource signatureSource) throws IOException { 68 | this.config = config; 69 | this.state = state; 70 | this.shutdown = false; 71 | URL node = new URL(config.host); 72 | 73 | this.db = new MilestoneDatabase(config.powMode, 74 | config.powHost, 75 | signatureSource, 76 | config.layersPath); 77 | this.api = new IotaAPI.Builder() 78 | .protocol(node.getProtocol()) 79 | .host(node.getHost()) 80 | .port(node.getPort()) 81 | .build(); 82 | 83 | validatorAPIs = config.validators.stream().map(url -> { 84 | URI uri = URI.create(url); 85 | return new IotaAPI.Builder().protocol(uri.getScheme()) 86 | .host(uri.getHost()) 87 | .port(uri.getPort()) 88 | .build(); 89 | }).collect(Collectors.toList()); 90 | } 91 | 92 | private static CoordinatorState loadState(String path) throws IOException, ClassNotFoundException { 93 | CoordinatorState state; 94 | try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) { 95 | state = (CoordinatorState) ois.readObject(); 96 | log.info("loaded index {}", state.latestMilestoneIndex); 97 | } 98 | return state; 99 | } 100 | 101 | private void storeState(CoordinatorState state, String path) throws IOException { 102 | try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) { 103 | oos.writeObject(state); 104 | log.info("stored index {}", state.latestMilestoneIndex); 105 | } 106 | } 107 | 108 | private void shutdownHook() { 109 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 110 | log.info("Shutting down Compass after next milestone..."); 111 | this.shutdown = true; 112 | try { 113 | this.workerThread.join(); 114 | } catch (InterruptedException e) { 115 | String msg = "Interrupted while waiting for Compass to issue next milestone."; 116 | log.error(msg, e); 117 | } 118 | }, "Shutdown Hook")); 119 | } 120 | 121 | public static void main(String[] args) throws Exception { 122 | 123 | // Limit DNS caching for resolved and failed records to 5 seconds 124 | Security.setProperty("networkaddress.cache.ttl" , RemoteSignatureSource.DEFAULT_CACHE_TTL); 125 | Security.setProperty("networkaddress.cache.negative.ttl" , RemoteSignatureSource.DEFAULT_CACHE_TTL); 126 | 127 | CoordinatorConfiguration config = new CoordinatorConfiguration(); 128 | CoordinatorState state; 129 | 130 | JCommander.newBuilder() 131 | .addObject(config) 132 | .acceptUnknownOptions(true) 133 | .build() 134 | .parse(args); 135 | 136 | if (config.powHost != null && config.powMode != SpongeFactory.Mode.CURLP81) { 137 | throw new ParameterException("Remote PoW only supports CURLP81."); 138 | } 139 | 140 | // We want an empty state if bootstrapping 141 | // and to allow overriding state file using `-index` flag 142 | if (config.bootstrap || config.index != null) { 143 | state = new CoordinatorState(); 144 | state.latestMilestoneIndex = config.index == null ? 0 : config.index; 145 | } else { 146 | try { 147 | state = loadState(config.statePath); 148 | } catch (Exception e) { 149 | String msg = "Error loading Compass state file '" + config.statePath + "'! State file required if not bootstrapping..."; 150 | 151 | log.error(msg, e); 152 | throw new RuntimeException(e); 153 | } 154 | } 155 | 156 | Coordinator coo = new Coordinator(config, state, SignatureSourceHelper.signatureSourceFromArgs(config.signatureSource, args)); 157 | coo.setup(); 158 | coo.start(); 159 | } 160 | 161 | /** 162 | * Checks that node is solid, bootstrapped and on latest milestone. 163 | * 164 | * @param nodeInfo response from node API call 165 | * @return true if node is solid 166 | */ 167 | private boolean nodeIsSolid(GetNodeInfoResponse nodeInfo) { 168 | if (nodeInfo.getLatestMilestone().equals(MilestoneSource.EMPTY_HASH) || 169 | nodeInfo.getLatestSolidSubtangleMilestone().equals(MilestoneSource.EMPTY_HASH)) 170 | return false; 171 | 172 | return nodeInfo.getLatestSolidSubtangleMilestoneIndex() == nodeInfo.getLatestMilestoneIndex(); 173 | } 174 | 175 | /** 176 | * Checks that node's latest solid milestone matches internal state. 177 | * 178 | * @param nodeInfo response from node API call 179 | * @return true if node is solid 180 | */ 181 | private boolean nodeMatchesInternalState(GetNodeInfoResponse nodeInfo) { 182 | return config.inception || (nodeInfo.getLatestSolidSubtangleMilestoneIndex() == state.latestMilestoneIndex); 183 | } 184 | 185 | /** 186 | * Sets up the coordinator and validates arguments 187 | */ 188 | private void setup() throws InterruptedException { 189 | log.info("Setup"); 190 | GetNodeInfoResponse nodeInfoResponse = getNodeInfoWithRetries(); 191 | 192 | if (config.bootstrap) { 193 | log.info("Bootstrapping."); 194 | if (!nodeInfoResponse.getLatestSolidSubtangleMilestone().equals(MilestoneSource.EMPTY_HASH) || 195 | !nodeInfoResponse.getLatestMilestone().equals(MilestoneSource.EMPTY_HASH)) { 196 | throw new RuntimeException("Network already bootstrapped"); 197 | } 198 | } 199 | 200 | log.info("Starting index from: " + state.latestMilestoneIndex); 201 | if (nodeInfoResponse.getLatestMilestoneIndex() > state.latestMilestoneIndex && !config.inception) { 202 | throw new RuntimeException("Provided index is lower than latest seen milestone: " + 203 | nodeInfoResponse.getLatestMilestoneIndex() + " vs " + state.latestMilestoneIndex); 204 | } 205 | 206 | milestoneTick = config.tick; 207 | if (milestoneTick <= 0) { 208 | throw new IllegalArgumentException("tick must be > 0"); 209 | } 210 | log.info("Setting milestone tick rate (ms) to: " + milestoneTick); 211 | 212 | 213 | depth = config.depth; 214 | if (depth < 0) { 215 | throw new IllegalArgumentException("depth must be >= 0"); 216 | } 217 | log.info("Setting depth to: " + depth); 218 | 219 | log.info("Validating Coordinator addresses."); 220 | if (!Objects.equals(nodeInfoResponse.getCoordinatorAddress(), db.getRoot())) { 221 | log.warn("Coordinator Addresses do not match! {} vs. {}", nodeInfoResponse.getCoordinatorAddress(), db.getRoot()); 222 | if (!config.allowDifferentCooAddress) { 223 | throw new IllegalArgumentException("Coordinator Addresses do not match!"); 224 | } 225 | } 226 | } 227 | 228 | private void start() throws InterruptedException { 229 | int bootstrapStage = 0; 230 | int milestonePropagationRetries = 0; 231 | int validationRetries = 0; 232 | this.workerThread = Thread.currentThread(); 233 | shutdownHook(); 234 | 235 | while (true) { 236 | //assume that we will be calling gtta 237 | boolean isReferencingLastMilestone = false; 238 | String trunk, branch; 239 | GetNodeInfoResponse nodeInfoResponse = getNodeInfoWithRetries(); 240 | 241 | if (!config.bootstrap) { 242 | if (!nodeIsSolid(nodeInfoResponse)) { 243 | log.warn("Node not solid."); 244 | Thread.sleep(config.unsolidDelay); 245 | continue; 246 | } 247 | if (!nodeMatchesInternalState(nodeInfoResponse)) { 248 | if (attemptToRepropagateLatestMilestone(milestonePropagationRetries, 249 | nodeInfoResponse.getLatestSolidSubtangleMilestoneIndex())) { 250 | milestonePropagationRetries++; 251 | // We wait a third of the milestone tick 252 | Thread.sleep(milestoneTick / 3); 253 | continue; 254 | } 255 | else { 256 | throw new RuntimeException("Latest milestone " + state.latestMilestoneHash + " #" + 257 | state.latestMilestoneIndex + " is failing to propagate!!!"); 258 | } 259 | } 260 | milestonePropagationRetries = 0; 261 | 262 | //if special referencing mode 263 | if (config.referenceLastMilestone) { 264 | trunk = state.latestMilestoneHash; 265 | branch = state.latestMilestoneHash; 266 | } 267 | //normal flow 268 | else { 269 | // We want to perform shutdown only when we are ready to issue the next normal milestone 270 | // and the node is in sync with the latest milestone we issued. 271 | if (shutdown) { 272 | return; 273 | } 274 | // GetTransactionsToApprove will return tips referencing latest milestone. 275 | GetTransactionsToApproveResponse txToApprove = null; 276 | try { 277 | txToApprove = getGetTransactionsToApproveResponseWithRetries(); 278 | 279 | trunk = txToApprove.getTrunkTransaction(); 280 | if (trunk == null || trunk.isEmpty()) { 281 | throw new RuntimeException("GTTA failed to return trunk"); 282 | } 283 | branch = txToApprove.getBranchTransaction(); 284 | if (branch == null || branch.isEmpty()) { 285 | throw new RuntimeException("GTTA failed to return branch"); 286 | } 287 | } catch (TimeoutException e) { 288 | log.warn("Due to timeout we will now reference last milestone"); 289 | trunk = state.latestMilestoneHash; 290 | branch = state.latestMilestoneHash; 291 | //gtta was not used so we set this flag to true 292 | isReferencingLastMilestone = true; 293 | } 294 | } 295 | 296 | try { 297 | // This can also throw a RuntimException in case of API Error 298 | if (!validateTransactionsToApprove(trunk, branch)) { 299 | throw new RuntimeException("Trunk & branch not consistent"); 300 | } 301 | } catch (RuntimeException e) { 302 | if (++validationRetries >= config.validationAttempts) { 303 | throw new RuntimeException("Trunk & branch were not consistent on multiple attempts!!! T: " + trunk + " B: " + branch); 304 | } else { 305 | log.warn("Validation failed, #{} of #{} attempts. Trying again...", validationRetries, config.validationAttempts); 306 | // Perform gTTA and Validation again 307 | continue; 308 | } 309 | } 310 | validationRetries = 0; 311 | } else { 312 | if (bootstrapStage >= 3) { 313 | config.bootstrap = false; 314 | continue; 315 | } 316 | if (bootstrapStage == 0) { 317 | log.info("Bootstrapping network."); 318 | trunk = MilestoneSource.EMPTY_HASH; 319 | branch = MilestoneSource.EMPTY_HASH; 320 | bootstrapStage = 1; 321 | } else { 322 | // Bootstrapping means creating a chain of milestones without pulling in external transactions. 323 | log.info("Reusing last milestone."); 324 | trunk = state.latestMilestoneHash; 325 | branch = MilestoneSource.EMPTY_HASH; 326 | bootstrapStage++; 327 | } 328 | 329 | if (bootstrapStage == 2) { 330 | if (!nodeIsSolid(nodeInfoResponse)) { 331 | log.warn("Node not solid."); 332 | Thread.sleep(config.unsolidDelay); 333 | continue; 334 | } else if (!nodeMatchesInternalState(nodeInfoResponse)) { 335 | log.warn("Node's solid milestone does not match Compass state: " + state.latestMilestoneIndex); 336 | Thread.sleep(config.unsolidDelay); 337 | continue; 338 | } 339 | } 340 | } 341 | 342 | // If all the above checks pass we are ready to issue a new milestone 343 | state.latestMilestoneIndex++; 344 | 345 | createAndBroadcastMilestone(trunk, branch); 346 | state.latestMilestoneTime = System.currentTimeMillis(); 347 | 348 | // Everything went fine, now we store 349 | try { 350 | storeState(state, config.statePath); 351 | } catch (Exception e) { 352 | String msg = "Error saving Compass state to file '" + config.statePath + "'!"; 353 | 354 | log.error(msg, e); 355 | throw new RuntimeException(e); 356 | } 357 | 358 | //if special referencing mode 359 | if (config.referenceLastMilestone) { 360 | //exit compass 361 | log.info("Referencing milestone broadcasted. Please validate manually whether it was recieved."); 362 | log.info("Gracefully exiting compass"); 363 | return; 364 | } 365 | //normal mode 366 | else { 367 | Thread.sleep(milestoneTick); 368 | } 369 | } 370 | } 371 | 372 | private void createAndBroadcastMilestone(String trunk, String branch) throws InterruptedException { 373 | log.info("Issuing milestone: " + state.latestMilestoneIndex); 374 | log.info("Trunk: " + trunk + " Branch: " + branch); 375 | 376 | List latestMilestoneTransactions = db.createMilestone(trunk, branch, state.latestMilestoneIndex, config.MWM); 377 | state.latestMilestoneTransactions = latestMilestoneTransactions.stream().map(Transaction::toTrytes).collect(Collectors.toList()); 378 | state.latestMilestoneHash = latestMilestoneTransactions.get(0).getHash(); 379 | 380 | // Do not store the state before broadcasting, since if broadcasting fails we should repeat the same milestone. 381 | broadcastLatestMilestone(); 382 | } 383 | 384 | /** 385 | * Checks the consistency of 2 given transactions against the nodes specified by {@link #validatorAPIs} 386 | * @param trunk transaction to be approved by milestone 387 | * @param branch transaction to be approved by milestone 388 | * @return {@code true} if the checks passed or didn't take place. Else return {@code false}. 389 | */ 390 | private boolean validateTransactionsToApprove(String trunk, String branch) throws InterruptedException { 391 | if (validatorAPIs.size() > 0) { 392 | 393 | // Give tips time to solidify on the validators 394 | Thread.sleep(config.validationDelay * 1000); 395 | 396 | return validatorAPIs.parallelStream().allMatch(validatorApi -> { 397 | CheckConsistencyResponse response; 398 | try { 399 | response = getCheckConsistencyResponseWithRetries(trunk, branch, validatorApi); 400 | if (!response.getState()) { 401 | log.error("{} reported invalid consistency: {}", validatorApi.getHost(), response.getInfo()); 402 | } 403 | return response.getState(); 404 | } catch (InterruptedException e) { 405 | throw new RuntimeException("Validation of transactions to approve failed", e); 406 | } 407 | }); 408 | } 409 | 410 | //nothing was checked so validation can't fail 411 | return true; 412 | } 413 | 414 | private GetNodeInfoResponse getNodeInfoWithRetries() throws InterruptedException { 415 | GetNodeInfoResponse response = null; 416 | for(int i = 0; i < config.APIRetries; i++) { 417 | try { 418 | response = api.getNodeInfo(); 419 | break; 420 | } catch (IllegalStateException | ArgumentException | IllegalAccessError e) { 421 | log.error("API call failed: ", e); 422 | Thread.sleep(config.APIRetryInterval); 423 | } 424 | } 425 | if (response == null) { 426 | throw new RuntimeException("getNodeInfo failed, check node!"); 427 | } 428 | 429 | return response; 430 | } 431 | 432 | private GetTransactionsToApproveResponse getGetTransactionsToApproveResponseWithRetries() throws 433 | TimeoutException, InterruptedException { 434 | GetTransactionsToApproveResponse response = null; 435 | for(int i = 0; i < config.APIRetries; i++) { 436 | try { 437 | response = api.getTransactionsToApprove(depth, state.latestMilestoneHash); 438 | break; 439 | } catch (IllegalStateException | IllegalAccessError e) { 440 | log.error("API call failed: ", e); 441 | Thread.sleep(config.APIRetryInterval); 442 | } 443 | catch (ArgumentException e) { 444 | log.error("There was a problem processing Get Transactions To Approve: ", e); 445 | if (e.getMessage().contains("exceeded timeout")) { 446 | throw new TimeoutException("Get Transactions To Approve call timed out", e); 447 | } 448 | else { 449 | Thread.sleep(config.APIRetryInterval); 450 | } 451 | } 452 | } 453 | if (response == null) { 454 | throw new RuntimeException("getTransactionsToApprove failed, check node!"); 455 | } 456 | 457 | return response; 458 | } 459 | 460 | private CheckConsistencyResponse getCheckConsistencyResponseWithRetries(String trunk, String branch, IotaAPI api) throws InterruptedException { 461 | CheckConsistencyResponse response = null; 462 | for(int i = 0; i < config.APIRetries; i++) { 463 | try { 464 | response = api.checkConsistency(trunk, branch); 465 | break; 466 | } catch (IllegalStateException | ArgumentException | IllegalAccessError e) { 467 | log.error("API call failed: ", e); 468 | Thread.sleep(config.APIRetryInterval); 469 | } 470 | } 471 | if (response == null) { 472 | throw new RuntimeException("checkConsistency failed, check node!"); 473 | } 474 | 475 | return response; 476 | } 477 | 478 | private void storeAndBroadcastWithRetries(String tx) throws InterruptedException { 479 | for(int i = 0; i < config.APIRetries; i++) { 480 | try { 481 | api.storeAndBroadcast(tx); 482 | return; 483 | } catch (IllegalStateException | ArgumentException | IllegalAccessError e) { 484 | log.error("API call failed: ", e); 485 | Thread.sleep(config.APIRetryInterval); 486 | } 487 | } 488 | 489 | throw new RuntimeException("storeAndBroadcast failed, check node!"); 490 | } 491 | 492 | private void broadcastLatestMilestone() throws InterruptedException { 493 | if (config.broadcast) { 494 | for (String tx : state.latestMilestoneTransactions) { 495 | storeAndBroadcastWithRetries(tx); 496 | } 497 | log.info("Broadcast milestone: " + state.latestMilestoneIndex); 498 | } 499 | } 500 | 501 | /** 502 | * Attempts to rebroadcast the latest milestone. Should succeed if {@code milestonePropagationRetries} 503 | * is not above configured threshold. 504 | * 505 | * @param milestonePropagationRetries number of propagation retries that have already taken place 506 | * @param lsm latest solid milestone index 507 | * @return {@code true} if the milestone was broadcasted again else return false 508 | * @throws InterruptedException upon an API problem 509 | */ 510 | private boolean attemptToRepropagateLatestMilestone(int milestonePropagationRetries, int lsm) throws InterruptedException { 511 | // Bail if we attempted to broadcast the latest Milestone too many times 512 | if (milestonePropagationRetries > config.propagationRetriesThreshold) { 513 | return false; 514 | } 515 | log.warn("getNodeInfo returned latestSolidSubtangleMilestoneIndex #{}, " + 516 | "it should be #{}. Rebroadcasting latest milestone.", lsm, state.latestMilestoneIndex); 517 | // We reissue the previous milestone again 518 | broadcastLatestMilestone(); 519 | return true; 520 | } 521 | } 522 | -------------------------------------------------------------------------------- /compass/LayersCalculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.beust.jcommander.JCommander; 29 | import com.google.common.math.IntMath; 30 | import org.iota.jota.pow.ICurl; 31 | import org.iota.jota.pow.SpongeFactory; 32 | import org.iota.jota.utils.Converter; 33 | import org.iota.compass.conf.LayersCalculatorConfiguration; 34 | import org.slf4j.Logger; 35 | import org.slf4j.LoggerFactory; 36 | 37 | import java.io.BufferedWriter; 38 | import java.io.IOException; 39 | import java.math.RoundingMode; 40 | import java.nio.file.Files; 41 | import java.nio.file.Path; 42 | import java.nio.file.Paths; 43 | import java.nio.file.StandardOpenOption; 44 | import java.util.ArrayList; 45 | import java.util.Collections; 46 | import java.util.List; 47 | import java.util.stream.Collectors; 48 | import java.util.stream.IntStream; 49 | 50 | public class LayersCalculator implements Runnable { 51 | private final static Logger log = LoggerFactory.getLogger(LayersCalculator.class); 52 | 53 | private final LayersCalculatorConfiguration config; 54 | private final SignatureSource signatureSource; 55 | private final int count; 56 | 57 | public LayersCalculator(LayersCalculatorConfiguration config, SignatureSource signatureSource) { 58 | this.count = 1 << config.depth; 59 | this.config = config; 60 | this.signatureSource = signatureSource; 61 | } 62 | 63 | public static void main(String[] args) throws IOException { 64 | LayersCalculatorConfiguration config = new LayersCalculatorConfiguration(); 65 | 66 | JCommander.newBuilder() 67 | .addObject(config) 68 | .acceptUnknownOptions(true) 69 | .build() 70 | .parse(args); 71 | 72 | LayersCalculator calc = new LayersCalculator(config, SignatureSourceHelper.signatureSourceFromArgs(config.signatureSource, args)); 73 | calc.run(); 74 | } 75 | 76 | @Override 77 | public void run() { 78 | Path layersPath = Paths.get(config.layersPath); 79 | try { 80 | if (Files.notExists(layersPath)) { 81 | Files.createDirectory(layersPath); 82 | } 83 | } catch (IOException e) { 84 | log.warn("failed to create folder: " + layersPath, e); 85 | } 86 | 87 | List addresses = calculateAllAddresses(); 88 | log.info("Calculated all addresses."); 89 | List> layers = calculateAllLayers(addresses); 90 | 91 | for (int i = 0; i < layers.size(); i++) { 92 | try { 93 | writeLayer(layersPath, i, layers.get(i)); 94 | } catch (IOException e) { 95 | log.error("Error writing layer: " + i, e); 96 | } 97 | } 98 | log.info("Successfully wrote Merkle Tree with root: " + layers.get(0).get(0)); 99 | } 100 | 101 | //Package Private For Testing 102 | List calculateAllAddresses() { 103 | log.info("Calculating " + count + " addresses."); 104 | return IntStream.range(0, count) 105 | .mapToObj(signatureSource::getAddress) 106 | .parallel() 107 | .collect(Collectors.toList()); 108 | } 109 | 110 | //Package Private For Testing 111 | List> calculateAllLayers(List addresses) { 112 | int depth = IntMath.log2(addresses.size(), RoundingMode.FLOOR); 113 | List> layers = new ArrayList<>(depth); 114 | List last = addresses; 115 | layers.add(last); 116 | 117 | while (depth-- > 0) { 118 | log.info("Calculating nodes for depth " + depth); 119 | last = calculateNextLayer(last); 120 | 121 | layers.add(last); 122 | } 123 | 124 | Collections.reverse(layers); 125 | return layers; 126 | } 127 | 128 | private void writeLayer(Path outputDir, int depth, List elements) throws IOException { 129 | Path out = Paths.get(outputDir.toString(), ("layer." + depth + ".csv")); 130 | BufferedWriter writer = Files.newBufferedWriter(out, StandardOpenOption.CREATE); 131 | 132 | for (String node : elements) { 133 | writer.write(node + "\n"); 134 | } 135 | 136 | writer.close(); 137 | } 138 | 139 | private List calculateNextLayer(List inLayer) { 140 | log.info("Calculating"); 141 | final List layer = Collections.unmodifiableList(inLayer); 142 | 143 | return IntStream.range(0, layer.size() / 2).mapToObj((int idx) -> { 144 | ICurl sp = SpongeFactory.create(signatureSource.getSignatureMode()); 145 | 146 | int[] t1 = Converter.trits(layer.get(idx * 2)); 147 | int[] t2 = Converter.trits(layer.get(idx * 2 + 1)); 148 | 149 | sp.absorb(t1, 0, t1.length); 150 | sp.absorb(t2, 0, t2.length); 151 | 152 | sp.squeeze(t1, 0, t1.length); 153 | 154 | return Converter.trytes(t1); 155 | }).parallel().collect(Collectors.toList()); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /compass/ShadowingCoordinator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.beust.jcommander.JCommander; 29 | import org.iota.jota.IotaAPI; 30 | import org.iota.jota.dto.response.GetNodeInfoResponse; 31 | import org.iota.jota.dto.response.GetTransactionsToApproveResponse; 32 | import org.iota.jota.error.ArgumentException; 33 | import org.iota.jota.model.Transaction; 34 | import org.apache.commons.lang3.NotImplementedException; 35 | import org.iota.compass.conf.ShadowingCoordinatorConfiguration; 36 | import org.iota.compass.crypto.Hasher; 37 | import org.slf4j.Logger; 38 | import org.slf4j.LoggerFactory; 39 | 40 | import java.io.IOException; 41 | import java.net.URL; 42 | import java.nio.file.Files; 43 | import java.nio.file.Paths; 44 | import java.util.ArrayList; 45 | import java.util.Comparator; 46 | import java.util.List; 47 | import java.util.stream.Collectors; 48 | 49 | 50 | /** 51 | * As opposed to the regular `org.iota.compass.Coordinator`, this coordinator will issue shadow milestones for an existing list of milestones. 52 | * This is useful if you want to migrate an existing Coordinator to a new seed or hashing method. 53 | *

54 | * !!! *NOTE* that the IRI node this ShadowingCoordinator talks to should already be configured to use the new Coordinator address !!! 55 | */ 56 | public class ShadowingCoordinator { 57 | private final Logger log = LoggerFactory.getLogger(getClass()); 58 | 59 | private final ShadowingCoordinatorConfiguration config; 60 | private final IotaAPI api; 61 | private final MilestoneSource db; 62 | private List oldMilestones; 63 | 64 | public ShadowingCoordinator(ShadowingCoordinatorConfiguration config, SignatureSource signatureSource) throws IOException { 65 | this.config = config; 66 | 67 | this.db = new MilestoneDatabase(config.powMode, 68 | config.powHost, signatureSource, config.layersPath); 69 | URL node = new URL(config.host); 70 | this.api = new IotaAPI.Builder() 71 | .protocol(node.getProtocol()) 72 | .host(node.getHost()) 73 | .port(node.getPort()) 74 | .build(); 75 | } 76 | 77 | public static void main(String[] args) throws Exception { 78 | ShadowingCoordinatorConfiguration config = new ShadowingCoordinatorConfiguration(); 79 | JCommander.newBuilder() 80 | .addObject(config) 81 | .build() 82 | .parse(args); 83 | 84 | ShadowingCoordinator coo = new ShadowingCoordinator(config, SignatureSourceHelper.signatureSourceFromArgs(config.signatureSource, args)); 85 | coo.setup(); 86 | coo.start(); 87 | } 88 | 89 | /** 90 | * Configures this `ShadowingCoordinator` instance and validates parameters 91 | * 92 | * @throws IOException if reading milestones CSV fails 93 | */ 94 | private void setup() throws IOException { 95 | if (config.oldRoot != null) { 96 | throw new NotImplementedException("oldRoot"); 97 | } 98 | 99 | if (config.milestonesCSV == null) { 100 | throw new IllegalArgumentException("Need a milestone csv"); 101 | } 102 | 103 | this.oldMilestones = Files.readAllLines(Paths.get(config.milestonesCSV)).stream().map((String s) -> { 104 | String[] chunks = s.split(","); 105 | long idx = Long.parseLong(chunks[0]); 106 | String tail = chunks[1]; 107 | 108 | return new OldMilestone(idx, tail); 109 | }) 110 | .filter(m -> m.milestoneIdx >= config.oldMinIndex && m.milestoneIdx <= config.oldMaxIndex) 111 | .sorted(Comparator.comparingLong(o -> o.milestoneIdx)) 112 | .collect(Collectors.toList()); 113 | 114 | log.info("Loaded {} old milestones", oldMilestones.size()); 115 | log.info("Old milestone indices (min, max): [{}, {}]", oldMilestones.get(0).milestoneIdx, oldMilestones.get(oldMilestones.size() - 1).milestoneIdx); 116 | } 117 | 118 | private void broadcast(List transactions) throws ArgumentException { 119 | log.info("Collected {} transactions for broadcast.", transactions.size()); 120 | 121 | if (config.broadcast) { 122 | api.storeAndBroadcast(transactions.stream().map(Transaction::toTrytes).toArray(String[]::new)); 123 | log.info("Broadcasted {} transactions.", transactions.size()); 124 | } else { 125 | log.info("Skipping broadcast."); 126 | } 127 | 128 | transactions.clear(); 129 | } 130 | 131 | 132 | private void start() throws Exception { 133 | String trunk = config.initialTrunk; 134 | String branch; 135 | 136 | int newMilestoneIdx = config.index; 137 | log.info("Starting milestone index: {}", newMilestoneIdx); 138 | 139 | List transactions = new ArrayList<>(); 140 | 141 | for (OldMilestone oldMilestone : oldMilestones) { 142 | branch = oldMilestone.tail; 143 | 144 | List txs = db.createMilestone(trunk, branch, newMilestoneIdx, config.MWM); 145 | transactions.addAll(txs); 146 | log.info("Created milestone {}({}) referencing {} and {}", newMilestoneIdx, Hasher.hashTrytes(db.getPoWMode(), 147 | txs.get(0).toTrytes()), trunk, branch); 148 | 149 | /* 150 | * If the current list of transactions exceeds the broadcast threshold, 151 | * broadcast all available transactions. 152 | * Before continuing the milestone generation, ensures that node has become solid on the new milestones. 153 | */ 154 | if (transactions.size() >= config.broadcastBatch) { 155 | broadcast(transactions); 156 | 157 | GetNodeInfoResponse nodeInfo; 158 | int count = 0; 159 | while (true) { 160 | nodeInfo = api.getNodeInfo(); 161 | Thread.sleep(200); 162 | count++; 163 | 164 | if (nodeInfo.getLatestSolidSubtangleMilestoneIndex() != newMilestoneIdx) { 165 | continue; 166 | } 167 | 168 | try { 169 | GetTransactionsToApproveResponse txToApprove = api.getTransactionsToApprove(config.depth); 170 | log.info("{} Trunk: {} Branch: {}", count, txToApprove.getBranchTransaction(), txToApprove.getTrunkTransaction()); 171 | if (txToApprove.getBranchTransaction() == null || txToApprove.getTrunkTransaction() == null) { 172 | throw new RuntimeException("Broke transactions to approve. Repeating check."); 173 | } 174 | 175 | break; 176 | } catch (Exception e) { 177 | log.error("Failed TX TO Approve at milestone: {}, {}", newMilestoneIdx, e.getMessage()); 178 | } 179 | } 180 | } 181 | 182 | 183 | newMilestoneIdx++; 184 | 185 | trunk = Hasher.hashTrytes(db.getPoWMode(), txs.get(0).toTrytes()); 186 | } 187 | 188 | broadcast(transactions); 189 | 190 | log.info("Shadowing complete."); 191 | } 192 | 193 | class OldMilestone { 194 | String tail; 195 | long milestoneIdx; 196 | 197 | public OldMilestone(long milestoneIdx, String tail) { 198 | this.tail = tail; 199 | this.milestoneIdx = milestoneIdx; 200 | } 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /compass/conf/BUILD: -------------------------------------------------------------------------------- 1 | java_library( 2 | name = "conf", 3 | srcs = glob(["*.java"]), 4 | visibility = ["//visibility:public"], 5 | deps = [ 6 | "//compass/milestone", 7 | "//compass/sign:common", 8 | "@com_beust_jcommander//jar", 9 | "@com_google_guava_guava//jar", 10 | "@junit_junit//jar", 11 | "@org_iota_jota//jar", 12 | ], 13 | ) 14 | -------------------------------------------------------------------------------- /compass/conf/BaseConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | import org.iota.jota.pow.SpongeFactory; 30 | import org.iota.compass.SignatureSourceType; 31 | 32 | import java.net.URL; 33 | 34 | public class BaseConfiguration { 35 | @Parameter(names = "-layers", description = "Path to folder containing Merkle Tree layers", required = true) 36 | public String layersPath; 37 | 38 | @Parameter(names = "-host", description = "URL for IRI host", required = true) 39 | public String host; 40 | 41 | @Parameter(names = "-mwm", description = "Minimum Weight Magnitude", required = true) 42 | public int MWM = 9; 43 | 44 | @Parameter(names = "-broadcast", description = "Should Coordinator really broadcast milestones?") 45 | public boolean broadcast = false; 46 | 47 | @Parameter(names = "-powMode", description = "Sponge mode to use for Proof of Work (one of CURLP81, KERL)", required = true, 48 | converter = SpongeModeConverter.class, validateValueWith = {POWModeValidator.class}) 49 | public SpongeFactory.Mode powMode = SpongeFactory.Mode.CURLP81; 50 | 51 | @Parameter(names = "-powHost", description = "Outsource CURLP81 PoW to an IRI host", required = false, converter = URLConverter.class) 52 | public URL powHost = null; 53 | 54 | @Parameter(names = "-signatureSource", description = "Signature source type (can be 'inmemory' or 'remote')", converter = SignatureSourceTypeConverter.class) 55 | public SignatureSourceType signatureSource = SignatureSourceType.INMEMORY; 56 | } 57 | -------------------------------------------------------------------------------- /compass/conf/CoordinatorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | 30 | import java.util.List; 31 | import java.util.ArrayList; 32 | 33 | public class CoordinatorConfiguration extends BaseConfiguration { 34 | @Parameter(names = "-bootstrap", description = "Bootstrap network") 35 | public boolean bootstrap = false; 36 | 37 | @Parameter(names = "-tick", description = "Milestone tick in milliseconds", required = true) 38 | public int tick = 15000; 39 | 40 | @Parameter(names = "-depth", description = "Starting depth") 41 | public int depth = 0; 42 | 43 | @Parameter(names = "-depthScale", description = "Time scale factor for depth decrease") 44 | public float depthScale = 1.01f; 45 | 46 | @Parameter(names = "-unsolidDelay", description = "Delay if node is not solid in milliseconds") 47 | public int unsolidDelay = 5000; 48 | 49 | @Parameter(names = "-inception", description = "Only use this if you know what you're doing.") 50 | public boolean inception = false; 51 | 52 | @Parameter(names = "-index", description = "Manually feed the current latest solid milestone index of IRI." + 53 | " So the next milestone will be index +1") 54 | public Integer index; 55 | 56 | @Parameter(names = "-validator", description = "Validator nodes to use") 57 | public List validators = new ArrayList<>(); 58 | 59 | @Parameter(names = "-validationAttempts", description = "If tips validation fails, obtain new tips and validate up to this number of attempts.") 60 | public int validationAttempts = 10; 61 | 62 | @Parameter(names = "-validationDelay", description = "Obtained tips might not be solid right away on the validators, sleep the specified amount of seconds before validating.") 63 | public int validationDelay = 5; 64 | 65 | @Parameter(names = "-propagationRetriesThreshold", description = "Number of milestone propagation retries we attempt before failing.") 66 | public int propagationRetriesThreshold = 5; 67 | 68 | @Parameter(names = "-allowDifferentCooAddress", description = "Don't fail on different Coordinator Addresses") 69 | public boolean allowDifferentCooAddress = false; 70 | 71 | @Parameter(names = "-statePath", description = "Path to compass state file.") 72 | public String statePath = "compass.state"; 73 | 74 | @Parameter(names = "-APIRetries", description = "Number of attempts to retry failing API call.") 75 | public int APIRetries = 5; 76 | 77 | @Parameter(names = "-APIRetryInterval", description = "Interval (in milliseconds) to wait between failing API attempts.") 78 | public int APIRetryInterval = 1000; 79 | 80 | @Parameter(names = "-referenceLastMilestone", description = "Generate a milestone that references the last and then exit") 81 | public boolean referenceLastMilestone = false; 82 | } 83 | -------------------------------------------------------------------------------- /compass/conf/CoordinatorState.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import java.io.Serializable; 29 | import java.util.Collections; 30 | import java.util.List; 31 | 32 | public class CoordinatorState implements Serializable { 33 | 34 | public int latestMilestoneIndex; 35 | public String latestMilestoneHash; 36 | public long latestMilestoneTime; 37 | public List latestMilestoneTransactions = Collections.EMPTY_LIST; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /compass/conf/InMemorySignatureSourceConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | import org.iota.jota.pow.SpongeFactory; 30 | 31 | public class InMemorySignatureSourceConfiguration { 32 | @Parameter(names = "-seed", description = "Seed", required = true) 33 | public String seed; 34 | 35 | @Parameter(names = "-sigMode", description = "Sponge mode to use for signature creation (one of CURLP27, CURLP81, KERL)", 36 | required = true, converter = SpongeModeConverter.class) 37 | public SpongeFactory.Mode sigMode = SpongeFactory.Mode.CURLP27; 38 | 39 | @Parameter(names = "-security", description = "Security level to use. Value must be in [1;3]") 40 | public Integer security = 1; 41 | } 42 | -------------------------------------------------------------------------------- /compass/conf/LayersCalculatorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | import org.iota.compass.SignatureSourceType; 30 | 31 | public class LayersCalculatorConfiguration { 32 | @Parameter(names = "-layers", description = "Path to folder where Merkle Tree layers will be written to", required = true) 33 | public String layersPath; 34 | 35 | @Parameter(names = "-depth", description = "Depth the resulting merkle tree", required = true) 36 | public int depth; 37 | 38 | @Parameter(names = "-signatureSource", description = "Signature source type (can be 'inmemory' or 'remote')", converter = SignatureSourceTypeConverter.class) 39 | public SignatureSourceType signatureSource = SignatureSourceType.INMEMORY; 40 | } 41 | -------------------------------------------------------------------------------- /compass/conf/POWModeValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.IValueValidator; 29 | import com.beust.jcommander.ParameterException; 30 | import org.iota.jota.pow.SpongeFactory; 31 | 32 | public class POWModeValidator implements IValueValidator { 33 | 34 | @Override 35 | public void validate(String s, SpongeFactory.Mode mode) throws ParameterException { 36 | if (mode != SpongeFactory.Mode.CURLP81 && mode != SpongeFactory.Mode.KERL) { 37 | throw new ParameterException("Invalid mode provided for PoW. Must be CURLP81 or KERL."); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /compass/conf/RemoteSignatureSourceConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | 30 | public class RemoteSignatureSourceConfiguration { 31 | @Parameter(names = "-remoteURI", description = "URI for remote signature source", required = true) 32 | public String uri; 33 | 34 | @Parameter(names = "-remotePlaintext", description = "Whether to communicate with signatureSource in plaintext") 35 | public boolean plaintext = false; 36 | 37 | @Parameter(names = "-remoteTrustCertCollection", description = "Path to trust cert collection for encrypted connection to remote signature source server") 38 | public String trustCertCollection = null; 39 | 40 | @Parameter(names = "-remoteClientCertChain", description = "Path to client certificate chain to use for authenticating to the remote signature source server") 41 | public String clientCertChain = null; 42 | 43 | @Parameter(names = "-remoteClientKey", description = "Path to private key to use for authenticating to the remote signature source server") 44 | public String clientKey = null; 45 | } 46 | -------------------------------------------------------------------------------- /compass/conf/ShadowingCoordinatorConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.conf; 27 | 28 | import com.beust.jcommander.Parameter; 29 | import org.iota.compass.MilestoneSource; 30 | 31 | public class ShadowingCoordinatorConfiguration extends BaseConfiguration { 32 | @Parameter(names = "-milestonesCSV", description = "csv (index, tail) of old milestones") 33 | public String milestonesCSV; 34 | 35 | @Parameter(names = "-oldRoot", description = "Old milestone address") 36 | public String oldRoot; 37 | 38 | @Parameter(names = "-oldMinIndex", description = "Minimum old milestone index (inclusive)") 39 | public long oldMinIndex = 0; 40 | 41 | @Parameter(names = "-oldMaxIndex", description = "Maximum old milestone index (inclusive)") 42 | public long oldMaxIndex = Long.MAX_VALUE; 43 | 44 | @Parameter(names = "-index", description = "Starting milestone index (inclusive)", required = true) 45 | public Integer index; 46 | 47 | @Parameter(names = "-broadcastBatch", description = "Rate at which broadcasts are batched") 48 | public int broadcastBatch = 666; 49 | 50 | @Parameter(names = "-initialTrunk", description = "Initial trunk that is referenced") 51 | public String initialTrunk = MilestoneSource.EMPTY_HASH; 52 | 53 | @Parameter(names = "-depth", description = "depth from which to start the random walk") 54 | public Integer depth = 3; 55 | } 56 | -------------------------------------------------------------------------------- /compass/conf/SignatureSourceServerConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.conf; 2 | 3 | import com.beust.jcommander.Parameter; 4 | 5 | public class SignatureSourceServerConfiguration extends InMemorySignatureSourceConfiguration { 6 | @Parameter(names = "-port", description = "Port to listen on.") 7 | public Integer port = 50051; 8 | 9 | @Parameter(names = "-plaintext", description = "Whether to communicate with signatureSource in plaintext") 10 | public boolean plaintext = false; 11 | 12 | @Parameter(names = "-trustCertCollection", description = "Path to trust cert collection") 13 | public String trustCertCollection = null; 14 | 15 | @Parameter(names = "-certChain", description = "Path to certificate chain") 16 | public String certChain = null; 17 | 18 | @Parameter(names = "-privateKey ", description = "Path to the server's certificate's private key") 19 | public String privateKey = null; 20 | } 21 | -------------------------------------------------------------------------------- /compass/conf/SignatureSourceTypeConverter.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.conf; 2 | 3 | import com.beust.jcommander.IStringConverter; 4 | import org.iota.compass.SignatureSourceType; 5 | 6 | public class SignatureSourceTypeConverter implements IStringConverter { 7 | @Override 8 | public SignatureSourceType convert(String s) { 9 | return SignatureSourceType.valueOf(s.toUpperCase()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /compass/conf/SpongeModeConverter.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.conf; 2 | 3 | import com.beust.jcommander.IStringConverter; 4 | import org.iota.jota.pow.SpongeFactory; 5 | 6 | public class SpongeModeConverter implements IStringConverter { 7 | @Override 8 | public SpongeFactory.Mode convert(String s) { 9 | return SpongeFactory.Mode.valueOf(s); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /compass/conf/URLConverter.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.conf; 2 | 3 | import com.beust.jcommander.IStringConverter; 4 | import com.beust.jcommander.ParameterException; 5 | 6 | import java.net.MalformedURLException; 7 | import java.net.URL; 8 | 9 | public class URLConverter implements IStringConverter { 10 | @Override 11 | public URL convert(String s) { 12 | try { 13 | return new URL(s); 14 | } catch (MalformedURLException e) { 15 | throw new ParameterException("Invalid URL provided as Remote PoW host."); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /compass/crypto/BUILD: -------------------------------------------------------------------------------- 1 | MAIN_BASE_PATH = "src/main/java/org/iota/compass/%s" 2 | 3 | java_library( 4 | name = "crypto", 5 | srcs = [ 6 | "Hasher.java", 7 | "ISS.java", 8 | "ISSInPlace.java", 9 | "KerlPoW.java", 10 | "RemoteCURLP81PoW.java", 11 | "IotaRemotePoW.java", 12 | ], 13 | visibility = ["//visibility:public"], 14 | deps = [ 15 | "@com_google_guava_guava//jar", 16 | "@org_bouncycastle_bcprov_jdk15on//jar", 17 | "@org_iota_jota//jar", 18 | "@org_slf4j_slf4j_api//jar", 19 | ], 20 | ) 21 | -------------------------------------------------------------------------------- /compass/crypto/Hasher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.crypto; 27 | 28 | import org.iota.jota.pow.ICurl; 29 | import org.iota.jota.pow.JCurl; 30 | import org.iota.jota.pow.SpongeFactory; 31 | import org.iota.jota.utils.Converter; 32 | 33 | /** 34 | * 35 | */ 36 | public class Hasher { 37 | /** 38 | * Hashes a provided Tryte string using the given method 39 | * 40 | * @param mode the sponge method to use 41 | * @param trytes 42 | * @return 81 tryte hash 43 | */ 44 | public static String hashTrytes(SpongeFactory.Mode mode, String trytes) { 45 | return Converter.trytes(hashTrytesToTrits(mode, trytes)); 46 | } 47 | 48 | public static int[] hashTrytesToTrits(SpongeFactory.Mode mode, String trytes) { 49 | int[] hash = new int[JCurl.HASH_LENGTH]; 50 | 51 | ICurl sponge = SpongeFactory.create(mode); 52 | sponge.absorb(Converter.trits(trytes)); 53 | sponge.squeeze(hash); 54 | 55 | return hash; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /compass/crypto/ISS.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.crypto; 27 | 28 | import org.iota.jota.pow.ICurl; 29 | import org.iota.jota.pow.JCurl; 30 | import org.iota.jota.pow.SpongeFactory; 31 | 32 | import java.util.Arrays; 33 | 34 | public class ISS { 35 | 36 | public static final int NUMBER_OF_FRAGMENT_CHUNKS = 27; 37 | public static final int FRAGMENT_LENGTH = JCurl.HASH_LENGTH * NUMBER_OF_FRAGMENT_CHUNKS; 38 | public static final int TRYTE_WIDTH = 3; 39 | private static final int NUMBER_OF_SECURITY_LEVELS = 3; 40 | public static final int NORMALIZED_FRAGMENT_LENGTH = JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS; 41 | private static final int MIN_TRIT_VALUE = -1, MAX_TRIT_VALUE = 1; 42 | private static final int MIN_TRYTE_VALUE = -13, MAX_TRYTE_VALUE = 13; 43 | 44 | public static int[] subseed(SpongeFactory.Mode mode, final int[] seed, long index) { 45 | 46 | if (index < 0) { 47 | throw new RuntimeException("Invalid subseed index: " + index); 48 | } 49 | 50 | final int[] subseedPreimage = Arrays.copyOf(seed, seed.length); 51 | 52 | while (index-- > 0) { 53 | 54 | for (int i = 0; i < subseedPreimage.length; i++) { 55 | 56 | if (++subseedPreimage[i] > MAX_TRIT_VALUE) { 57 | subseedPreimage[i] = MIN_TRIT_VALUE; 58 | } else { 59 | break; 60 | } 61 | } 62 | } 63 | 64 | final int[] subseed = new int[JCurl.HASH_LENGTH]; 65 | 66 | final ICurl hash = SpongeFactory.create(mode); 67 | hash.absorb(subseedPreimage, 0, subseedPreimage.length); 68 | hash.squeeze(subseed, 0, subseed.length); 69 | return subseed; 70 | } 71 | 72 | public static int[] key(SpongeFactory.Mode mode, final int[] subseed, final int numberOfFragments) { 73 | 74 | if (subseed.length != JCurl.HASH_LENGTH) { 75 | throw new RuntimeException("Invalid subseed length: " + subseed.length); 76 | } 77 | if (numberOfFragments <= 0) { 78 | throw new RuntimeException("Invalid number of key fragments: " + numberOfFragments); 79 | } 80 | 81 | final int[] key = new int[FRAGMENT_LENGTH * numberOfFragments]; 82 | 83 | final ICurl hash = SpongeFactory.create(mode); 84 | hash.absorb(subseed, 0, subseed.length); 85 | hash.squeeze(key, 0, key.length); 86 | return key; 87 | } 88 | 89 | public static int[] digests(SpongeFactory.Mode mode, final int[] key) { 90 | 91 | if (key.length == 0 || key.length % FRAGMENT_LENGTH != 0) { 92 | throw new RuntimeException("Invalid key length: " + key.length); 93 | } 94 | 95 | final int[] digests = new int[key.length / FRAGMENT_LENGTH * JCurl.HASH_LENGTH]; 96 | final ICurl hash = SpongeFactory.create(mode); 97 | 98 | for (int i = 0; i < key.length / FRAGMENT_LENGTH; i++) { 99 | 100 | final int[] buffer = Arrays.copyOfRange(key, i * FRAGMENT_LENGTH, (i + 1) * FRAGMENT_LENGTH); 101 | for (int j = 0; j < NUMBER_OF_FRAGMENT_CHUNKS; j++) { 102 | 103 | for (int k = MAX_TRYTE_VALUE - MIN_TRYTE_VALUE; k-- > 0; ) { 104 | hash.reset(); 105 | hash.absorb(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 106 | hash.squeeze(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 107 | } 108 | } 109 | hash.reset(); 110 | hash.absorb(buffer, 0, buffer.length); 111 | hash.squeeze(digests, i * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 112 | } 113 | 114 | return digests; 115 | } 116 | 117 | public static int[] address(SpongeFactory.Mode mode, final int[] digests) { 118 | 119 | if (digests.length == 0 || digests.length % JCurl.HASH_LENGTH != 0) { 120 | throw new RuntimeException("Invalid digests length: " + digests.length); 121 | } 122 | 123 | final int[] address = new int[JCurl.HASH_LENGTH]; 124 | 125 | final ICurl hash = SpongeFactory.create(mode); 126 | hash.absorb(digests, 0, digests.length); 127 | hash.squeeze(address, 0, address.length); 128 | 129 | return address; 130 | } 131 | 132 | public static int[] normalizedBundle(final int[] bundle) { 133 | 134 | if (bundle.length != JCurl.HASH_LENGTH) { 135 | throw new RuntimeException("Invalid bundleValidator length: " + bundle.length); 136 | } 137 | 138 | final int[] normalizedBundle = new int[JCurl.HASH_LENGTH / TRYTE_WIDTH]; 139 | 140 | for (int i = 0; i < NUMBER_OF_SECURITY_LEVELS; i++) { 141 | 142 | int sum = 0; 143 | for (int j = i * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j < (i + 1) * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j++) { 144 | 145 | normalizedBundle[j] = bundle[j * TRYTE_WIDTH] + bundle[j * TRYTE_WIDTH + 1] * 3 + bundle[j * TRYTE_WIDTH + 2] * 9; 146 | sum += normalizedBundle[j]; 147 | } 148 | if (sum > 0) { 149 | 150 | while (sum-- > 0) { 151 | 152 | for (int j = i * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j < (i + 1) * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j++) { 153 | 154 | if (normalizedBundle[j] > MIN_TRYTE_VALUE) { 155 | normalizedBundle[j]--; 156 | break; 157 | } 158 | } 159 | } 160 | 161 | } else { 162 | 163 | while (sum++ < 0) { 164 | 165 | for (int j = i * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j < (i + 1) * (JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS); j++) { 166 | 167 | if (normalizedBundle[j] < MAX_TRYTE_VALUE) { 168 | normalizedBundle[j]++; 169 | break; 170 | } 171 | } 172 | } 173 | } 174 | } 175 | 176 | return normalizedBundle; 177 | } 178 | 179 | public static int[] signatureFragment(SpongeFactory.Mode mode, final int[] normalizedBundleFragment, final int[] keyFragment) { 180 | 181 | if (normalizedBundleFragment.length != NORMALIZED_FRAGMENT_LENGTH) { 182 | throw new RuntimeException("Invalid normalized bundleValidator fragment length: " + normalizedBundleFragment.length); 183 | } 184 | if (keyFragment.length != FRAGMENT_LENGTH) { 185 | throw new RuntimeException("Invalid key fragment length: " + keyFragment.length); 186 | } 187 | 188 | final int[] signatureFragment = Arrays.copyOf(keyFragment, keyFragment.length); 189 | final ICurl hash = SpongeFactory.create(mode); 190 | 191 | for (int j = 0; j < NUMBER_OF_FRAGMENT_CHUNKS; j++) { 192 | 193 | for (int k = MAX_TRYTE_VALUE - normalizedBundleFragment[j]; k-- > 0; ) { 194 | hash.reset(); 195 | hash.absorb(signatureFragment, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 196 | hash.squeeze(signatureFragment, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 197 | } 198 | } 199 | 200 | return signatureFragment; 201 | } 202 | 203 | public static int[] digest(SpongeFactory.Mode mode, final int[] normalizedBundleFragment, final int[] signatureFragment) { 204 | 205 | if (normalizedBundleFragment.length != JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS) { 206 | throw new RuntimeException("Invalid normalized bundleValidator fragment length: " + normalizedBundleFragment.length); 207 | } 208 | if (signatureFragment.length != FRAGMENT_LENGTH) { 209 | throw new RuntimeException("Invalid signature fragment length: " + signatureFragment.length); 210 | } 211 | 212 | final int[] digest = new int[JCurl.HASH_LENGTH]; 213 | final int[] buffer = Arrays.copyOf(signatureFragment, FRAGMENT_LENGTH); 214 | final ICurl hash = SpongeFactory.create(mode); 215 | for (int j = 0; j < NUMBER_OF_FRAGMENT_CHUNKS; j++) { 216 | 217 | for (int k = normalizedBundleFragment[j] - MIN_TRYTE_VALUE; k-- > 0; ) { 218 | hash.reset(); 219 | hash.absorb(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 220 | hash.squeeze(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 221 | } 222 | } 223 | hash.reset(); 224 | hash.absorb(buffer, 0, buffer.length); 225 | hash.squeeze(digest, 0, digest.length); 226 | 227 | return digest; 228 | } 229 | 230 | public static int[] getMerkleRoot(SpongeFactory.Mode mode, final int[] inHash, int[] trits, int offset, final int indexIn, int size) { 231 | int index = indexIn; 232 | int[] hash = inHash.clone(); 233 | final ICurl curl = SpongeFactory.create(mode); 234 | for (int i = 0; i < size; i++) { 235 | curl.reset(); 236 | if ((index & 1) == 0) { 237 | curl.absorb(hash, 0, hash.length); 238 | curl.absorb(trits, offset + i * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 239 | } else { 240 | curl.absorb(trits, offset + i * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 241 | curl.absorb(hash, 0, hash.length); 242 | } 243 | curl.squeeze(hash, 0, hash.length); 244 | 245 | index >>= 1; 246 | } 247 | if (index != 0) { 248 | return new int[JCurl.HASH_LENGTH]; 249 | } 250 | return hash; 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /compass/crypto/ISSInPlace.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.crypto; 27 | 28 | import org.iota.jota.pow.ICurl; 29 | import org.iota.jota.pow.JCurl; 30 | import org.iota.jota.pow.SpongeFactory; 31 | 32 | import java.util.Arrays; 33 | 34 | /** 35 | * (c) 2016 Come-from-Beyond 36 | */ 37 | public class ISSInPlace { 38 | 39 | public static final int NUMBER_OF_FRAGMENT_CHUNKS = 27; 40 | public static final int FRAGMENT_LENGTH = JCurl.HASH_LENGTH * NUMBER_OF_FRAGMENT_CHUNKS; 41 | public static final int TRYTE_WIDTH = 3; 42 | private static final int NUMBER_OF_SECURITY_LEVELS = 3; 43 | public static final int NORMALIZED_FRAGMENT_LENGTH = JCurl.HASH_LENGTH / TRYTE_WIDTH / NUMBER_OF_SECURITY_LEVELS; 44 | private static final int MIN_TRIT_VALUE = -1, MAX_TRIT_VALUE = 1; 45 | private static final int MIN_TRYTE_VALUE = -13, MAX_TRYTE_VALUE = 13; 46 | 47 | public static void subseed(SpongeFactory.Mode mode, int[] subseed, long index) { 48 | 49 | if (index < 0) { 50 | throw new RuntimeException("Invalid subseed index: " + index); 51 | } 52 | 53 | if (subseed.length != JCurl.HASH_LENGTH) { 54 | throw new IllegalArgumentException("Subseed array is not of HASH_LENGTH"); 55 | } 56 | 57 | while (index-- > 0) { 58 | for (int i = 0; i < subseed.length; i++) { 59 | 60 | if (++subseed[i] > MAX_TRIT_VALUE) { 61 | subseed[i] = MIN_TRIT_VALUE; 62 | } else { 63 | break; 64 | } 65 | } 66 | } 67 | 68 | final ICurl hash = SpongeFactory.create(mode); 69 | hash.absorb(subseed, 0, subseed.length); 70 | hash.squeeze(subseed, 0, subseed.length); 71 | } 72 | 73 | public static void key(SpongeFactory.Mode mode, final int[] subseed, int[] key) { 74 | 75 | if (subseed.length != JCurl.HASH_LENGTH) { 76 | throw new RuntimeException("Invalid subseed length: " + subseed.length); 77 | } 78 | 79 | if ((key.length % FRAGMENT_LENGTH) != 0) { 80 | throw new IllegalArgumentException("key length must be multiple of fragment length"); 81 | } 82 | 83 | int numberOfFragments = key.length / FRAGMENT_LENGTH; 84 | 85 | if (numberOfFragments <= 0) { 86 | throw new RuntimeException("Invalid number of key fragments: " + numberOfFragments); 87 | } 88 | 89 | final ICurl hash = SpongeFactory.create(mode); 90 | hash.absorb(subseed, 0, subseed.length); 91 | hash.squeeze(key, 0, key.length); 92 | } 93 | 94 | public static void digests(SpongeFactory.Mode mode, final int[] key, int[] digests) { 95 | 96 | if (key.length == 0 || key.length % FRAGMENT_LENGTH != 0) { 97 | throw new RuntimeException("Invalid key length: " + key.length); 98 | } 99 | 100 | if (digests.length != (key.length / FRAGMENT_LENGTH * JCurl.HASH_LENGTH)) { 101 | throw new IllegalArgumentException("Invalid digests length"); 102 | } 103 | 104 | final ICurl hash = SpongeFactory.create(mode); 105 | 106 | for (int i = 0; i < key.length / FRAGMENT_LENGTH; i++) { 107 | 108 | final int[] buffer = Arrays.copyOfRange(key, i * FRAGMENT_LENGTH, (i + 1) * FRAGMENT_LENGTH); 109 | for (int j = 0; j < NUMBER_OF_FRAGMENT_CHUNKS; j++) { 110 | 111 | for (int k = MAX_TRYTE_VALUE - MIN_TRYTE_VALUE; k-- > 0; ) { 112 | hash.reset(); 113 | hash.absorb(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 114 | hash.squeeze(buffer, j * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 115 | } 116 | } 117 | hash.reset(); 118 | hash.absorb(buffer, 0, buffer.length); 119 | hash.squeeze(digests, i * JCurl.HASH_LENGTH, JCurl.HASH_LENGTH); 120 | } 121 | } 122 | 123 | public static void address(SpongeFactory.Mode mode, final int[] digests, int[] address) { 124 | 125 | if (digests.length == 0 || digests.length % JCurl.HASH_LENGTH != 0) { 126 | throw new RuntimeException("Invalid digests length: " + digests.length); 127 | } 128 | 129 | if (address.length != JCurl.HASH_LENGTH) { 130 | throw new IllegalArgumentException("Invalid address length"); 131 | } 132 | 133 | final ICurl hash = SpongeFactory.create(mode); 134 | hash.absorb(digests, 0, digests.length); 135 | hash.squeeze(address, 0, address.length); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /compass/crypto/IotaRemotePoW.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.crypto; 2 | 3 | import org.iota.jota.IotaPoW; 4 | 5 | public interface IotaRemotePoW extends IotaPoW { } 6 | -------------------------------------------------------------------------------- /compass/crypto/KerlPoW.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass.crypto; 27 | 28 | import org.iota.jota.pow.IotaLocalPoW; 29 | import org.iota.jota.pow.ICurl; 30 | import org.iota.jota.pow.SpongeFactory; 31 | import org.iota.jota.utils.Converter; 32 | import org.slf4j.Logger; 33 | import org.slf4j.LoggerFactory; 34 | 35 | import java.util.List; 36 | import java.util.concurrent.*; 37 | import java.util.concurrent.atomic.AtomicBoolean; 38 | import java.util.stream.Collectors; 39 | import java.util.stream.IntStream; 40 | 41 | /** 42 | * A simple man's naive and single-threaded implementation of Kerl-based Proof-of-Work 43 | */ 44 | public class KerlPoW implements IotaLocalPoW { 45 | private static final Logger log = LoggerFactory.getLogger("KerlPoW"); 46 | 47 | private final static int NONCE_START_TRIT = 7938; 48 | private final static int NONCE_LENGTH_TRIT = 81; 49 | private final static int NONCE_START_TRYTE = NONCE_START_TRIT / 3; 50 | public final static int NONCE_LENGTH_TRYTE = NONCE_LENGTH_TRIT / 3; 51 | 52 | private KerlPoWSettings settings; 53 | 54 | public KerlPoW() { 55 | this(new KerlPoWSettings()); 56 | } 57 | 58 | private KerlPoW(KerlPoWSettings settings) { 59 | this.settings = settings; 60 | if (settings.numberOfThreads <= 0) { 61 | int available = Runtime.getRuntime().availableProcessors(); 62 | settings.numberOfThreads = Math.max(1, Math.floorDiv(available * 8, 10)); 63 | } 64 | 65 | // TODO (th0br0): fix PoW offsetting so we can use multiple threads 66 | settings.numberOfThreads = 1; 67 | } 68 | 69 | @Override 70 | public String performPoW(String trytes, int minWeightMagnitude) { 71 | final ExecutorService executorService = Executors.newFixedThreadPool(settings.numberOfThreads); 72 | final AtomicBoolean resultFound = new AtomicBoolean(false); 73 | final List searchers = IntStream.range(0, settings.numberOfThreads) 74 | .mapToObj((idx) -> new Searcher(trytes, resultFound, minWeightMagnitude)) 75 | .collect(Collectors.toList()); 76 | final List> searcherFutures = searchers.stream() 77 | .map(executorService::submit) 78 | .collect(Collectors.toList()); 79 | 80 | executorService.shutdown(); 81 | try { 82 | executorService.awaitTermination(10, TimeUnit.MINUTES); 83 | 84 | for (Future f : searcherFutures) { 85 | if (f.isDone() && f.get() != null) { 86 | return trytes.substring(0, NONCE_START_TRYTE) + f.get(); 87 | } 88 | } 89 | } catch (ExecutionException | InterruptedException e) { 90 | log.error("failed to calculate PoW with MWM: {} , trytes: {}", trytes, minWeightMagnitude, e); 91 | return null; 92 | } 93 | 94 | return null; 95 | } 96 | 97 | private static class KerlPoWSettings { 98 | private int numberOfThreads = 1; 99 | } 100 | 101 | class Searcher implements Callable { 102 | 103 | private final AtomicBoolean resultFound; 104 | private final int targetZeros; 105 | 106 | private int[] trits; 107 | private int[] hashTrits = new int[243]; 108 | 109 | public Searcher(String inputTrytes, AtomicBoolean resultFound, int targetZeros) { 110 | this.resultFound = resultFound; 111 | this.trits = Converter.trits(inputTrytes); 112 | this.targetZeros = targetZeros; 113 | } 114 | 115 | private boolean shouldAbort() { 116 | return resultFound.get(); 117 | } 118 | 119 | private void increment(int[] trits, int offset, int size) { 120 | for (int i = offset; i < (offset + size) && ++trits[i] > 1; ++i) { 121 | trits[i] = -1; 122 | } 123 | } 124 | 125 | private int trailingZeros(int[] trits) { 126 | int count = 0; 127 | for (int i = trits.length - 1; i >= 0 && trits[i] == 0; i--) { 128 | count++; 129 | } 130 | 131 | return count; 132 | } 133 | 134 | private void search() { 135 | ICurl sponge = SpongeFactory.create(SpongeFactory.Mode.KERL); 136 | increment(trits, NONCE_START_TRIT, NONCE_LENGTH_TRIT); 137 | 138 | sponge.absorb(trits); 139 | sponge.squeeze(hashTrits); 140 | } 141 | 142 | @Override 143 | public String call() { 144 | String result = null; 145 | while (!shouldAbort()) { 146 | search(); 147 | 148 | if (trailingZeros(hashTrits) >= targetZeros) { 149 | result = Converter.trytes(trits, NONCE_START_TRIT, NONCE_LENGTH_TRIT); 150 | resultFound.set(true); 151 | break; 152 | } 153 | } 154 | 155 | return result; 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /compass/crypto/RemoteCURLP81PoW.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.crypto; 2 | 3 | import org.iota.jota.IotaAPI; 4 | import org.iota.jota.dto.response.GetAttachToTangleResponse; 5 | import org.iota.jota.error.ArgumentException; 6 | import org.iota.jota.model.Transaction; 7 | 8 | import java.net.URL; 9 | 10 | public class RemoteCURLP81PoW implements IotaRemotePoW { 11 | 12 | private final URL powHost; 13 | 14 | public RemoteCURLP81PoW(URL powHost) { 15 | this.powHost = powHost; 16 | } 17 | 18 | @Override 19 | public String performPoW(String trytes, int minWeightMagnitude) throws ArgumentException { 20 | // Build API object each time, preventing network changes between PoWs 21 | IotaAPI api = new IotaAPI.Builder() 22 | .protocol(powHost.getProtocol()) 23 | .host(powHost.getHost()) 24 | .port(powHost.getPort()) 25 | .build(); 26 | Transaction txSiblings = Transaction.asTransactionObject(trytes); 27 | GetAttachToTangleResponse res = api.attachToTangle( 28 | txSiblings.getTrunkTransaction(), 29 | txSiblings.getBranchTransaction(), 30 | minWeightMagnitude, 31 | trytes); 32 | // We sent only one big chunk of trytes 33 | return res.getTrytes()[0]; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /compass/exceptions/BUILD: -------------------------------------------------------------------------------- 1 | MAIN_BASE_PATH = "src/main/java/org/iota/compass/%s" 2 | 3 | java_library( 4 | name = "exceptions", 5 | srcs = glob([ 6 | "*.java", 7 | ]), 8 | visibility = ["//visibility:public"], 9 | ) 10 | -------------------------------------------------------------------------------- /compass/exceptions/TimeoutException.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass.exceptions; 2 | 3 | /** 4 | * Thrown if an API call to IRI is timed out 5 | */ 6 | public class TimeoutException extends Exception { 7 | 8 | public TimeoutException() { 9 | } 10 | 11 | public TimeoutException(String message) { 12 | super(message); 13 | } 14 | 15 | public TimeoutException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public TimeoutException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | public TimeoutException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(message, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /compass/milestone/BUILD: -------------------------------------------------------------------------------- 1 | MAIN_BASE_PATH = "src/main/java/org/iota/compass/%s" 2 | 3 | java_library( 4 | name = "milestone", 5 | srcs = [ 6 | "MilestoneDatabase.java", 7 | "MilestoneSource.java", 8 | ], 9 | visibility = ["//visibility:public"], 10 | deps = [ 11 | "//compass/crypto", 12 | "//compass/sign:common", 13 | "@com_google_guava_guava//jar", 14 | "@org_bouncycastle_bcprov_jdk15on//jar", 15 | "@org_iota_jota//jar", 16 | "@org_slf4j_slf4j_api//jar", 17 | ], 18 | ) 19 | 20 | java_test( 21 | name = "test_milestone", 22 | srcs = ["MilestoneTest.java"], 23 | flaky = True, 24 | test_class = "org.iota.compass.MilestoneTest", 25 | deps = [ 26 | ":milestone", 27 | "//compass:layers_calculator", 28 | "//compass/conf", 29 | "//compass/crypto", 30 | "//compass/sign:common", 31 | "//compass/sign:inmemory", 32 | "//compass/sign:remote", 33 | "//compass/sign:server", 34 | "//compass/test", 35 | "@com_google_guava_guava//jar", 36 | "@junit_junit//jar", 37 | "@org_iota_jota//jar", 38 | ], 39 | ) 40 | -------------------------------------------------------------------------------- /compass/milestone/MilestoneDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.google.common.base.Strings; 29 | import org.iota.jota.IotaPoW; 30 | import org.iota.jota.model.Bundle; 31 | import org.iota.jota.model.Transaction; 32 | import org.iota.jota.pow.ICurl; 33 | import org.iota.jota.pow.SpongeFactory; 34 | import org.iota.jota.pow.pearldiver.PearlDiverLocalPoW; 35 | import org.iota.jota.utils.Converter; 36 | import org.iota.compass.crypto.*; 37 | import org.slf4j.Logger; 38 | import org.slf4j.LoggerFactory; 39 | 40 | import java.io.BufferedReader; 41 | import java.io.FileReader; 42 | import java.io.IOException; 43 | import java.net.URL; 44 | import java.nio.file.Files; 45 | import java.nio.file.Path; 46 | import java.nio.file.Paths; 47 | import java.util.*; 48 | import java.util.stream.Collectors; 49 | import java.util.stream.IntStream; 50 | 51 | import static org.iota.jota.pow.JCurl.HASH_LENGTH; 52 | 53 | public class MilestoneDatabase extends MilestoneSource { 54 | 55 | private static final Logger log = LoggerFactory.getLogger(MilestoneDatabase.class); 56 | private static final int NONCE_OFFSET = 2673 /* tx length in trytes */ - 27 /* nonce length in trytes */; 57 | private static final int SIGNATURE_LENGTH = 27 * 81; 58 | private static final int OFFSET = (ISS.FRAGMENT_LENGTH / 3); 59 | private static final int LENGTH = (243 + 81 + 81 + 27 + 27 + 27) / 3; 60 | 61 | private final SpongeFactory.Mode powMode; 62 | private final URL powHost; 63 | private final SignatureSource signatureSource; 64 | private final String root; 65 | private final List> layers; 66 | 67 | 68 | public MilestoneDatabase(SpongeFactory.Mode powMode, URL powHost, SignatureSource signatureSource, String path) throws IOException { 69 | this(powMode, powHost, signatureSource, loadLayers(path)); 70 | } 71 | 72 | public MilestoneDatabase(SpongeFactory.Mode powMode, URL powHost, SignatureSource signatureSource, List> layers) { 73 | root = layers.get(0).get(0); 74 | this.layers = layers; 75 | this.signatureSource = signatureSource; 76 | this.powMode = powMode; 77 | this.powHost = powHost; 78 | } 79 | 80 | private static List readLines(Path p, int totalSize) throws IOException { 81 | BufferedReader br = new BufferedReader(new FileReader(p.toString())); 82 | List result = new ArrayList<>(totalSize); 83 | String line; 84 | do { 85 | line = br.readLine(); 86 | if (line != null) { 87 | result.add(line); 88 | } 89 | } while (line != null); 90 | 91 | return result; 92 | } 93 | 94 | private static List> loadLayers(String path) throws IOException { 95 | Map> result = new HashMap<>(); 96 | 97 | for (Path p : Files.newDirectoryStream(Paths.get(path))) { 98 | int idx = Integer.parseInt(p.toString().split("\\.")[1]); 99 | int totalSize = 1 << idx; 100 | try { 101 | result.put(idx, readLines(p, totalSize)); 102 | } catch (IOException e) { 103 | log.error("failed to load layers from: {}", path, e); 104 | } 105 | } 106 | 107 | return IntStream.range(0, result.size()) 108 | .mapToObj(result::get) 109 | .peek(list -> Objects.requireNonNull(list, "Found a missing layer. please check: " + path)) 110 | .collect(Collectors.toList()); 111 | } 112 | 113 | /** 114 | * Calculates a list of siblings 115 | * 116 | * @param leafIdx index of leaf 117 | * @param layers the Merkle tree in layers structure 118 | * @return a list of siblings 119 | */ 120 | private static List siblings(int leafIdx, List> layers) { 121 | List siblings = new ArrayList<>(layers.size()); 122 | 123 | int curLayer = layers.size() - 1; 124 | 125 | while (curLayer > 0) { 126 | List layer = layers.get(curLayer); 127 | if ((leafIdx & 1) == 1) { 128 | // odd 129 | siblings.add(layer.get(leafIdx - 1)); 130 | } else { 131 | siblings.add(layer.get(leafIdx + 1)); 132 | } 133 | 134 | leafIdx /= 2; 135 | curLayer--; 136 | } 137 | 138 | return siblings; 139 | } 140 | 141 | @Override 142 | public SpongeFactory.Mode getPoWMode() { 143 | return powMode; 144 | } 145 | 146 | @Override 147 | public String getRoot() { 148 | return root; 149 | } 150 | 151 | private IotaPoW getPoWProvider() { 152 | if (powMode == SpongeFactory.Mode.KERL) { 153 | return new KerlPoW(); 154 | } else { 155 | if (powHost != null) { 156 | return new RemoteCURLP81PoW(powHost); 157 | } else { 158 | return new PearlDiverLocalPoW(); 159 | } 160 | } 161 | } 162 | 163 | private String getTagForIndex(int index) { 164 | String tag; 165 | int[] trits = new int[15]; 166 | for (int i = 0; i < index; i++) { 167 | Converter.increment(trits, trits.length); 168 | } 169 | tag = Converter.trytes(trits); 170 | return Strings.padEnd(tag, 27, '9'); 171 | } 172 | 173 | @Override 174 | public List createMilestone(String trunk, String branch, int index, int mwm) { 175 | 176 | IotaPoW pow = getPoWProvider(); 177 | 178 | // Get the siblings in the current merkle tree 179 | List leafSiblings = siblings(index, layers); 180 | String siblingsTrytes = String.join("", leafSiblings); 181 | String paddedSiblingsTrytes = Strings.padEnd(siblingsTrytes, ISS.FRAGMENT_LENGTH / ISS.TRYTE_WIDTH, '9'); 182 | 183 | final String tag = getTagForIndex(index); 184 | 185 | // A milestone consists of two transactions. 186 | // The last transaction (currentIndex == lastIndex) contains the siblings for the merkle tree. 187 | Transaction txSiblings = new Transaction(); 188 | txSiblings.setSignatureFragments(paddedSiblingsTrytes); 189 | txSiblings.setAddress(root); 190 | txSiblings.setCurrentIndex(signatureSource.getSecurity()); 191 | txSiblings.setLastIndex(signatureSource.getSecurity()); 192 | txSiblings.setTimestamp(System.currentTimeMillis() / 1000); 193 | txSiblings.setObsoleteTag(tag); 194 | txSiblings.setValue(0); 195 | txSiblings.setBundle(EMPTY_HASH); 196 | txSiblings.setTrunkTransaction(trunk); 197 | txSiblings.setBranchTransaction(branch); 198 | txSiblings.setTag(tag); 199 | txSiblings.setNonce(EMPTY_TAG); 200 | 201 | // The other transactions contain a signature that signs the siblings and thereby ensures the integrity. 202 | List txs = 203 | IntStream.range(0, signatureSource.getSecurity()).mapToObj(i -> { 204 | Transaction tx = new Transaction(); 205 | tx.setSignatureFragments(Strings.repeat("9", 27 * 81)); 206 | tx.setAddress(root); 207 | tx.setCurrentIndex(i); 208 | tx.setLastIndex(signatureSource.getSecurity()); 209 | tx.setTimestamp(System.currentTimeMillis() / 1000); 210 | tx.setObsoleteTag(tag); 211 | tx.setValue(0); 212 | tx.setBundle(EMPTY_HASH); 213 | tx.setTrunkTransaction(EMPTY_HASH); 214 | tx.setBranchTransaction(trunk); 215 | tx.setTag(tag); 216 | tx.setNonce(EMPTY_TAG); 217 | return tx; 218 | }).collect(Collectors.toList()); 219 | 220 | txs.add(txSiblings); 221 | 222 | Transaction tPoW; 223 | String hashToSign; 224 | 225 | //calculate the bundle hash (same for Curl & Kerl) 226 | String bundleHash = calculateBundleHash(txs); 227 | txs.forEach(tx -> tx.setBundle(bundleHash)); 228 | 229 | txSiblings.setAttachmentTimestamp(System.currentTimeMillis()); 230 | tPoW = new Transaction(pow.performPoW(txSiblings.toTrytes(), mwm)); 231 | txSiblings.setAttachmentTimestamp(tPoW.getAttachmentTimestamp()); 232 | txSiblings.setAttachmentTimestampLowerBound(tPoW.getAttachmentTimestampLowerBound()); 233 | txSiblings.setAttachmentTimestampUpperBound(tPoW.getAttachmentTimestampUpperBound()); 234 | txSiblings.setNonce(tPoW.getNonce()); 235 | 236 | // We need to avoid the M bug we we are signing with KERL 237 | if (signatureSource.getSignatureMode() == SpongeFactory.Mode.KERL) { 238 | /* 239 | In the case that the signature is created using KERL, we need to ensure that there exists no 'M'(=13) in the 240 | normalized fragment that we're signing. 241 | */ 242 | boolean hashContainsM; 243 | int attempts = 0; 244 | do { 245 | int[] hashTrits = Hasher.hashTrytesToTrits(powMode, txSiblings.toTrytes()); 246 | int[] normHash = ISS.normalizedBundle(hashTrits); 247 | 248 | hashContainsM = Arrays.stream(normHash).limit(ISS.NUMBER_OF_FRAGMENT_CHUNKS * signatureSource.getSecurity()).anyMatch(elem -> elem == 13); 249 | if (hashContainsM) { 250 | txSiblings.setAttachmentTimestamp(System.currentTimeMillis()); 251 | tPoW = new Transaction(pow.performPoW(txSiblings.toTrytes(), mwm)); 252 | txSiblings.setAttachmentTimestamp(tPoW.getAttachmentTimestamp()); 253 | txSiblings.setAttachmentTimestampLowerBound(tPoW.getAttachmentTimestampLowerBound()); 254 | txSiblings.setAttachmentTimestampUpperBound(tPoW.getAttachmentTimestampUpperBound()); 255 | txSiblings.setNonce(tPoW.getNonce()); 256 | } 257 | attempts++; 258 | } while (hashContainsM); 259 | 260 | log.info("KERL milestone generation took {} attempts.", attempts); 261 | 262 | } 263 | 264 | hashToSign = Hasher.hashTrytes(powMode, txSiblings.toTrytes()); 265 | String signature = signatureSource.getSignature(index, hashToSign); 266 | txSiblings.setHash(hashToSign); 267 | 268 | validateSignature(root, index, hashToSign, signature, siblingsTrytes); 269 | 270 | chainTransactionsFillSignatures(mwm, txs, signature); 271 | 272 | return txs; 273 | } 274 | 275 | private void validateSignature(String root, int index, String hashToSign, String signature, String siblingsTrytes) { 276 | int[] rootTrits = Converter.trits(root); 277 | int[] signatureTrits = Converter.trits(signature); 278 | int[] siblingsTrits = Converter.trits(siblingsTrytes); 279 | SpongeFactory.Mode mode = signatureSource.getSignatureMode(); 280 | 281 | int[][] normalizedBundleFragments = new int[3][27]; 282 | 283 | 284 | { 285 | int[] normalizedBundleHash = new Bundle().normalizedBundle(hashToSign); 286 | 287 | // Split hash into 3 fragments 288 | for (int i = 0; i < 3; i++) { 289 | normalizedBundleFragments[i] = Arrays.copyOfRange(normalizedBundleHash, i * 27, (i + 1) * 27); 290 | } 291 | } 292 | 293 | // Get digests 294 | int[] digests = new int[signatureSource.getSecurity() * HASH_LENGTH]; 295 | for (int i = 0; i < signatureSource.getSecurity(); i++) { 296 | int[] digestBuffer = ISS.digest(mode, normalizedBundleFragments[i % 3], Arrays.copyOfRange(signatureTrits, i * ISS.FRAGMENT_LENGTH, (i + 1) * ISS.FRAGMENT_LENGTH)); 297 | System.arraycopy(digestBuffer, 0, digests, i * HASH_LENGTH, HASH_LENGTH); 298 | } 299 | int[] addressTrits = ISS.address(mode, digests); 300 | 301 | int[] calculatedRootTrits = ISS.getMerkleRoot(mode, addressTrits, siblingsTrits, 302 | 0, index, siblingsTrits.length / HASH_LENGTH); 303 | 304 | if (!Arrays.equals(rootTrits, calculatedRootTrits)) { 305 | String msg = "Calculated root does not match expected! Aborting. " + root + " :: " + Converter.trytes(calculatedRootTrits); 306 | log.error(msg); 307 | throw new RuntimeException(msg); 308 | } 309 | } 310 | 311 | private void chainTransactionsFillSignatures(int mwm, List txs, String signature) { 312 | //to chain transactions we start from the LastIndex and move towards index 0. 313 | Collections.reverse(txs); 314 | 315 | txs.stream().skip(1).forEach(tx -> { 316 | //copy signature fragment 317 | String sigFragment = signature.substring((int) (tx.getCurrentIndex() * SIGNATURE_LENGTH), 318 | (int) (tx.getCurrentIndex() + 1) * SIGNATURE_LENGTH); 319 | tx.setSignatureFragments(sigFragment); 320 | 321 | //chain bundle 322 | String prevHash = txs.get((int) (tx.getLastIndex() - tx.getCurrentIndex() - 1)).getHash(); 323 | tx.setTrunkTransaction(prevHash); 324 | 325 | //perform PoW 326 | Transaction tPoW = new Transaction(getPoWProvider().performPoW(tx.toTrytes(), mwm)); 327 | tx.setAttachmentTimestamp(tPoW.getAttachmentTimestamp()); 328 | tx.setAttachmentTimestampLowerBound(tPoW.getAttachmentTimestampLowerBound()); 329 | tx.setAttachmentTimestampUpperBound(tPoW.getAttachmentTimestampUpperBound()); 330 | tx.setNonce(tPoW.getNonce()); 331 | tx.setHash(Hasher.hashTrytes(powMode, tx.toTrytes())); 332 | }); 333 | 334 | Collections.reverse(txs); 335 | } 336 | 337 | private String calculateBundleHash(List txs) { 338 | 339 | ICurl sponge = SpongeFactory.create(SpongeFactory.Mode.KERL); 340 | 341 | for (Transaction tx : txs) { 342 | sponge.absorb(Converter.trits(tx.toTrytes().substring(OFFSET, OFFSET + LENGTH))); 343 | } 344 | 345 | int[] bundleHashTrits = new int[HASH_LENGTH]; 346 | sponge.squeeze(bundleHashTrits, 0, HASH_LENGTH); 347 | 348 | return Converter.trytes(bundleHashTrits, 0, HASH_LENGTH); 349 | } 350 | } 351 | -------------------------------------------------------------------------------- /compass/milestone/MilestoneSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.google.common.base.Strings; 29 | import org.iota.jota.model.Transaction; 30 | import org.iota.jota.pow.SpongeFactory; 31 | 32 | import java.util.List; 33 | 34 | public abstract class MilestoneSource { 35 | public final static String EMPTY_HASH = Strings.repeat("9", 81); 36 | public final static String EMPTY_TAG = Strings.repeat("9", 27); 37 | public final static String EMPTY_MSG = Strings.repeat("9", 27 * 81); 38 | 39 | /** 40 | * @return the merkle tree root backed by this `MilestoneSource` 41 | */ 42 | public abstract String getRoot(); 43 | 44 | /** 45 | * @return the sponge mode used by this `MilestoneSource` for performing proof of work 46 | */ 47 | public abstract SpongeFactory.Mode getPoWMode(); 48 | 49 | public abstract List createMilestone(String trunk, String branch, int index, int mwm); 50 | } 51 | -------------------------------------------------------------------------------- /compass/milestone/MilestoneTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import com.google.common.base.Strings; 29 | import org.iota.jota.model.Transaction; 30 | import org.iota.jota.pow.SpongeFactory; 31 | import org.iota.jota.utils.Converter; 32 | import org.iota.compass.conf.LayersCalculatorConfiguration; 33 | import org.iota.compass.conf.SignatureSourceServerConfiguration; 34 | import org.iota.compass.crypto.Hasher; 35 | import org.iota.compass.crypto.ISS; 36 | import org.junit.Assert; 37 | import org.junit.Test; 38 | import org.junit.runner.RunWith; 39 | import org.junit.runners.JUnit4; 40 | 41 | import java.io.IOException; 42 | import java.net.URL; 43 | import java.util.Arrays; 44 | import java.util.List; 45 | import java.util.Random; 46 | import java.util.stream.Collectors; 47 | 48 | import static org.iota.jota.pow.SpongeFactory.Mode.*; 49 | 50 | /** 51 | * Tests milestone generation & verifies the signatures 52 | */ 53 | @RunWith(JUnit4.class) 54 | public class MilestoneTest { 55 | 56 | private void runForMode(SpongeFactory.Mode powMode, URL powHost, SignatureSource signatureSource) { 57 | final int depth = 4; 58 | final int MWM = 4; 59 | 60 | final SpongeFactory.Mode sigMode = signatureSource.getSignatureMode(); 61 | 62 | final LayersCalculatorConfiguration layersConfig = new LayersCalculatorConfiguration(); 63 | layersConfig.depth = depth; 64 | final LayersCalculator layersCalculator = new LayersCalculator(layersConfig, signatureSource); 65 | 66 | final List addresses = layersCalculator.calculateAllAddresses(); 67 | final List> layers = layersCalculator.calculateAllLayers(addresses); 68 | final MilestoneDatabase db = new MilestoneDatabase(powMode, powHost, signatureSource, layers); 69 | 70 | for (int i = 0; i < (1 << depth); i++) { 71 | final List txs = db.createMilestone(TestUtil.nextSeed(), TestUtil.nextSeed(), i, MWM); 72 | 73 | final Transaction txFirst = txs.get(0); 74 | final Transaction txSiblings = txs.get(txs.size() - 1); 75 | 76 | txs.forEach(tx -> System.err.println(Hasher.hashTrytes(powMode, tx.toTrytes()))); 77 | 78 | txs.forEach(tx -> Assert.assertTrue("Transaction PoW MWM not met", 79 | tx.getHash().endsWith(Strings.repeat("9", MWM / 3)))); 80 | Assert.assertEquals(db.getRoot(), txFirst.getAddress()); 81 | final int[] trunkTrits = ISS.normalizedBundle(Converter.trits(Hasher.hashTrytes(powMode, txSiblings.toTrytes()))); 82 | 83 | // Get digest of each individual signature. 84 | int[] signatureTrits = Converter.trits( 85 | txs.stream() 86 | .limit(txs.size() - 1) 87 | .map(t -> Converter.trytes(ISS.digest(sigMode, 88 | Arrays.copyOfRange(trunkTrits, (int) t.getCurrentIndex() * ISS.NUMBER_OF_FRAGMENT_CHUNKS, 89 | (int) (t.getCurrentIndex() + 1) * ISS.NUMBER_OF_FRAGMENT_CHUNKS), 90 | Converter.trits(t.getSignatureFragments())))) 91 | .collect(Collectors.joining(""))); 92 | 93 | int[] signatureAddress = ISS.address(sigMode, signatureTrits); 94 | Assert.assertEquals(addresses.get(i), Converter.trytes(signatureAddress)); 95 | 96 | int[] siblingTrits = Converter.trits(txSiblings.getSignatureFragments()); 97 | int[] root = ISS.getMerkleRoot(sigMode, signatureAddress, siblingTrits, 0, i, depth); 98 | Assert.assertEquals(db.getRoot(), Converter.trytes(root)); 99 | } 100 | } 101 | 102 | @Test 103 | public void runRemoteTest() throws IOException { 104 | int port = new Random().nextInt(14436) + 51200; 105 | 106 | final String seed = TestUtil.nextSeed(); 107 | 108 | SignatureSourceServerConfiguration config = new SignatureSourceServerConfiguration(); 109 | config.port = port; 110 | config.security = 1; 111 | config.sigMode = SpongeFactory.Mode.CURLP27; 112 | config.plaintext = true; 113 | config.seed = seed; 114 | 115 | SignatureSourceServer server = new SignatureSourceServer(config); 116 | server.start(); 117 | 118 | SignatureSource source = new RemoteSignatureSource("localhost:" + port); 119 | 120 | runForMode(SpongeFactory.Mode.CURLP81, null, source); 121 | 122 | server.stop(); 123 | } 124 | 125 | @Test 126 | public void runTests() { 127 | int from = 1, to = 3; 128 | SpongeFactory.Mode[] powModes = new SpongeFactory.Mode[]{ 129 | // Jota's LocalPoWProvider only supports CURLP81 130 | // CURLP27, 131 | CURLP81, 132 | KERL 133 | }; 134 | 135 | SpongeFactory.Mode[] sigModes = new SpongeFactory.Mode[]{ 136 | KERL, 137 | CURLP27, 138 | CURLP81 139 | }; 140 | 141 | final String seed = TestUtil.nextSeed(); 142 | 143 | for (SpongeFactory.Mode powMode : powModes) { 144 | for (SpongeFactory.Mode sigMode : sigModes) { 145 | for (int security = from; security <= to; security++) { 146 | SignatureSource source = new InMemorySignatureSource(sigMode, seed, security); 147 | 148 | System.err.println("Running: " + powMode + " : " + sigMode + " : " + security); 149 | runForMode(powMode, null, source); 150 | } 151 | } 152 | } 153 | 154 | } 155 | 156 | 157 | } 158 | -------------------------------------------------------------------------------- /compass/sign/BUILD: -------------------------------------------------------------------------------- 1 | MAIN_BASE_PATH = "src/main/java/org/iota/compass/%s" 2 | 3 | java_library( 4 | name = "inmemory", 5 | srcs = ["InMemorySignatureSource.java"], 6 | visibility = ["//visibility:public"], 7 | deps = [ 8 | ":common", 9 | "//compass/crypto", 10 | "@org_iota_jota//jar", 11 | "@org_slf4j_slf4j_api//jar", 12 | ], 13 | ) 14 | 15 | java_library( 16 | name = "remote", 17 | srcs = ["RemoteSignatureSource.java"], 18 | visibility = ["//visibility:public"], 19 | deps = [ 20 | ":common", 21 | "//proto:signature_source_java_grpc", 22 | "//proto:signature_source_java_proto", 23 | "@com_google_api_grpc_proto_google_common_protos//jar", 24 | "@com_google_code_findbugs_jsr305//jar", 25 | "@com_google_guava_guava//jar", 26 | "@com_google_protobuf//:protobuf_java", 27 | "@com_google_protobuf//:protobuf_java_util", 28 | "@io_grpc_grpc_java//alts", 29 | "@io_grpc_grpc_java//core", 30 | "@io_grpc_grpc_java//netty", 31 | "@io_grpc_grpc_java//protobuf", 32 | "@io_grpc_grpc_java//stub", 33 | "@io_netty_netty_handler//jar", 34 | "@org_iota_jota//jar", 35 | "@org_slf4j_slf4j_api//jar", 36 | ], 37 | ) 38 | 39 | java_library( 40 | name = "common", 41 | srcs = [ 42 | "SignatureSource.java", 43 | "SignatureSourceType.java", 44 | ], 45 | visibility = ["//visibility:public"], 46 | deps = [ 47 | "@org_iota_jota//jar", 48 | ], 49 | ) 50 | 51 | java_library( 52 | name = "helper", 53 | srcs = [ 54 | "SignatureSourceHelper.java", 55 | ], 56 | visibility = ["//visibility:public"], 57 | deps = [ 58 | ":common", 59 | ":inmemory", 60 | ":remote", 61 | "//compass/conf", 62 | "@com_beust_jcommander//jar", 63 | ], 64 | ) 65 | 66 | java_binary( 67 | name = "server", 68 | srcs = ["SignatureSourceServer.java"], 69 | main_class = "org.iota.compass.SignatureSourceServer", 70 | visibility = ["//visibility:public"], 71 | runtime_deps = ["@org_slf4j_slf4j_simple//jar"], 72 | deps = [ 73 | ":common", 74 | ":inmemory", 75 | "//compass/conf", 76 | "//compass/crypto", 77 | "//proto:signature_source_java_grpc", 78 | "//proto:signature_source_java_proto", 79 | "@com_beust_jcommander//jar", 80 | "@com_google_api_grpc_proto_google_common_protos//jar", 81 | "@com_google_code_findbugs_jsr305//jar", 82 | "@com_google_guava_guava//jar", 83 | "@com_google_protobuf//:protobuf_java", 84 | "@com_google_protobuf//:protobuf_java_util", 85 | "@io_grpc_grpc_java//alts", 86 | "@io_grpc_grpc_java//core", 87 | "@io_grpc_grpc_java//netty", 88 | "@io_grpc_grpc_java//protobuf", 89 | "@io_grpc_grpc_java//stub", 90 | "@io_netty_netty_handler//jar", 91 | "@org_iota_jota//jar", 92 | "@org_slf4j_slf4j_api//jar", 93 | ], 94 | ) 95 | -------------------------------------------------------------------------------- /compass/sign/InMemorySignatureSource.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | 4 | import org.iota.jota.pow.JCurl; 5 | import org.iota.jota.pow.SpongeFactory; 6 | import org.iota.jota.utils.Converter; 7 | import org.iota.compass.crypto.ISS; 8 | import org.iota.compass.crypto.ISSInPlace; 9 | 10 | import java.util.Arrays; 11 | 12 | /** 13 | * A signature provider that holds the seed in local memory. 14 | */ 15 | public class InMemorySignatureSource extends SignatureSource { 16 | 17 | private final SpongeFactory.Mode mode; 18 | private final int[] seed; 19 | private final int security; 20 | 21 | public InMemorySignatureSource(SpongeFactory.Mode mode, String seed, int security) { 22 | this.mode = mode; 23 | this.seed = Converter.trits(seed); 24 | this.security = security; 25 | } 26 | 27 | @Override 28 | public int getSecurity() { 29 | return security; 30 | } 31 | 32 | @Override 33 | public SpongeFactory.Mode getSignatureMode() { 34 | return mode; 35 | } 36 | 37 | @Override 38 | public String getAddress(long index) { 39 | int[] subseed = new int[JCurl.HASH_LENGTH]; 40 | int[] key = new int[ISSInPlace.FRAGMENT_LENGTH * security]; 41 | int[] digests = new int[key.length / ISSInPlace.FRAGMENT_LENGTH * JCurl.HASH_LENGTH]; 42 | int[] address = new int[JCurl.HASH_LENGTH]; 43 | 44 | System.arraycopy(seed, 0, subseed, 0, subseed.length); 45 | ISSInPlace.subseed(mode, subseed, index); 46 | ISSInPlace.key(mode, subseed, key); 47 | Arrays.fill(subseed, 0); 48 | ISSInPlace.digests(mode, key, digests); 49 | Arrays.fill(key, 0); 50 | ISSInPlace.address(mode, digests, address); 51 | 52 | return Converter.trytes(address); 53 | } 54 | 55 | /** 56 | * @param index key / tree leaf index to generate signature for 57 | * @param hashToSign the hash to be signed 58 | * @return a valid signature for {@code hashToSign} using the {@code index} leaf 59 | */ 60 | @Override 61 | public String getSignature(long index, String hashToSign) { 62 | int[] subseed = ISS.subseed(mode, seed, index); 63 | int[] key = ISS.key(mode, subseed, security); 64 | Arrays.fill(subseed, 0); 65 | 66 | int[] normalizedBundle = ISS.normalizedBundle(Converter.trits(hashToSign)); 67 | 68 | StringBuilder fragment = new StringBuilder(); 69 | 70 | for (int i = 0; i < getSecurity(); i++) { 71 | int[] curFrag = ISS.signatureFragment(getSignatureMode(), 72 | Arrays.copyOfRange(normalizedBundle, i * ISS.NUMBER_OF_FRAGMENT_CHUNKS, (i + 1) * ISS.NUMBER_OF_FRAGMENT_CHUNKS), 73 | Arrays.copyOfRange(key, i * ISS.FRAGMENT_LENGTH, (i + 1) * ISS.FRAGMENT_LENGTH)); 74 | fragment.append(Converter.trytes(curFrag)); 75 | } 76 | 77 | Arrays.fill(key, 0); 78 | 79 | return fragment.toString(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /compass/sign/RemoteSignatureSource.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | import io.grpc.ManagedChannelBuilder; 4 | import io.grpc.StatusRuntimeException; 5 | import io.grpc.netty.GrpcSslContexts; 6 | import io.grpc.netty.NettyChannelBuilder; 7 | import io.netty.handler.ssl.SslContext; 8 | import io.netty.handler.ssl.SslContextBuilder; 9 | import org.iota.jota.pow.SpongeFactory; 10 | import org.iota.compass.proto.*; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import javax.net.ssl.SSLException; 15 | import java.io.File; 16 | import java.security.Security; 17 | import java.util.Optional; 18 | import java.util.concurrent.TimeUnit; 19 | 20 | /** 21 | * An implementation of a SignatureSource that talks to a remote gRPC service. 22 | */ 23 | public class RemoteSignatureSource extends SignatureSource { 24 | private static final Logger log = LoggerFactory.getLogger(RemoteSignatureSource.class); 25 | public static final String DEFAULT_CACHE_TTL = "5"; 26 | 27 | private SignatureSourceGrpc.SignatureSourceBlockingStub serviceStub; 28 | private final ManagedChannelBuilder channelBuilder; 29 | 30 | private Optional cachedSecurity = Optional.empty(); 31 | private Optional cachedSignatureMode = Optional.empty(); 32 | 33 | /** 34 | * Constructs a RemoteSignatureSource using an encrypted gRPC channel. 35 | * 36 | * @param uri the URI of the host to connect to 37 | * @param trustCertCollectionFilePath 38 | * @param clientCertChainFilePath 39 | * @param clientPrivateKeyFilePath 40 | * @throws SSLException 41 | */ 42 | public RemoteSignatureSource(String uri, 43 | String trustCertCollectionFilePath, 44 | String clientCertChainFilePath, 45 | String clientPrivateKeyFilePath) throws SSLException { 46 | 47 | this.channelBuilder = createSecureManagedChannelBuilder( 48 | uri, trustCertCollectionFilePath, clientCertChainFilePath, clientPrivateKeyFilePath 49 | ); 50 | this.serviceStub = SignatureSourceGrpc.newBlockingStub(channelBuilder.build()); 51 | 52 | } 53 | 54 | 55 | /** 56 | * Constructs a RemoteSignatureSource using an *unencrypted* gRPC channel. 57 | * 58 | * @param uri the URI of the host to connect to 59 | */ 60 | public RemoteSignatureSource(String uri) { 61 | this.channelBuilder = createPlaintextManagedChannelBuilder(uri); 62 | this.serviceStub = SignatureSourceGrpc.newBlockingStub(channelBuilder.build()); 63 | } 64 | 65 | private ManagedChannelBuilder createSecureManagedChannelBuilder(String uri, 66 | String trustCertCollectionFilePath, 67 | String clientCertChainFilePath, 68 | String clientPrivateKeyFilePath) throws SSLException { 69 | String cacheTtl = Security.getProperty("networkaddress.cache.ttl"); 70 | if (cacheTtl == null) { 71 | cacheTtl = DEFAULT_CACHE_TTL; 72 | } 73 | return NettyChannelBuilder 74 | .forTarget(uri) 75 | .idleTimeout(Integer.valueOf(cacheTtl) * 2, TimeUnit.SECONDS) 76 | .useTransportSecurity() 77 | .sslContext( 78 | buildSslContext(trustCertCollectionFilePath, clientCertChainFilePath, clientPrivateKeyFilePath) 79 | ); 80 | } 81 | 82 | private ManagedChannelBuilder createPlaintextManagedChannelBuilder(String uri) { 83 | String cacheTtl = Security.getProperty("networkaddress.cache.ttl"); 84 | if (cacheTtl == null) { 85 | cacheTtl = DEFAULT_CACHE_TTL; 86 | } 87 | return ManagedChannelBuilder 88 | .forTarget(uri) 89 | .idleTimeout(Integer.valueOf(cacheTtl) * 2, TimeUnit.SECONDS) 90 | .usePlaintext(); 91 | } 92 | 93 | private static SslContext buildSslContext( 94 | String trustCertCollectionFilePath, 95 | String clientCertChainFilePath, 96 | String clientPrivateKeyFilePath) throws SSLException { 97 | SslContextBuilder builder = GrpcSslContexts.forClient(); 98 | if (trustCertCollectionFilePath != null) { 99 | builder.trustManager(new File(trustCertCollectionFilePath)); 100 | } 101 | if (clientCertChainFilePath != null && !clientCertChainFilePath.isEmpty() 102 | && clientPrivateKeyFilePath != null && !clientPrivateKeyFilePath.isEmpty()) { 103 | builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath)); 104 | } 105 | return builder.build(); 106 | } 107 | 108 | @Override 109 | public String getSignature(long index, String hash) { 110 | log.trace("Requesting signature for index: " + index + " and hash: " + hash); 111 | GetSignatureResponse response; 112 | try { 113 | response = serviceStub.getSignature(GetSignatureRequest.newBuilder().setIndex(index).setHash(hash).build()); 114 | } catch (StatusRuntimeException e) { 115 | // If an exception occurs, wait 10 seconds, and retry only once by rebuilding the gRPC client stub from a new Channel 116 | try { 117 | Thread.sleep(10_000); 118 | } catch (InterruptedException ex) { 119 | // Ignore the fact that we got interrupted 120 | } 121 | serviceStub = SignatureSourceGrpc.newBlockingStub(channelBuilder.build()); 122 | response = serviceStub.getSignature(GetSignatureRequest.newBuilder().setIndex(index).setHash(hash).build()); 123 | } 124 | return response.getSignature(); 125 | } 126 | 127 | @Override 128 | public int getSecurity() { 129 | synchronized (cachedSecurity) { 130 | if (cachedSecurity.isPresent()) 131 | return cachedSecurity.get(); 132 | 133 | 134 | GetSecurityResponse response = serviceStub.getSecurity(GetSecurityRequest.getDefaultInstance()); 135 | cachedSecurity = Optional.of(response.getSecurity()); 136 | 137 | log.info("Caching security level: " + response.getSecurity()); 138 | 139 | return response.getSecurity(); 140 | } 141 | } 142 | 143 | @Override 144 | public SpongeFactory.Mode getSignatureMode() { 145 | synchronized (cachedSignatureMode) { 146 | if (cachedSignatureMode.isPresent()) return cachedSignatureMode.get(); 147 | 148 | GetSignatureModeResponse response = serviceStub.getSignatureMode(GetSignatureModeRequest.getDefaultInstance()); 149 | 150 | SpongeFactory.Mode spongeMode; 151 | switch (response.getMode()) { 152 | case CURLP27: 153 | spongeMode = SpongeFactory.Mode.CURLP27; 154 | break; 155 | case CURLP81: 156 | spongeMode = SpongeFactory.Mode.CURLP81; 157 | break; 158 | case KERL: 159 | spongeMode = SpongeFactory.Mode.KERL; 160 | break; 161 | default: 162 | throw new RuntimeException("Unknown remote signature mode: " + response.getMode()); 163 | } 164 | 165 | cachedSignatureMode = Optional.of(spongeMode); 166 | 167 | log.info("Caching signature mode: " + spongeMode); 168 | 169 | return spongeMode; 170 | } 171 | } 172 | 173 | @Override 174 | public String getAddress(long index) { 175 | GetAddressResponse response = serviceStub.getAddress(GetAddressRequest.newBuilder().setIndex(index).build()); 176 | return response.getAddress(); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /compass/sign/SignatureSource.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | import org.iota.jota.pow.SpongeFactory; 4 | 5 | public abstract class SignatureSource { 6 | /** 7 | * Provides the signature for the given milestone index. 8 | * 9 | * @param index the key / leaf index 10 | * @param bundleHash the hash to sign 11 | * @return trit-array containing the key 12 | */ 13 | public abstract String getSignature(long index, String bundleHash); 14 | 15 | /** 16 | * The security level of this key provider 17 | * 18 | * @return security level (1 to 3 inclusive) 19 | */ 20 | public abstract int getSecurity(); 21 | 22 | /** 23 | * @return the signature mode for this key 24 | */ 25 | public abstract SpongeFactory.Mode getSignatureMode(); 26 | 27 | 28 | /** 29 | * @param index the key / leaf index 30 | * @return the address for the given key / leaf index 31 | */ 32 | public abstract String getAddress(long index); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /compass/sign/SignatureSourceHelper.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | import com.beust.jcommander.JCommander; 4 | import org.iota.compass.conf.InMemorySignatureSourceConfiguration; 5 | import org.iota.compass.conf.RemoteSignatureSourceConfiguration; 6 | 7 | import javax.net.ssl.SSLException; 8 | 9 | public class SignatureSourceHelper { 10 | public static SignatureSource signatureSourceFromArgs(SignatureSourceType type, String[] args) throws SSLException { 11 | switch (type) { 12 | case REMOTE: { 13 | RemoteSignatureSourceConfiguration sourceConf = new RemoteSignatureSourceConfiguration(); 14 | JCommander.newBuilder().addObject(sourceConf).acceptUnknownOptions(true).build().parse(args); 15 | 16 | if (sourceConf.plaintext) { 17 | return new RemoteSignatureSource(sourceConf.uri); 18 | } else { 19 | return new RemoteSignatureSource(sourceConf.uri, sourceConf.trustCertCollection, sourceConf.clientCertChain, sourceConf.clientKey); 20 | } 21 | } 22 | case INMEMORY: { 23 | InMemorySignatureSourceConfiguration sourceConf = new InMemorySignatureSourceConfiguration(); 24 | JCommander.newBuilder().addObject(sourceConf).acceptUnknownOptions(true).build().parse(args); 25 | 26 | return new InMemorySignatureSource(sourceConf.sigMode, sourceConf.seed, sourceConf.security); 27 | } 28 | } 29 | 30 | throw new IllegalArgumentException(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /compass/sign/SignatureSourceServer.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | import com.beust.jcommander.JCommander; 4 | import io.grpc.Server; 5 | import io.grpc.netty.GrpcSslContexts; 6 | import io.grpc.netty.NettyServerBuilder; 7 | import io.grpc.stub.StreamObserver; 8 | import io.netty.handler.ssl.ClientAuth; 9 | import io.netty.handler.ssl.SslContextBuilder; 10 | import io.netty.handler.ssl.SslProvider; 11 | import org.iota.compass.conf.SignatureSourceServerConfiguration; 12 | import org.iota.compass.proto.*; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | 19 | public class SignatureSourceServer { 20 | private static final Logger log = LoggerFactory.getLogger(SignatureSourceServer.class); 21 | 22 | private final SignatureSourceServerConfiguration config; 23 | private final SignatureSource signatureSource; 24 | 25 | private Server server; 26 | 27 | public SignatureSourceServer(SignatureSourceServerConfiguration config) { 28 | this.config = config; 29 | this.signatureSource = new InMemorySignatureSource(config.sigMode, config.seed, config.security); 30 | } 31 | 32 | public static void main(String[] args) throws IOException, InterruptedException { 33 | SignatureSourceServerConfiguration config = new SignatureSourceServerConfiguration(); 34 | 35 | JCommander.newBuilder() 36 | .addObject(config) 37 | .build() 38 | .parse(args); 39 | 40 | final SignatureSourceServer server = new SignatureSourceServer(config); 41 | server.start(); 42 | server.blockUntilShutdown(); 43 | } 44 | 45 | public void start() throws IOException { 46 | NettyServerBuilder builder = 47 | NettyServerBuilder.forPort(config.port) 48 | .addService(new SignatureSourceImpl(signatureSource)); 49 | 50 | if (!config.plaintext) { 51 | if (config.certChain == null || config.certChain.isEmpty()) { 52 | throw new IllegalArgumentException("-certChain is required if not running in plaintext mode"); 53 | } 54 | 55 | if (config.privateKey == null || config.privateKey.isEmpty()) { 56 | throw new IllegalArgumentException("-privateKey is required if not running in plaintext mode"); 57 | } 58 | 59 | SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(config.certChain), 60 | new File(config.privateKey)); 61 | if (config.trustCertCollection != null) { 62 | sslClientContextBuilder.trustManager(new File(config.trustCertCollection)); 63 | sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE); 64 | } 65 | 66 | builder = builder.sslContext(GrpcSslContexts.configure(sslClientContextBuilder, 67 | SslProvider.OPENSSL).build()); 68 | } 69 | 70 | server = builder.build(); 71 | server.start(); 72 | 73 | log.info("Server started, listening on " + config.port); 74 | 75 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 76 | System.err.println("*** shutting down gRPC server since JVM is shutting down"); 77 | SignatureSourceServer.this.stop(); 78 | System.err.println("*** server shut down"); 79 | })); 80 | } 81 | 82 | public void stop() { 83 | if (server != null) { 84 | server.shutdown(); 85 | } 86 | } 87 | 88 | public void blockUntilShutdown() throws InterruptedException { 89 | if (server != null) { 90 | server.awaitTermination(); 91 | } 92 | } 93 | 94 | 95 | static class SignatureSourceImpl extends SignatureSourceGrpc.SignatureSourceImplBase { 96 | private final SignatureSource signatureSource; 97 | 98 | public SignatureSourceImpl(SignatureSource signatureSource) { 99 | super(); 100 | this.signatureSource = signatureSource; 101 | } 102 | 103 | @Override 104 | public void getSecurity(GetSecurityRequest request, StreamObserver responseObserver) { 105 | log.info("Responding to getSecurity"); 106 | responseObserver.onNext(GetSecurityResponse.newBuilder() 107 | .setSecurity(signatureSource.getSecurity()) 108 | .build()); 109 | responseObserver.onCompleted(); 110 | } 111 | 112 | @Override 113 | public void getSignatureMode(GetSignatureModeRequest request, StreamObserver responseObserver) { 114 | log.info("Responding to getSignatureMode"); 115 | SignatureMode mode; 116 | 117 | switch (signatureSource.getSignatureMode()) { 118 | case CURLP27: 119 | mode = SignatureMode.CURLP27; 120 | break; 121 | case CURLP81: 122 | mode = SignatureMode.CURLP81; 123 | break; 124 | case KERL: 125 | mode = SignatureMode.KERL; 126 | break; 127 | default: 128 | throw new RuntimeException(); 129 | } 130 | 131 | responseObserver.onNext(GetSignatureModeResponse.newBuilder() 132 | .setMode(mode) 133 | .build()); 134 | responseObserver.onCompleted(); 135 | } 136 | 137 | @Override 138 | public void getSignature(GetSignatureRequest request, StreamObserver responseObserver) { 139 | log.info("Responding to getSignature for index: " + request.getIndex() + " and hash: " + request.getHash()); 140 | 141 | responseObserver.onNext(GetSignatureResponse.newBuilder() 142 | .setSignature(signatureSource.getSignature(request.getIndex(), request.getHash())) 143 | .build()); 144 | responseObserver.onCompleted(); 145 | } 146 | 147 | @Override 148 | public void getAddress(GetAddressRequest request, StreamObserver responseObserver) { 149 | log.info("Responding to getAddress for index: " + request.getIndex()); 150 | 151 | responseObserver.onNext(GetAddressResponse.newBuilder() 152 | .setAddress(signatureSource.getAddress(request.getIndex())) 153 | .build()); 154 | responseObserver.onCompleted(); 155 | } 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /compass/sign/SignatureSourceType.java: -------------------------------------------------------------------------------- 1 | package org.iota.compass; 2 | 3 | public enum SignatureSourceType { 4 | INMEMORY, REMOTE 5 | } 6 | -------------------------------------------------------------------------------- /compass/simplelogger.properties: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of TestnetCOO. 3 | # 4 | # Copyright (C) 2018 IOTA Stiftung 5 | # TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | # 7 | # TestnetCOO is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Affero General Public License as published 9 | # by the Free Software Foundation, either version 3 of the License, 10 | # or (at your option) any later version. 11 | # 12 | # TestnetCOO is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Affero General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Affero General Public License 18 | # along with TestnetCOO. If not, see: 19 | # http://www.gnu.org/licenses/ 20 | # 21 | # For more information contact: 22 | # IOTA Stiftung 23 | # https://www.iota.org/ 24 | # 25 | 26 | org.slf4j.simpleLogger.defaultLogLevel=info 27 | #org.slf4j.simpleLogger.log.xxxxx= 28 | 29 | org.slf4j.simpleLogger.showDateTime=true 30 | org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z 31 | 32 | org.slf4j.simpleLogger.showThreadName=true 33 | org.slf4j.simpleLogger.showLogName=true 34 | -------------------------------------------------------------------------------- /compass/test/BUILD: -------------------------------------------------------------------------------- 1 | java_library( 2 | name = "test", 3 | srcs = ["TestUtil.java"], 4 | visibility = ["//visibility:public"], 5 | ) 6 | -------------------------------------------------------------------------------- /compass/test/TestUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TestnetCOO. 3 | * 4 | * Copyright (C) 2018 IOTA Stiftung 5 | * TestnetCOO is Copyright (C) 2017-2018 IOTA Stiftung 6 | * 7 | * TestnetCOO is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Affero General Public License as published 9 | * by the Free Software Foundation, either version 3 of the License, 10 | * or (at your option) any later version. 11 | * 12 | * TestnetCOO is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Affero General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Affero General Public License 18 | * along with TestnetCOO. If not, see: 19 | * http://www.gnu.org/licenses/ 20 | * 21 | * For more information contact: 22 | * IOTA Stiftung 23 | * https://www.iota.org/ 24 | */ 25 | 26 | package org.iota.compass; 27 | 28 | import java.security.SecureRandom; 29 | import java.util.Random; 30 | 31 | public class TestUtil { 32 | 33 | private static final String ALPHABET = "9ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 34 | private static final int randomnessSeed = 1; 35 | private static final Random random = new SecureRandom(); 36 | 37 | { 38 | //for deterministic testing 39 | random.setSeed(randomnessSeed); 40 | } 41 | 42 | static String nextSeed() { 43 | return nextTrytes(81); 44 | } 45 | 46 | private static String nextTrytes(int count) { 47 | char[] buf = new char[count]; 48 | 49 | for (int idx = 0; idx < buf.length; ++idx) 50 | buf[idx] = ALPHABET.charAt(random.nextInt(ALPHABET.length())); 51 | 52 | return new String(buf); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /docker/BUILD: -------------------------------------------------------------------------------- 1 | load("@io_bazel_rules_docker//container:container.bzl", "container_image") 2 | 3 | container_image( 4 | name = "layers_calculator", 5 | base = "@java_base//image", 6 | cmd = ["layers_calculator_deploy.jar"], 7 | files = ["//compass:layers_calculator_deploy.jar"], 8 | repository = "iota/compass", 9 | ) 10 | 11 | container_image( 12 | name = "coordinator", 13 | base = "@java_base//image", 14 | cmd = ["coordinator_deploy.jar"], 15 | files = ["//compass:coordinator_deploy.jar"], 16 | repository = "iota/compass", 17 | ) 18 | 19 | container_image( 20 | name = "shadowing_coordinator", 21 | base = "@java_base//image", 22 | cmd = ["shadowing_coordinator_deploy.jar"], 23 | files = ["//compass:shadowing_coordinator_deploy.jar"], 24 | repository = "iota/compass", 25 | ) 26 | 27 | container_image( 28 | name = "signature_source_server", 29 | base = "@java_base//image", 30 | cmd = ["server_deploy.jar"], 31 | files = ["//compass/sign:server_deploy.jar"], 32 | repository = "iota/compass", 33 | ) 34 | -------------------------------------------------------------------------------- /docs/HOWTO_private_tangle.md: -------------------------------------------------------------------------------- 1 | # HOWTO: Setting up a private Tangle 2 | 3 | ## Introduction 4 | A private Tangle consists in a set of IRI nodes interconnected between each other. We also recommended you create Private Tangles with their own genesis (a custom snapshot file). This will clearly differentiate your Private Tangle from any other existing network, whether public or private. 5 | 6 | A private Tangle can consist of a single IRI instance. The instructions below will guide you through creating your own single node private Tangle. 7 | 8 | ### The components 9 | - IRI — IOTA Reference Implementation — software 10 | - A custom snapshot file — genesis 11 | - The Coordinator (COO) 12 | - The scripts in `docs/private_tangle` 13 | 14 | ## Important things to note 15 | The instructions below do not consider all individual circumstances of your setup. They are meant to give you an understanding on how to bootstrap your own Private Tangle on a 1 node network topology. More complex setups can be achieved by running more IRI nodes interconnected between each other. 16 | 17 | If you prefer to use Docker to set up IRI instances, we provide [IRI docker containers](https://hub.docker.com/r/iotaledger/iri/). We recommend adapting the instructions below by following the [IRI Docker instructions](https://github.com/iotaledger/iri/blob/dev/DOCKER.md). 18 | 19 | ## Step 1: Setting up the Coordinator 20 | The Coordinator uses Java to run. These instructions assume that you have already setup [bazel](https://bazel.build) on 21 | your system and installed the `//docker:coordinator` and `//docker:layers_calculator` images. The relevant scripts are inside the `private_tangle` folder. 22 | **The scripts assume that they are in the same folder as the `config.json` file and data folders.** 23 | 24 | ### Bootstrapping the Coordinator 25 | We now need to bootstrap the Coordinator milestone merkle tree. 26 | 1. Generate a valid random seed. 27 | The seed is going to be used by the COO to generate and sign milestones. **Do not lose the generated seed.** 28 | 29 | ``` 30 | cat /dev/urandom |LC_ALL=C tr -dc 'A-Z9' | fold -w 81 | head -n 1  31 | ``` 32 | 33 | The output of the command above will be a random string of 81 chars, all capital letters, such as this: 34 | `COOSEED99999999999999999999999999999999999999999999999999999999999999999999999999`. 35 | 36 | 2. Decide on the depth of the Coordinator. 37 | 38 | The higher the number, the more milestones can be issued: At depth 18, = ~260 thousand milestones, 39 | 20 = ~1 million milestones, 21 = ~2 million milestones – or more precisely 2^DEPTH. 40 | 41 | For this exercise, we use depth 8 — allowing 256 milestones to be issued. 42 | 43 | **Keep in mind this process is highly CPU intensive. For example, generating a depth 20 tree on a 64 CPU server takes about 1 hour.** 44 | 3. Copy the `config.example.json` file to `config.json` and alter its contents (specifying correct depth & seed). 45 | 4. Run the layer calculator via `./01_calculate_layers.sh` from the `private_tangle` folder. 46 | 5. After completing execution, the LayersCalculator will tell you the root of the generated merkle tree. *This is the Coordinator's address*. 47 | 48 | ## Step 2: Running the IRI node 49 | IRI is an open source, Java reference implementation of the IOTA protocol. The development of IRI is supported by the IOTA Foundation. 50 | 51 | Dedicate a Linux server as an IRI node. The server requirements are low, we recommend the following for a better experience: 52 | 53 | - VPS or bare metal 54 | - 4 CPUs (or virtual CPUs) 55 | - 8GB RAM 56 | - SSD drive with at least 10GB – highly dependent on how much data you wish to store 57 | - Virtually any Linux distribution, as long as Docker is available. We recommend Ubuntu Linux and this guide assumes it’s Ubuntu Linux. 58 | 59 | The script assumes that the DB will be stored in the same path as the script. 60 | 61 | If you look inside the script, here's some of those parameters explaned: 62 | 63 | - `--testnet-coordinator $COO_ADDRESS` - the Coordinator address that IRI listens on 64 | - `--mwm` (e.g. `9`) - sets the minimum weight magnitude (MWM) required by a client when performing proof-of-work (PoW). Keep in mind that an MWM of 9 requires a negligible amount of PoW. For comparison, the IOTA Mainnet Network uses `MWM = 14`. 65 | - `--max-depth` (e.g. `1000`) - only required on the node where the COO will be issuing milestones. If you are creating more than one IRI node, this is not necessary. 66 | - `--milestone-start` (e.g. `1`) - the lowest milestone index that IRI uses 67 | - `--milestone-keys` - see the description of `depth` further above 68 | - `--snapshot` - the file containing the private tangle's current snapshot information 69 | 70 | ### Create custom genesis 71 | Create a custom genesis `snapshot.txt` file and place it in the same folder as the script. 72 | 73 | Here's an **example** one: 74 | ```yaml 75 | FJHSSHBZTAKQNDTIKJYCZBOZDGSZANCZSWCNWUOCZXFADNOQSYAHEJPXRLOVPNOQFQXXGEGVDGICLMOXX;2779530283277761 76 | ``` 77 | This allocates all token supply to seed `SEED99999999999999999999999999999999999999999999999999999999999999999999999999999` 78 | 79 | ### Start IRI 80 | ``` 81 | ./02_run_iri.sh 82 | ``` 83 | 84 | ### IRI node explained 85 | IRI by default uses three ports. If you need to access these ports remotely, please make sure the firewall on your server is setup accordingly. The ports are: 86 | 87 | - UDP neighbor peering port (default is `14600`) 88 | - TCP neighbor peering port (default is `15600`) 89 | - TCP HTTP API port (default is `14265`) 90 | 91 | #### Checking the Node Status 92 | Using curl and jq you can test the TCP API port. 93 | 94 | ``` 95 | apt-get install -y curl jq 96 | curl -s http://localhost:14265 -X POST -H 'X-IOTA-API-Version: 1' -H 'Content-Type: application/json' -d '{"command": "getNodeInfo"}' | jq 97 | ``` 98 | 99 | Please refer to https://iota.readme.io/reference for all HTTP IRI API commands available.  100 | 101 | ## Step 3: Running the Coordinator 102 | The IRI node is now running but it has not received its first milestone. We need to bootstrap the Tangle.  103 | We suggest at this stage to have two terminals open on your server. One with journalctl or equivalent looking at its logs and one running the following commands: 104 | 105 | ``` 106 | ./03_run_coordinator.sh -bootstrap -broadcast 107 | ``` 108 | 109 | Let this command run until you see output similar to: 110 | ``` 111 | 07/20 09:10:43.699 [Latest Milestone Tracker] INFO  com.iota.iri.Milestone - Latest milestone has changed from #2 to #3 112 | 07/20 09:10:45.385 [Solid Milestone Tracker] INFO  com.iota.iri.Milestone - Latest SOLID SUBTANGLE milestone has changed from #2 to #3 113 | ``` 114 | 115 | For future runs, you no longer need to provide the `-bootstrap` parameter (the Coordinator actually won't start with it). 116 | The `-broadcast` flag, however, is required as a security measure that the Coordinator should actually broadcast its milestones to IRI. 117 | 118 | A new milestone will be issued by the COO every 60 seconds (set by `"tick": 60000` in the `config.json`). 119 | 120 | You now have a working Private Tangle. 121 | -------------------------------------------------------------------------------- /docs/private_tangle/.gitignore: -------------------------------------------------------------------------------- 1 | config.json 2 | snapshot.txt 3 | data/ 4 | db/ 5 | .*.swp 6 | -------------------------------------------------------------------------------- /docs/private_tangle/01_calculate_layers.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | docker run -t --rm -v $scriptdir/data:/data iota/compass/docker:layers_calculator layers_calculator_deploy.jar -sigMode $sigMode -seed $seed -depth $depth -security $security -layers /data/layers 9 | -------------------------------------------------------------------------------- /docs/private_tangle/02_run_iri.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | COO_ADDRESS=$(cat $scriptdir/data/layers/layer.0.csv) 9 | 10 | docker pull iotaledger/iri:latest 11 | docker run -t --net host --rm -v $scriptdir/db:/iri/data -v $scriptdir/snapshot.txt:/snapshot.txt -p 14265 iotaledger/iri:latest \ 12 | --testnet true \ 13 | --remote true \ 14 | --testnet-coordinator $COO_ADDRESS \ 15 | --testnet-coordinator-security-level $security \ 16 | --testnet-coordinator-signature-mode $sigMode \ 17 | --mwm $mwm \ 18 | --milestone-start $milestoneStart \ 19 | --milestone-keys $depth \ 20 | --snapshot /snapshot.txt \ 21 | --max-depth 1000 $@ 22 | 23 | -------------------------------------------------------------------------------- /docs/private_tangle/03_run_coordinator.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | docker run -t --net host --rm -v $scriptdir/data:/data iota/compass/docker:coordinator coordinator_deploy.jar \ 9 | -layers /data/layers \ 10 | -statePath /data/compass.state \ 11 | -sigMode $sigMode \ 12 | -powMode $powMode \ 13 | -mwm $mwm \ 14 | -security $security \ 15 | -seed $seed \ 16 | -tick $tick \ 17 | -host $host \ 18 | "$@" 19 | -------------------------------------------------------------------------------- /docs/private_tangle/11_run_signature_source_server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | docker run -t --net host --rm -v $scriptdir/data:/data iota/compass/docker:signature_source_server server_deploy.jar \ 9 | -sigMode $sigMode \ 10 | -security $security \ 11 | -seed $seed \ 12 | -plaintext \ 13 | -port 50051 \ 14 | "$@" 15 | -------------------------------------------------------------------------------- /docs/private_tangle/12_run_coordinator_remote.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | docker run -t --net host --rm -v $scriptdir/data:/data iota/compass/docker:coordinator coordinator_deploy.jar \ 9 | -layers /data/layers \ 10 | -statePath /data/compass.state \ 11 | -powMode $powMode \ 12 | -mwm $mwm \ 13 | -tick $tick \ 14 | -host $host \ 15 | -signatureSource remote \ 16 | -remoteURI localhost:50051 \ 17 | -remotePlaintext \ 18 | "$@" 19 | -------------------------------------------------------------------------------- /docs/private_tangle/21_calculate_layers_remote.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scriptdir=$(dirname "$(readlink -f "$0")") 4 | . $scriptdir/lib.sh 5 | 6 | load_config 7 | 8 | docker run -t --net host --rm -v $scriptdir/data:/data iota/compass/docker:layers_calculator layers_calculator_deploy.jar -depth $depth -layers /data/layers \ 9 | -signatureSource remote \ 10 | -remoteURI localhost:50051 \ 11 | -remotePlaintext \ 12 | 13 | -------------------------------------------------------------------------------- /docs/private_tangle/config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "seed": "MYSEEDHEREPLEASEREPLACEMEIMMEDIATELYWITHSOMETHINGSECURE99999999999999999999999999", 3 | "powMode": "CURLP81", 4 | "sigMode": "CURLP27", 5 | "security": 1, 6 | "depth": 8, 7 | "milestoneStart": 0, 8 | "mwm": 9, 9 | "tick": 60000, 10 | "host": "http://localhost:14265" 11 | } 12 | -------------------------------------------------------------------------------- /docs/private_tangle/lib.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function load_config { 4 | if [ ! -f $scriptdir/config.json ]; then 5 | echo "Config file 'config.json' does not exist! Please look at config.example.json and create one!" 6 | exit 1 7 | fi 8 | 9 | if [ ! -d $scriptdir/data/ ]; then 10 | mkdir $scriptdir/data/ 11 | echo "Depending on OS you might have to set SELinux permissions for data/" 12 | fi 13 | 14 | if [ ! -d $scriptdir/db/ ]; then 15 | mkdir $scriptdir/db/ 16 | echo "Depending on OS you might have to set SELinux permissions for db/" 17 | fi 18 | 19 | mkdir $scriptdir/data &> /dev/null 20 | mkdir $scriptdir/db &> /dev/null 21 | 22 | host=$(jq -r .host $scriptdir/config.json) 23 | sigMode=$(jq -r .sigMode $scriptdir/config.json) 24 | powMode=$(jq -r .powMode $scriptdir/config.json) 25 | seed=$(jq -r .seed $scriptdir/config.json) 26 | security=$(jq .security $scriptdir/config.json) 27 | depth=$(jq .depth $scriptdir/config.json) 28 | tick=$(jq .tick $scriptdir/config.json) 29 | mwm=$(jq .mwm $scriptdir/config.json) 30 | milestoneStart=$(jq .milestoneStart $scriptdir/config.json) 31 | } 32 | -------------------------------------------------------------------------------- /docs/private_tangle/snapshot.example.txt: -------------------------------------------------------------------------------- 1 | FJHSSHBZTAKQNDTIKJYCZBOZDGSZANCZSWCNWUOCZXFADNOQSYAHEJPXRLOVPNOQFQXXGEGVDGICLMOXX;2779530283277761 2 | -------------------------------------------------------------------------------- /proto/BUILD: -------------------------------------------------------------------------------- 1 | load("@io_grpc_grpc_java//:java_grpc_library.bzl", "java_grpc_library") 2 | 3 | java_proto_library( 4 | name = "signature_source_java_proto", 5 | visibility = ["//visibility:public"], 6 | deps = [":signature_source_proto"], 7 | ) 8 | 9 | java_grpc_library( 10 | name = "signature_source_java_grpc", 11 | srcs = [":signature_source_proto"], 12 | visibility = ["//visibility:public"], 13 | deps = [":signature_source_java_proto"], 14 | ) 15 | 16 | proto_library( 17 | name = "signature_source_proto", 18 | srcs = ["signature_source.proto"], 19 | visibility = ["//visibility:public"], 20 | ) 21 | -------------------------------------------------------------------------------- /proto/signature_source.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option java_multiple_files = true; 4 | option java_package = "org.iota.compass.proto"; 5 | option java_outer_classname = "SignatureSourceProto"; 6 | 7 | package org.iota.compass.proto; 8 | 9 | enum SignatureMode { 10 | CURLP27 = 0; 11 | CURLP81 = 1; 12 | KERL = 2; 13 | } 14 | 15 | message GetSignatureRequest { 16 | uint64 index = 1; 17 | string hash = 2; 18 | } 19 | 20 | message GetSignatureResponse { 21 | string signature = 1; 22 | } 23 | 24 | message GetSecurityRequest { 25 | } 26 | message GetSecurityResponse { 27 | uint32 security = 1; 28 | } 29 | 30 | message GetSignatureModeRequest { 31 | } 32 | 33 | message GetSignatureModeResponse { 34 | SignatureMode mode = 1; 35 | } 36 | 37 | message GetAddressRequest { 38 | uint64 index = 1; 39 | } 40 | message GetAddressResponse { 41 | string address = 1; 42 | } 43 | 44 | service SignatureSource { 45 | rpc GetSecurity (GetSecurityRequest) returns (GetSecurityResponse); 46 | rpc GetSignatureMode (GetSignatureModeRequest) returns (GetSignatureModeResponse); 47 | rpc GetSignature (GetSignatureRequest) returns (GetSignatureResponse); 48 | // Note that implementation of this method is optional. 49 | rpc GetAddress (GetAddressRequest) returns (GetAddressResponse); 50 | } 51 | -------------------------------------------------------------------------------- /third-party/BUILD: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iotaledger-archive/compass/d01fbc401efa1cc4de23c83352ec9c1130d6049e/third-party/BUILD -------------------------------------------------------------------------------- /third-party/maven_deps.bzl: -------------------------------------------------------------------------------- 1 | def maven_jars(): 2 | # com.google.guava:guava:bundle:26.0-jre 3 | native.maven_jar( 4 | name = "com_google_code_findbugs_jsr305", 5 | artifact = "com.google.code.findbugs:jsr305:3.0.2", 6 | repository = "https://jcenter.bintray.com/", 7 | sha1 = "25ea2e8b0c338a877313bd4672d3fe056ea78f0d", 8 | ) 9 | 10 | # com.google.guava:guava:bundle:26.0-jre 11 | native.maven_jar( 12 | name = "org_codehaus_mojo_animal_sniffer_annotations", 13 | artifact = "org.codehaus.mojo:animal-sniffer-annotations:1.14", 14 | repository = "https://jcenter.bintray.com/", 15 | sha1 = "775b7e22fb10026eed3f86e8dc556dfafe35f2d5", 16 | ) 17 | 18 | # org.slf4j:slf4j-simple:jar:1.7.25 19 | native.maven_jar( 20 | name = "org_slf4j_slf4j_api", 21 | artifact = "org.slf4j:slf4j-api:1.7.25", 22 | repository = "https://jcenter.bintray.com/", 23 | sha1 = "da76ca59f6a57ee3102f8f9bd9cee742973efa8a", 24 | ) 25 | 26 | # junit:junit:jar:4.12 27 | native.maven_jar( 28 | name = "org_hamcrest_hamcrest_core", 29 | artifact = "org.hamcrest:hamcrest-core:1.3", 30 | repository = "https://jcenter.bintray.com/", 31 | sha1 = "42a25dc3219429f0e5d060061f71acb49bf010a0", 32 | ) 33 | 34 | native.maven_jar( 35 | name = "com_squareup_retrofit2_converter_gson", 36 | artifact = "com.squareup.retrofit2:converter-gson:2.4.0", 37 | repository = "https://jcenter.bintray.com/", 38 | sha1 = "15d7790ee311d961379c51b00aba12d5967cb7ea", 39 | ) 40 | 41 | # com.squareup.retrofit2:converter-gson:jar:2.4.0 42 | native.maven_jar( 43 | name = "com_google_code_gson_gson", 44 | artifact = "com.google.code.gson:gson:2.8.2", 45 | repository = "https://jcenter.bintray.com/", 46 | sha1 = "3edcfe49d2c6053a70a2a47e4e1c2f94998a49cf", 47 | ) 48 | 49 | native.maven_jar( 50 | name = "com_squareup_retrofit2_retrofit", 51 | artifact = "com.squareup.retrofit2:retrofit:2.4.0", 52 | repository = "https://jcenter.bintray.com/", 53 | sha1 = "fc4aa382632bfaa7be7b41579efba41d5a71ecf3", 54 | ) 55 | 56 | # com.google.guava:guava:bundle:26.0-jre 57 | native.maven_jar( 58 | name = "org_checkerframework_checker_qual", 59 | artifact = "org.checkerframework:checker-qual:2.5.2", 60 | repository = "https://jcenter.bintray.com/", 61 | sha1 = "cea74543d5904a30861a61b4643a5f2bb372efc4", 62 | ) 63 | 64 | # com.squareup.retrofit2:retrofit:jar:2.4.0 65 | native.maven_jar( 66 | name = "com_squareup_okhttp3_okhttp", 67 | artifact = "com.squareup.okhttp3:okhttp:3.10.0", 68 | repository = "https://jcenter.bintray.com/", 69 | sha1 = "7ef0f1d95bf4c0b3ba30bbae25e0e562b05cf75e", 70 | ) 71 | 72 | # com.google.guava:guava:bundle:26.0-jre 73 | native.maven_jar( 74 | name = "com_google_errorprone_error_prone_annotations", 75 | artifact = "com.google.errorprone:error_prone_annotations:2.1.3", 76 | repository = "https://jcenter.bintray.com/", 77 | sha1 = "39b109f2cd352b2d71b52a3b5a1a9850e1dc304b", 78 | ) 79 | 80 | native.maven_jar( 81 | name = "org_apache_commons_commons_lang3", 82 | artifact = "org.apache.commons:commons-lang3:3.8.1", 83 | repository = "https://jcenter.bintray.com/", 84 | sha1 = "6505a72a097d9270f7a9e7bf42c4238283247755", 85 | ) 86 | 87 | # com.squareup.okhttp3:okhttp:jar:3.10.0 88 | native.maven_jar( 89 | name = "com_squareup_okio_okio", 90 | artifact = "com.squareup.okio:okio:1.14.0", 91 | repository = "https://jcenter.bintray.com/", 92 | sha1 = "102d7be47241d781ef95f1581d414b0943053130", 93 | ) 94 | 95 | native.maven_jar( 96 | name = "com_google_guava_guava", 97 | artifact = "com.google.guava:guava:26.0-jre", 98 | repository = "https://jcenter.bintray.com/", 99 | sha1 = "6a806eff209f36f635f943e16d97491f00f6bfab", 100 | ) 101 | 102 | native.maven_jar( 103 | name = "org_bouncycastle_bcprov_jdk15on", 104 | artifact = "org.bouncycastle:bcprov-jdk15on:1.60", 105 | repository = "https://jcenter.bintray.com/", 106 | sha1 = "bd47ad3bd14b8e82595c7adaa143501e60842a84", 107 | ) 108 | 109 | native.maven_jar( 110 | name = "com_beust_jcommander", 111 | artifact = "com.beust:jcommander:1.72", 112 | repository = "https://jcenter.bintray.com/", 113 | sha1 = "6375e521c1e11d6563d4f25a07ce124ccf8cd171", 114 | ) 115 | 116 | native.maven_jar( 117 | name = "org_slf4j_slf4j_simple", 118 | artifact = "org.slf4j:slf4j-simple:1.7.25", 119 | repository = "https://jcenter.bintray.com/", 120 | sha1 = "8dacf9514f0c707cbbcdd6fd699e8940d42fb54e", 121 | ) 122 | 123 | native.maven_jar( 124 | name = "junit_junit", 125 | artifact = "junit:junit:4.12", 126 | repository = "https://jcenter.bintray.com/", 127 | sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec", 128 | ) 129 | 130 | # com.google.guava:guava:bundle:26.0-jre 131 | native.maven_jar( 132 | name = "com_google_j2objc_j2objc_annotations", 133 | artifact = "com.google.j2objc:j2objc-annotations:1.1", 134 | repository = "https://jcenter.bintray.com/", 135 | sha1 = "ed28ded51a8b1c6b112568def5f4b455e6809019", 136 | ) 137 | 138 | # org.iota:jota:1.0.0-beta6 139 | native.maven_jar( 140 | name = "org_iota_jota", 141 | artifact = "org.iota:jota:1.0.0-beta6", 142 | repository = "https://jcenter.bintray.com/", 143 | sha1 = "5a4141395af7b307f4a5cd89e87988ccce974fd0", 144 | ) 145 | 146 | def maven_libraries(): 147 | native.java_library( 148 | name = "com_google_code_findbugs_jsr305", 149 | visibility = ["//visibility:public"], 150 | exports = ["@com_google_code_findbugs_jsr305//jar"], 151 | ) 152 | 153 | native.java_library( 154 | name = "org_codehaus_mojo_animal_sniffer_annotations", 155 | visibility = ["//visibility:public"], 156 | exports = ["@org_codehaus_mojo_animal_sniffer_annotations//jar"], 157 | ) 158 | 159 | native.java_library( 160 | name = "org_slf4j_slf4j_api", 161 | visibility = ["//visibility:public"], 162 | exports = ["@org_slf4j_slf4j_api//jar"], 163 | ) 164 | 165 | native.java_library( 166 | name = "org_hamcrest_hamcrest_core", 167 | visibility = ["//visibility:public"], 168 | exports = ["@org_hamcrest_hamcrest_core//jar"], 169 | ) 170 | 171 | native.java_library( 172 | name = "com_squareup_retrofit2_converter_gson", 173 | visibility = ["//visibility:public"], 174 | exports = ["@com_squareup_retrofit2_converter_gson//jar"], 175 | runtime_deps = [ 176 | ":com_google_code_gson_gson", 177 | ":com_squareup_retrofit2_retrofit", 178 | ], 179 | ) 180 | 181 | native.java_library( 182 | name = "com_google_code_gson_gson", 183 | visibility = ["//visibility:public"], 184 | exports = ["@com_google_code_gson_gson//jar"], 185 | ) 186 | 187 | native.java_library( 188 | name = "com_squareup_retrofit2_retrofit", 189 | visibility = ["//visibility:public"], 190 | exports = ["@com_squareup_retrofit2_retrofit//jar"], 191 | runtime_deps = [ 192 | ":com_squareup_okhttp3_okhttp", 193 | ":com_squareup_okio_okio", 194 | ], 195 | ) 196 | 197 | native.java_library( 198 | name = "org_checkerframework_checker_qual", 199 | visibility = ["//visibility:public"], 200 | exports = ["@org_checkerframework_checker_qual//jar"], 201 | ) 202 | 203 | native.java_library( 204 | name = "com_squareup_okhttp3_okhttp", 205 | visibility = ["//visibility:public"], 206 | exports = ["@com_squareup_okhttp3_okhttp//jar"], 207 | runtime_deps = [ 208 | ":com_squareup_okio_okio", 209 | ], 210 | ) 211 | 212 | native.java_library( 213 | name = "com_google_errorprone_error_prone_annotations", 214 | visibility = ["//visibility:public"], 215 | exports = ["@com_google_errorprone_error_prone_annotations//jar"], 216 | ) 217 | 218 | native.java_library( 219 | name = "org_apache_commons_commons_lang3", 220 | visibility = ["//visibility:public"], 221 | exports = ["@org_apache_commons_commons_lang3//jar"], 222 | ) 223 | 224 | native.java_library( 225 | name = "com_squareup_okio_okio", 226 | visibility = ["//visibility:public"], 227 | exports = ["@com_squareup_okio_okio//jar"], 228 | ) 229 | 230 | native.java_library( 231 | name = "com_google_guava_guava", 232 | visibility = ["//visibility:public"], 233 | exports = ["@com_google_guava_guava//jar"], 234 | runtime_deps = [ 235 | ":com_google_code_findbugs_jsr305", 236 | ":com_google_errorprone_error_prone_annotations", 237 | ":com_google_j2objc_j2objc_annotations", 238 | ":org_checkerframework_checker_qual", 239 | ":org_codehaus_mojo_animal_sniffer_annotations", 240 | ], 241 | ) 242 | 243 | native.java_library( 244 | name = "org_bouncycastle_bcprov_jdk15on", 245 | visibility = ["//visibility:public"], 246 | exports = ["@org_bouncycastle_bcprov_jdk15on//jar"], 247 | ) 248 | 249 | native.java_library( 250 | name = "com_beust_jcommander", 251 | visibility = ["//visibility:public"], 252 | exports = ["@com_beust_jcommander//jar"], 253 | ) 254 | 255 | native.java_library( 256 | name = "org_slf4j_slf4j_simple", 257 | visibility = ["//visibility:public"], 258 | exports = ["@org_slf4j_slf4j_simple//jar"], 259 | runtime_deps = [ 260 | ":org_slf4j_slf4j_api", 261 | ], 262 | ) 263 | 264 | native.java_library( 265 | name = "junit_junit", 266 | visibility = ["//visibility:public"], 267 | exports = ["@junit_junit//jar"], 268 | runtime_deps = [ 269 | ":org_hamcrest_hamcrest_core", 270 | ], 271 | ) 272 | 273 | native.java_library( 274 | name = "com_google_j2objc_j2objc_annotations", 275 | visibility = ["//visibility:public"], 276 | exports = ["@com_google_j2objc_j2objc_annotations//jar"], 277 | ) 278 | 279 | native.java_library( 280 | name = "org_iota_jota", 281 | visibility = ["//visibility:public"], 282 | exports = ["@org_iota_jota//jar"], 283 | ) 284 | --------------------------------------------------------------------------------