├── .bazelrc ├── .ci ├── coverity_scan.sh └── setup.sh ├── .clang-format ├── .github └── workflows │ └── github_actions.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── BUILD ├── CONTRIBUTING.md ├── Doxyfile ├── LICENSE ├── Makefile ├── README.md ├── WORKSPACE ├── accelerator ├── BUILD ├── cli_info.h ├── config.c ├── config.h ├── core │ ├── BUILD │ ├── apis.c │ ├── apis.h │ ├── core.c │ ├── core.h │ ├── mam_core.c │ ├── mam_core.h │ ├── periodical_task.c │ ├── periodical_task.h │ ├── pow.c │ ├── pow.h │ ├── proxy_apis.c │ ├── proxy_apis.h │ ├── request │ │ ├── BUILD │ │ ├── request.h │ │ ├── ta_find_transaction_objects.c │ │ ├── ta_find_transaction_objects.h │ │ ├── ta_recv_mam.c │ │ ├── ta_recv_mam.h │ │ ├── ta_register_mam_channel.c │ │ ├── ta_register_mam_channel.h │ │ ├── ta_send_mam.c │ │ ├── ta_send_mam.h │ │ ├── ta_send_transfer.c │ │ └── ta_send_transfer.h │ ├── response │ │ ├── BUILD │ │ ├── response.h │ │ ├── ta_fetch_buffered_request_status.c │ │ ├── ta_fetch_buffered_request_status.h │ │ ├── ta_find_transactions.c │ │ ├── ta_find_transactions.h │ │ ├── ta_find_transactions_obj.c │ │ ├── ta_find_transactions_obj.h │ │ ├── ta_recv_mam.c │ │ ├── ta_recv_mam.h │ │ ├── ta_send_mam.c │ │ ├── ta_send_mam.h │ │ ├── ta_send_transfer.c │ │ └── ta_send_transfer.h │ └── serializer │ │ ├── BUILD │ │ ├── ser_helper.c │ │ ├── ser_helper.h │ │ ├── ser_mam.c │ │ ├── ser_mam.h │ │ ├── serializer.c │ │ └── serializer.h ├── main.c ├── mqtt_main.c ├── runtime_cli.c └── runtime_cli.h ├── common ├── BUILD ├── debug.c ├── debug.h ├── logger.h ├── macros.h ├── ta_errors.c └── ta_errors.h ├── connectivity ├── BUILD ├── common.c ├── common.h ├── http │ ├── BUILD │ ├── http.c │ └── http.h └── mqtt │ ├── BUILD │ ├── duplex_callback.c │ ├── duplex_callback.h │ ├── duplex_utils.c │ ├── duplex_utils.h │ ├── mqtt_common.c │ ├── mqtt_common.h │ ├── pub_utils.c │ ├── pub_utils.h │ ├── sub_utils.c │ ├── sub_utils.h │ └── usage.md ├── crypto ├── BUILD ├── ecdh.c └── ecdh.h ├── docs ├── MAM-procedure.md ├── MQTT-mode-intro.md ├── OBD2-emulator.md ├── build.md ├── endpoint-platforms.md ├── endpoint-shell.md ├── endpoint.md ├── permanode.md ├── reattacher.md └── transaction-buffer.md ├── endpoint ├── BUILD ├── Makefile ├── OBDComp │ ├── BUILD │ ├── can-bus │ │ ├── BUILD │ │ ├── can-utils.c │ │ └── can-utils.h │ ├── emulator │ │ ├── BUILD │ │ ├── obd_emulator.c │ │ ├── obd_emulator.h │ │ └── script.sh │ ├── endpointService │ │ ├── Component.cdef │ │ └── endpoint_service.c │ ├── monitor │ │ ├── BUILD │ │ ├── Component.cdef │ │ └── monitor.c │ └── obd_pid.h ├── OBDMonitor.adef ├── build-legato.sh ├── cipher.c ├── cipher.h ├── connectivity │ ├── BUILD │ ├── conn_http.c │ └── conn_http.h ├── diagnose.adef ├── diagnoseComp │ ├── Component.cdef │ ├── diagnose.c │ └── diagnose.h ├── endpoint.adef ├── endpoint.api ├── endpointComp │ ├── Component.cdef │ ├── endpoint.c │ └── endpoint.h ├── endpoint_core.c ├── endpoint_core.h ├── https.c ├── https.h ├── platform │ ├── impl.h │ ├── legato-target │ │ └── impl.c │ └── simulator │ │ └── impl.c ├── shell.adef ├── shellComp │ ├── Component.cdef │ ├── shell.c │ └── shell.h ├── tests │ ├── regression │ │ ├── BUILD │ │ ├── driver.sh │ │ └── test_http.c │ └── unit-test │ │ ├── BUILD │ │ ├── test_cipher.c │ │ └── test_text_serializer.c ├── text_serializer.c └── text_serializer.h ├── hooks ├── autohook.sh ├── buildifier ├── ci_buildifier_check ├── ci_format_check ├── format-exclude-list ├── formatter ├── pre-commit │ ├── 01-buildifier-check │ ├── 02-format-check │ └── 03-function-check ├── scripts │ ├── buildifier_check │ ├── format_check │ └── function_check └── toolchains.rc ├── pem ├── BUILD ├── README.md ├── cert.pem └── key.pem ├── reattacher ├── BUILD └── reattacher_main.c ├── storage ├── BUILD ├── scylladb_client.c ├── scylladb_client.h ├── scylladb_identity.c ├── scylladb_identity.h ├── scylladb_permanode.c ├── scylladb_permanode.h ├── scylladb_utils.c ├── scylladb_utils.h └── ta_storage.h ├── tests ├── BUILD ├── api │ ├── BUILD │ ├── driver.c │ ├── driver_setting.py │ ├── mam_test.c │ ├── test_mam_psk.c │ ├── test_periodical_task.c │ ├── test_write_until_next_channel.c │ └── test_write_with_chid.c ├── common.c ├── common.h ├── coverity_analysis.sh ├── endpoint │ ├── common.sh │ ├── test-endpoint.sh │ └── test-target.sh ├── regression │ ├── common.py │ ├── common.sh │ ├── load_test_suite │ │ ├── TransferTest.py │ │ ├── __init__.py │ │ └── readme.md │ ├── requirements.txt │ ├── router-sanitizer.sh │ ├── run-api-with-db.sh │ ├── run-api-with-mqtt.sh │ ├── run-api.sh │ ├── runner.py │ ├── ta_waiting.sh │ └── test_suite │ │ ├── find_transactions_hash_by_tag.py │ │ ├── find_transactions_object_by_tag.py │ │ ├── get_transactions_object.py │ │ ├── get_transactions_object_single.py │ │ ├── send_transfer.py │ │ └── send_trytes.py ├── test_define.h └── unit-test │ ├── BUILD │ ├── test_cache.c │ ├── test_crypto.c │ ├── test_pow.c │ ├── test_scylladb.c │ ├── test_serializer.c │ ├── test_timer.c │ └── test_tryte_byte_conv.c ├── third_party ├── BUILD ├── BUILD.hiredis ├── flatcc.BUILD ├── mbedtls.BUILD └── third_party.bzl └── utils ├── BUILD ├── bundle_array.h ├── cache ├── BUILD ├── backend_redis.c └── cache.h ├── char_buffer_str.h ├── cpuinfo.h ├── fill_nines.h ├── hash_algo_djb2.h ├── timer.c ├── timer.h ├── tryte_byte_conv.c └── tryte_byte_conv.h /.bazelrc: -------------------------------------------------------------------------------- 1 | build --copt -W 2 | build --copt -Wall 3 | build --copt -Wextra 4 | build --output_filter='^//((?!external:).)*$' 5 | 6 | coverage -s 7 | coverage --experimental_cc_coverage 8 | coverage --combined_report=lcov 9 | coverage --coverage_report_generator=@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main 10 | coverage --instrumentation_filter="-/tests[/:]" 11 | 12 | 13 | test --copt='-ggdb3' 14 | 15 | # enforce using python2 16 | # see also: https://github.com/bazelbuild/rules_docker#known-issues 17 | build --host_force_python=PY2 18 | test --host_force_python=PY2 19 | run --host_force_python=PY2 20 | 21 | # --config asan: Address sanitizer 22 | build:asan --strip=never 23 | build:asan --copt -DADDRESS_SANITIZER 24 | build:asan --copt -fsanitize=address 25 | build:asan --copt -fno-omit-frame-pointer 26 | build:asan --linkopt -fsanitize=address 27 | 28 | # --config tsan: ThreadSanitizer 29 | build:tsan --strip=never 30 | build:tsan --copt -DTHREAD_SANITIZER 31 | build:tsan --copt -DDYNAMIC_ANNOTATIONS_ENABLED=1 32 | build:tsan --copt -DDYNAMIC_ANNOTATIONS_EXTERNAL_IMPL=1 33 | build:tsan --copt -fsanitize=thread 34 | build:tsan --copt -fno-omit-frame-pointer 35 | build:tsan --linkopt -fsanitize=thread 36 | build:tsan --linkopt -ltsan 37 | 38 | # --config msan: Memory sanitizer 39 | build:msan --strip=never 40 | build:msan --copt -DADDRESS_SANITIZER 41 | build:msan --copt -fsanitize=memory 42 | build:msan --copt -fno-omit-frame-pointer 43 | build:msan --linkopt -fsanitize=memory 44 | 45 | # --config ubsan: Undefined Behavior Sanitizer 46 | build:ubsan --strip=never 47 | build:ubsan --copt -fsanitize=undefined 48 | build:ubsan --copt -fno-omit-frame-pointer 49 | build:ubsan --linkopt -fsanitize=undefined 50 | build:ubsan --linkopt -lubsan 51 | 52 | import %workspace%/hooks/toolchains.rc 53 | try-import %workspace%/user.bazelrc 54 | -------------------------------------------------------------------------------- /.ci/coverity_scan.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Download Coverity Build Tool 4 | wget -q https://scan.coverity.com/download/cxx/linux64 --post-data "token=$TOKEN&project=DLTcollab/tangle-accelerator" -O cov-analysis-linux64.tar.gz 5 | mkdir cov-analysis-linux64 6 | tar xzf cov-analysis-linux64.tar.gz --strip 1 -C cov-analysis-linux64 7 | 8 | # Build with cov-build 9 | export PATH=`pwd`/cov-analysis-linux64/bin:$PATH 10 | cov-build --dir cov-int bash tests/coverity_analysis.sh 11 | 12 | # Submit the result to Coverity Scan 13 | tar czvf tangle-accelerator.tgz cov-int 14 | curl \ 15 | --form project=DLTcollab/tangle-accelerator \ 16 | --form token=$TOKEN \ 17 | --form email=yanghau@biilabs.io \ 18 | --form file=@tangle-accelerator.tgz \ 19 | --form version=trunk \ 20 | --form description="Tangle-accelerator" \ 21 | https://scan.coverity.com/builds?project=DLTcollab/tangle-accelerator 22 | -------------------------------------------------------------------------------- /.ci/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | sudo apt update -y 4 | sudo apt upgrade -y 5 | echo -n | openssl s_client -connect https://scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- 6 | # Add Bazel distribution URI as a package source 7 | sudo apt install curl 8 | curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add - 9 | echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list 10 | # Install and update Bazel 11 | sudo apt install bazel 12 | # Install UUID library 13 | sudo apt install uuid-dev 14 | # Install Cassandra C client library 15 | echo "deb https://downloads.apache.org/cassandra/debian 311x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list 16 | curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add - 17 | sudo apt-get update 18 | sudo apt-get install -y libuv1 libuv1-dev cassandra 19 | -------------------------------------------------------------------------------- /.github/workflows/github_actions.yml: -------------------------------------------------------------------------------- 1 | name: Github CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | coverity-scan: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: checkout code 10 | uses: actions/checkout@v2 11 | - name: install dependencies 12 | run: | 13 | bash .ci/setup.sh 14 | - name: coverity scan 15 | run: | 16 | bash .ci/coverity_scan.sh 17 | env: 18 | TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .#* 3 | 4 | # Mobile Tools for Java (J2ME) 5 | .mtj.tmp/ 6 | 7 | # Package Files # 8 | *.jar 9 | *.war 10 | *.ear 11 | 12 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 13 | hs_err_pid* 14 | 15 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 16 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 17 | 18 | # User-specific stuff: 19 | .idea/**/workspace.xml 20 | .idea/**/tasks.xml 21 | 22 | # Sensitive or high-churn files: 23 | .idea/**/dataSources/ 24 | .idea/**/dataSources.ids 25 | .idea/**/dataSources.xml 26 | .idea/**/dataSources.local.xml 27 | .idea/**/sqlDataSources.xml 28 | .idea/**/dynamic.xml 29 | .idea/**/uiDesigner.xml 30 | 31 | # Gradle: 32 | .idea/**/gradle.xml 33 | .idea/**/libraries 34 | 35 | # Mongo Explorer plugin: 36 | .idea/**/mongoSettings.xml 37 | 38 | ## File-based project format: 39 | *.iws 40 | 41 | ## Plugin-specific files: 42 | 43 | # IntelliJ 44 | /out/ 45 | /lib/ 46 | 47 | # Visual Studio 48 | .vs/ 49 | 50 | # mpeltonen/sbt-idea plugin 51 | .idea_modules/ 52 | 53 | # JIRA plugin 54 | atlassian-ide-plugin.xml 55 | 56 | # Crashlytics plugin (for Android Studio and IntelliJ) 57 | com_crashlytics_export_strings.xml 58 | crashlytics.properties 59 | crashlytics-build.properties 60 | fabric.properties 61 | 62 | buck-out/ 63 | .buckd/ 64 | .buckconfig.local 65 | 66 | .idea/ 67 | pom.xml 68 | *.iml 69 | 70 | # Logs 71 | *.log 72 | .gdb_history 73 | 74 | bazel* 75 | .bazelrc 76 | cclient/bazel* 77 | cclient/cmake-* 78 | 79 | coverage 80 | 81 | # Atom conf 82 | .clang_complete 83 | 84 | # Database 85 | ciri/ciri.db* 86 | 87 | # Visual Studio Code conf 88 | .vscode/ 89 | 90 | # Documentation 91 | docs/html/ 92 | 93 | # Python 94 | __pycache__/ 95 | 96 | # Certificate for build system 97 | pem/*.inc 98 | 99 | # Legato app related files 100 | resolv.conf 101 | output_base/ 102 | endpoint/_build_*/ 103 | _build_*/ 104 | *.*.update 105 | .repo 106 | legato/ 107 | build/ 108 | leaf-data 109 | leaf-workspace.json 110 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "third_party/dcurl"] 2 | path = third_party/dcurl 3 | url = https://github.com/DLTcollab/dcurl.git 4 | [submodule "third_party/hiredis"] 5 | path = third_party/hiredis 6 | url = https://github.com/redis/hiredis.git 7 | [submodule "third_party/mosquitto"] 8 | path = third_party/mosquitto 9 | url = https://github.com/eclipse/mosquitto.git 10 | [submodule "third_party/brotli"] 11 | path = third_party/brotli 12 | url = https://github.com/google/brotli.git 13 | [submodule "third_party/flatcc"] 14 | path = third_party/flatcc 15 | url = https://github.com/dvidelabs/flatcc.git 16 | [submodule "third_party/vehicle-scheme"] 17 | path = third_party/vehicle-scheme 18 | url = https://github.com/DLTcollab/vehicle-scheme.git 19 | [submodule "third_party/mbedtls"] 20 | path = third_party/mbedtls 21 | url = https://github.com/ARMmbed/mbedtls.git 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: bionic 2 | 3 | env: 4 | global: 5 | # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created 6 | # via the "travis encrypt" command using the project repo's public key 7 | - secure: "UzFj98mHlWrUob3k8s+T3AyPY3V/M5PIMyTzdNpLokby6YOl7BAb0ubeHkz3JxfYiEvGt1TB5zD/8LA8hBH0pn/EccrgNX/BYLW+ZUBA3rbBahJvpcTlGqKifKbWYEcPXSrW+naAEU5HFIfYayhyGLg1weucY2lsoM7yo8NlE2kYPu9+XXbltHpRYa2Nfw0bTHRs0RRVSs5kvtLIVyq/f2Mv/CdBbJJRaiTlzVUilQvejM9bdu/sLOvDdxucv6wMvPdzJL2LtXW6BSjjkE9lgQg58OT2AxErBENMElZMMG3lO2KgHozTJ+IOjJ+/CzkyUHfLjAD7aKxRN4cygV/DXcoZ/+ppw5MqDLA7eIVzX0xAjy6S93QPrfpiB4rkohls8NCAd4No6o0vFgCvFfPxcbYpa7eLEyrMpbHnUwBkGXcHUHyGg/v5WQUCthHGUTJ0A0SIPn7z5WEaNTv15IusSVSxYZhLu0PqWosABslDnaMVrOZkgkaNMty3ZFBpNBWHtlH9XjybBe4V28/E4g5xOrwkDm9KLiFQi+vjdPx2i0vOCgRHseG5DCRUBjyfgktOOP3DhOvbe48CxAyRm2qT1T/xeT9qK420k9fryjzdMV/4L86Fid4oBqAGd+ScjODhgIS3tAQRpdpOzFZWitwWxZUEGC4AjqrwTwIsyiBopuI=" 8 | 9 | language: c 10 | 11 | before_install: 12 | - echo -n | openssl s_client -connect https://scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- 13 | # Add Bazel distribution URI as a package source 14 | - sudo apt install curl 15 | - curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add - 16 | - echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list 17 | # Install and update Bazel 18 | - sudo apt update && sudo apt install bazel 19 | # Install UUID library 20 | - sudo apt install uuid-dev 21 | # Install Cassandra C client library 22 | - wget https://downloads.datastax.com/cpp-driver/ubuntu/18.04/dependencies/libuv/v1.35.0/libuv1_1.35.0-1_amd64.deb 23 | - sudo dpkg -i libuv1_1.35.0-1_amd64.deb 24 | - wget https://downloads.datastax.com/cpp-driver/ubuntu/18.04/cassandra/v2.15.1/cassandra-cpp-driver_2.15.1-1_amd64.deb 25 | - sudo dpkg -i cassandra-cpp-driver_2.15.1-1_amd64.deb 26 | - wget https://downloads.datastax.com/cpp-driver/ubuntu/18.04/cassandra/v2.15.1/cassandra-cpp-driver-dev_2.15.1-1_amd64.deb 27 | - sudo dpkg -i cassandra-cpp-driver-dev_2.15.1-1_amd64.deb 28 | 29 | addons: 30 | coverity_scan: 31 | project: 32 | name: "DLTcollab/tangle-accelerator" 33 | description: "Accelerate IOTA transactions by caching API requests and redirecting to faster alternatives" 34 | notification_email: yanghau@biilabs.io 35 | build_command_prepend: "" 36 | build_command: "bash tests/coverity_analysis.sh" 37 | branch_pattern: develop 38 | 39 | script: if [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then bash -e tests/coverity_analysis.sh; fi 40 | -------------------------------------------------------------------------------- /BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar") 2 | 3 | pkg_tar( 4 | name = "pkg_coverage", 5 | srcs = glob(["coverage/*"]), 6 | package_dir = "./coverage", 7 | ) 8 | -------------------------------------------------------------------------------- /Doxyfile: -------------------------------------------------------------------------------- 1 | DOXYFILE_ENCODING = UTF-8 2 | PROJECT_NAME = "tangle-accelerator" 3 | PROJECT_NUMBER = 0.9.7 4 | OUTPUT_DIRECTORY = docs/ 5 | OPTIMIZE_OUTPUT_FOR_C = YES 6 | INPUT = . \ 7 | accelerator \ 8 | accelerator/core \ 9 | accelerator/core/request \ 10 | accelerator/core/response \ 11 | accelerator/core/serializer \ 12 | endpoint \ 13 | endpoint/endpointComp \ 14 | endpoint/hal \ 15 | endpoint \ 16 | utils \ 17 | utils/cache \ 18 | common \ 19 | storage \ 20 | connectivity/mqtt \ 21 | connectivity/http 22 | FILE_PATTERNS = *.h \ 23 | *.md \ 24 | *.c 25 | EXAMPLE_PATH = tests 26 | EXAMPLE_PATTERNS = test_* 27 | USE_MDFILE_AS_MAINPAGE = README.md 28 | GENERATE_LATEX = NO 29 | QUIET = YES 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 4 | All Rights Reserved. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository", "new_git_repository") 2 | load("//third_party:third_party.bzl", "third_party_deps") 3 | 4 | git_repository( 5 | name = "rules_iota", 6 | commit = "2d15c55f12cff0db106f45866312f61314c583cd", 7 | remote = "https://github.com/iotaledger/rules_iota.git", 8 | ) 9 | 10 | git_repository( 11 | name = "iota_toolchains", 12 | commit = "700904f445d15ef948d112bf0bccf7dd3814ae5c", 13 | remote = "https://github.com/iotaledger/toolchains.git", 14 | ) 15 | 16 | git_repository( 17 | name = "iota.c", 18 | commit = "3f1c255bd6e7ccc19bd527a83fa4593d342cad32", 19 | remote = "https://github.com/iotaledger/iota.c.git", 20 | ) 21 | 22 | git_repository( 23 | name = "org_iota_common", 24 | commit = "cf649803757abf48432d4fa60e9f27ac119bae5f", 25 | remote = "https://github.com/iotaledger/iota_common.git", 26 | ) 27 | 28 | git_repository( 29 | name = "mam.c", 30 | commit = "fca24aa8f98e535c6af9feea3394bdeea555d0d3", 31 | remote = "https://github.com/iotaledger/mam.c.git", 32 | ) 33 | 34 | git_repository( 35 | name = "io_bazel_rules_docker", 36 | remote = "https://github.com/bazelbuild/rules_docker.git", 37 | tag = "v0.9.0", 38 | ) 39 | 40 | new_git_repository( 41 | name = "mbedtls_2_16_6", 42 | build_file = "//third_party:mbedtls.BUILD", 43 | remote = "https://github.com/ARMmbed/mbedtls.git", 44 | tag = "mbedtls-2.16.6", 45 | ) 46 | 47 | new_git_repository( 48 | name = "flatcc_0_6_0", 49 | build_file = "//third_party:flatcc.BUILD", 50 | remote = "https://github.com/dvidelabs/flatcc.git", 51 | tag = "v0.6.0", 52 | ) 53 | 54 | load("@rules_iota//:defs.bzl", "iota_deps") 55 | load("@io_bazel_rules_docker//repositories:repositories.bzl", container_repositories = "repositories") 56 | 57 | container_repositories() 58 | 59 | load("@io_bazel_rules_docker//cc:image.bzl", _cc_image_repos = "repositories") 60 | load("@io_bazel_rules_docker//container:pull.bzl", "container_pull") 61 | 62 | container_pull( 63 | name = "ubuntu1804", 64 | registry = "l.gcr.io", 65 | repository = "google/ubuntu1804", 66 | tag = "latest", 67 | ) 68 | 69 | iota_deps() 70 | 71 | third_party_deps() 72 | 73 | _cc_image_repos() 74 | 75 | load("@iota_toolchains//:toolchains.bzl", "setup_initial_deps") 76 | 77 | setup_initial_deps() 78 | 79 | load("@iota_toolchains//:defs.bzl", "setup_toolchains_repositories") 80 | 81 | setup_toolchains_repositories() 82 | -------------------------------------------------------------------------------- /accelerator/core/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "apis", 3 | srcs = ["apis.c"], 4 | hdrs = ["apis.h"], 5 | linkopts = [ 6 | "-lpthread", 7 | ], 8 | visibility = ["//visibility:public"], 9 | deps = [ 10 | "//accelerator:build_option", 11 | "//accelerator/core", 12 | "//accelerator/core:mam_core", 13 | "//accelerator/core/serializer", 14 | "//common", 15 | ], 16 | ) 17 | 18 | cc_library( 19 | name = "proxy_apis", 20 | srcs = ["proxy_apis.c"], 21 | hdrs = ["proxy_apis.h"], 22 | visibility = ["//visibility:public"], 23 | deps = [ 24 | "//accelerator/core/serializer", 25 | "//utils:char_buffer_str", 26 | "//utils:hash_algo_djb2", 27 | "@iota.c//cclient/api", 28 | "@iota.c//cclient/request:requests", 29 | "@iota.c//cclient/response:responses", 30 | ], 31 | ) 32 | 33 | cc_library( 34 | name = "core", 35 | srcs = ["core.c"], 36 | hdrs = ["core.h"], 37 | linkopts = [ 38 | "-luuid", 39 | ], 40 | visibility = ["//visibility:public"], 41 | deps = [ 42 | "//accelerator:ta_config", 43 | "//accelerator/core/request", 44 | "//accelerator/core/response", 45 | "//accelerator/core/serializer", 46 | "//common", 47 | "//utils:bundle_array", 48 | "//utils:char_buffer_str", 49 | "//utils:timer", 50 | "@com_github_uthash//:uthash", 51 | "@iota.c//cclient/api", 52 | "@org_iota_common//utils:time", 53 | "@org_iota_common//utils/containers/hash:hash243_set", 54 | ], 55 | ) 56 | 57 | cc_library( 58 | name = "mam_core", 59 | srcs = ["mam_core.c"], 60 | hdrs = ["mam_core.h"], 61 | visibility = ["//visibility:public"], 62 | deps = [ 63 | "//accelerator/core", 64 | "//accelerator/core/request", 65 | "//accelerator/core/response", 66 | "//utils:fill_nines", 67 | "//utils:tryte_byte_conv", 68 | "@mam.c//mam/api", 69 | "@org_iota_common//common/trinary:flex_trit", 70 | "@org_iota_common//utils/containers/hash:hash_array", 71 | ], 72 | ) 73 | 74 | cc_library( 75 | name = "pow", 76 | srcs = ["pow.c"], 77 | hdrs = ["pow.h"], 78 | visibility = ["//visibility:public"], 79 | deps = [ 80 | "//common:ta_errors", 81 | "//common:ta_logger", 82 | "//third_party:dcurl", 83 | "@com_github_uthash//:uthash", 84 | "@org_iota_common//common/helpers:digest", 85 | "@org_iota_common//common/model:bundle", 86 | "@org_iota_common//common/trinary:flex_trit", 87 | "@org_iota_common//utils:time", 88 | ], 89 | ) 90 | 91 | cc_library( 92 | name = "periodical_task", 93 | srcs = ["periodical_task.c"], 94 | hdrs = ["periodical_task.h"], 95 | linkopts = [ 96 | "-lpthread", 97 | ], 98 | visibility = ["//visibility:public"], 99 | deps = [ 100 | ":core", 101 | ":mam_core", 102 | "//common:ta_errors", 103 | "//common:ta_logger", 104 | ], 105 | ) 106 | -------------------------------------------------------------------------------- /accelerator/core/mam_core.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CORE_MAM_CORE_H_ 10 | #define CORE_MAM_CORE_H_ 11 | 12 | #include "accelerator/core/core.h" 13 | #include "common/macros.h" 14 | #include "common/trinary/flex_trit.h" 15 | #include "common/trinary/tryte_ascii.h" 16 | #include "mam/api/api.h" 17 | #include "mam/mam/mam_channel_t_set.h" 18 | #include "utarray.h" 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | /** 25 | * @file accelerator/core/mam_core.h 26 | */ 27 | 28 | /** 29 | * Initialize logger for 'mam_core' 30 | */ 31 | void ta_mam_logger_init(); 32 | 33 | /** 34 | * Release logger 35 | * 36 | * @return 37 | * - zero on success 38 | * - EXIT_FAILURE on error 39 | */ 40 | int ta_mam_logger_release(); 41 | 42 | typedef enum mam_send_operation_e { ANNOUNCE_CHID, SEND_MESSAGE } mam_send_operation_t; 43 | 44 | typedef struct mam_encrypt_key_s { 45 | mam_psk_t_set_t psks; 46 | mam_ntru_pk_t_set_t ntru_pks; 47 | mam_ntru_sk_t_set_t ntru_sks; 48 | } mam_encrypt_key_t; 49 | 50 | /** 51 | * @brief Send a MAM message. 52 | * 53 | * @param[in] info Tangle-accelerator configuration variables 54 | * @param[in] iconf IOTA API parameter configurations 55 | * @param[in] service IOTA node service 56 | * @param[in] req Request in 'ta_send_mam_req_t' datatype 57 | * @param[out] res Result in 'ta_send_mam_res_t' datatype 58 | * 59 | * @return 60 | * - SC_OK on success 61 | * - non-zero on error 62 | */ 63 | status_t ta_send_mam_message(const ta_config_t* const info, const iota_config_t* const iconf, 64 | const iota_client_service_t* const service, ta_send_mam_req_t const* const req, 65 | ta_send_mam_res_t* const res); 66 | 67 | /** 68 | * @brief Receive MAM messages. 69 | * 70 | * @param[in] iconf IOTA API parameter configurations 71 | * @param[in] service IOTA node service 72 | * @param[in] req Request in 'ta_recv_mam_req_t' datatype 73 | * @param[out] res Result in 'ta_recv_mam_res_t' datatype 74 | * 75 | * @return 76 | * - SC_OK on success 77 | * - non-zero on error 78 | */ 79 | status_t ta_recv_mam_message(const iota_config_t* const iconf, const iota_client_service_t* const service, 80 | ta_recv_mam_req_t* const req, ta_recv_mam_res_t* const res); 81 | 82 | /** 83 | * @brief Register user identity with MAM channel seed. 84 | * 85 | * @param[in] cache redis configuration variables 86 | * @param[in] req Request in 'ta_register_mam_channel_req_t' datatype 87 | * @param[out] uuid Returned UUID 88 | * 89 | * @return 90 | * - SC_OK on success 91 | * - non-zero on error 92 | */ 93 | status_t ta_register_mam_channel(const ta_cache_t* const cache, const ta_register_mam_channel_req_t* const req, 94 | char* uuid); 95 | 96 | #ifdef __cplusplus 97 | } 98 | #endif 99 | 100 | #endif // CORE_MAM_CORE_H_ 101 | -------------------------------------------------------------------------------- /accelerator/core/periodical_task.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CORE_PERIODICAL_TASK_H_ 10 | #define CORE_PERIODICAL_TASK_H_ 11 | 12 | #include 13 | #include "accelerator/config.h" 14 | #include "accelerator/core/core.h" 15 | #include "accelerator/core/mam_core.h" 16 | #include "common/logger.h" 17 | #include "common/ta_errors.h" 18 | #include "pthread.h" 19 | #include "time.h" 20 | #include "uuid/uuid.h" 21 | 22 | #ifdef __cplusplus 23 | extern "C" { 24 | #endif 25 | 26 | /** 27 | * @file accelerator/core/periodical_task.h 28 | */ 29 | 30 | void* health_track(void* arg); 31 | 32 | /** 33 | * @brief Broadcast transactions in transaction buffer 34 | * 35 | * Failed transactions would be stored in transaction buffer. Once tangle-accelerator retrieve the connetion with 36 | * Tangle, then tangle-accelerator will start to broadcast these failed transaction trytes. 37 | * 38 | * @param[in] core Pointer to Tangle-accelerator core configuration structure 39 | * 40 | * @return 41 | * - SC_OK on success 42 | * - non-zero on error 43 | */ 44 | status_t broadcast_buffered_txn(const ta_core_t* const core); 45 | 46 | /** 47 | * @brief Broadcast buffered MAM requests 48 | * 49 | * @param[in] core Pointer to Tangle-accelerator core configuration structure 50 | * 51 | * @return 52 | * - SC_OK on success 53 | * - non-zero on error 54 | */ 55 | status_t broadcast_buffered_send_mam_request(const ta_core_t* const core); 56 | 57 | #ifdef __cplusplus 58 | } 59 | #endif 60 | 61 | #endif // CORE_PERIODICAL_TASK_H_ 62 | -------------------------------------------------------------------------------- /accelerator/core/pow.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CORE_POW_H_ 10 | #define CORE_POW_H_ 11 | 12 | #include 13 | #include "common/model/bundle.h" 14 | #include "common/ta_errors.h" 15 | #include "common/trinary/flex_trit.h" 16 | #include "utarray.h" 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | /** 23 | * @file accelerator/core/pow.h 24 | * @brief PoW interface 25 | * @example unit-test/test_pow.c 26 | */ 27 | 28 | /** 29 | * Initiate pow module 30 | */ 31 | void pow_init(); 32 | 33 | /** 34 | * Stop interacting with pow module 35 | */ 36 | void pow_destroy(); 37 | 38 | /** 39 | * Perform PoW and return the result of flex trits 40 | * 41 | * @param[in] trits_in Flex trits that does pow 42 | * @param[in] mwm Maximum weight magnitude 43 | * 44 | * @return a flex_trit_t data 45 | */ 46 | flex_trit_t* ta_pow_flex(const flex_trit_t* const trits_in, const uint8_t mwm); 47 | 48 | /** 49 | * Perform PoW to the given bundle 50 | * 51 | * @param[in] bundle Bundle that does pow 52 | * @param[in] trunk Trunk transaction hash 53 | * @param[in] branch Branch transaction hash 54 | * @param[in] mwm Maximum weight magnitude 55 | * 56 | * @return 57 | * - SC_OK on success 58 | * - non-zero on error 59 | */ 60 | status_t ta_pow(const bundle_transactions_t* bundle, const flex_trit_t* const trunk, const flex_trit_t* const branch, 61 | const uint8_t mwm); 62 | 63 | #ifdef __cplusplus 64 | } 65 | #endif 66 | 67 | #endif // CORE_POW_H_ 68 | -------------------------------------------------------------------------------- /accelerator/core/proxy_apis.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CORE_PROXY_APIS_H_ 10 | #define CORE_PROXY_APIS_H_ 11 | 12 | #include "cclient/api/core/core_api.h" 13 | #include "cclient/request/requests.h" 14 | #include "cclient/response/responses.h" 15 | #include "serializer/serializer.h" 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | /** 22 | * @file accelerator/core/proxy_apis.h 23 | * @brief Implement Proxy APIs 24 | * 25 | * tangle-accelerator provides major IOTA Proxy APIs wrapper. 26 | * The arguments and return strings are all in json format. There can be 27 | * different server or protocol integration with these APIs. 28 | */ 29 | 30 | /** 31 | * Initialize logger 32 | */ 33 | void proxy_apis_logger_init(); 34 | 35 | /** 36 | * Release logger 37 | * 38 | * @return 39 | * - zero on success 40 | * - EXIT_FAILURE on error 41 | */ 42 | int proxy_apis_logger_release(); 43 | 44 | /** 45 | * Initialize lock 46 | * 47 | * @return 48 | * - zero on success 49 | * - SC_CONF_LOCK_INIT on error 50 | */ 51 | status_t proxy_apis_lock_init(); 52 | 53 | /** 54 | * Destroy lock 55 | * 56 | * @return 57 | * - zero on success 58 | * - SC_CONF_LOCK_DESTROY on error 59 | */ 60 | status_t proxy_apis_lock_destroy(); 61 | 62 | /** 63 | * @brief Proxy API of IOTA core functionalities 64 | * 65 | * @param[in] iconf IOTA API parameter configurations 66 | * @param[in] service IOTA full node service 67 | * @param[in] obj IOTA core APIs request body 68 | * @param[out] json_result Result of IOTA core APIs 69 | * 70 | * @return 71 | * - SC_OK on success 72 | * - non-zero on error 73 | */ 74 | status_t proxy_api_wrapper(const ta_config_t* const iconf, const iota_client_service_t* const service, 75 | const char* const obj, char** json_result); 76 | 77 | #ifdef __cplusplus 78 | } 79 | #endif 80 | 81 | #endif // CORE_PROXY_APIS_H_ 82 | -------------------------------------------------------------------------------- /accelerator/core/request/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "request", 3 | srcs = glob([ 4 | "*.c", 5 | ]), 6 | hdrs = glob([ 7 | "*.h", 8 | ]), 9 | include_prefix = "accelerator/core/request", 10 | visibility = ["//visibility:public"], 11 | deps = [ 12 | "//common", 13 | "@org_iota_common//common:errors", 14 | "@org_iota_common//common/model:transaction", 15 | "@org_iota_common//common/trinary:tryte", 16 | "@org_iota_common//utils/containers/hash:hash243_queue", 17 | "@org_iota_common//utils/containers/hash:hash81_queue", 18 | ], 19 | ) 20 | -------------------------------------------------------------------------------- /accelerator/core/request/request.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef REQUEST_REQUEST_H_ 10 | #define REQUEST_REQUEST_H_ 11 | 12 | #include "ta_find_transaction_objects.h" 13 | #include "ta_recv_mam.h" 14 | #include "ta_register_mam_channel.h" 15 | #include "ta_send_mam.h" 16 | #include "ta_send_transfer.h" 17 | 18 | /** 19 | * @file accelerator/core/request/request.h 20 | * @brief Data structure of request type 21 | */ 22 | 23 | #endif // REQUEST_REQUEST_H__ 24 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_find_transaction_objects.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_find_transaction_objects.h" 10 | 11 | ta_find_transaction_objects_req_t* ta_find_transaction_objects_req_new() { 12 | ta_find_transaction_objects_req_t* req = 13 | (ta_find_transaction_objects_req_t*)malloc(sizeof(ta_find_transaction_objects_req_t)); 14 | if (req != NULL) { 15 | req->hashes = NULL; 16 | return req; 17 | } 18 | return NULL; 19 | } 20 | 21 | void ta_find_transaction_objects_req_free(ta_find_transaction_objects_req_t** req) { 22 | if (*req) { 23 | hash243_queue_free(&(*req)->hashes); 24 | free((*req)); 25 | *req = NULL; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_find_transaction_objects.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef REQUEST_TA_GET_TRANSACTION_OBJECT_H_ 10 | #define REQUEST_TA_GET_TRANSACTION_OBJECT_H_ 11 | 12 | #include "common/model/transaction.h" 13 | #include "common/ta_errors.h" 14 | #include "utils/containers/hash/hash243_queue.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | /** 21 | * @file accelerator/core/request/ta_find_transaction_objects.h 22 | */ 23 | 24 | /** struct of ta_find_transaction_objects_req_t */ 25 | typedef struct ta_find_transaction_objects_req { 26 | /** Transaction hashes in ascii with UT_array. */ 27 | hash243_queue_t hashes; 28 | } ta_find_transaction_objects_req_t; 29 | 30 | /** 31 | * @brief Allocate memory of ta_find_transaction_objects_req_t 32 | * 33 | * @return 34 | * - struct of ta_find_transaction_objects_req_t on success 35 | * - NULL on error 36 | */ 37 | ta_find_transaction_objects_req_t* ta_find_transaction_objects_req_new(); 38 | 39 | /** 40 | * @brief Free memory of ta_find_transaction_objects_req_t 41 | * 42 | * @param[in] req Data type of ta_find_transaction_objects_req_t 43 | */ 44 | void ta_find_transaction_objects_req_free(ta_find_transaction_objects_req_t** req); 45 | 46 | #ifdef __cplusplus 47 | } 48 | #endif 49 | 50 | #endif // REQUEST_TA_GET_TRANSACTION_OBJECT_H_ 51 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_register_mam_channel.c: -------------------------------------------------------------------------------- 1 | #include "ta_register_mam_channel.h" 2 | 3 | ta_register_mam_channel_req_t* ta_register_mam_channel_req_new() { 4 | ta_register_mam_channel_req_t* req = (ta_register_mam_channel_req_t*)malloc(sizeof(ta_register_mam_channel_req_t)); 5 | if (req != NULL) { 6 | return req; 7 | } 8 | return NULL; 9 | } 10 | 11 | void ta_register_mam_channel_req_free(ta_register_mam_channel_req_t** req) { 12 | if (!req || !(*req)) { 13 | return; 14 | } 15 | free(*req); 16 | *req = NULL; 17 | } 18 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_register_mam_channel.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef REQUEST_TA_REGISTER_MAM_CHANNEL_H_ 10 | #define REQUEST_TA_REGISTER_MAM_CHANNEL_H_ 11 | 12 | #include "common/model/transaction.h" 13 | #include "common/ta_errors.h" 14 | #include "utils/containers/hash/hash243_queue.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | /** 21 | * @file accelerator/core/request/ta_register_mam_channel.h 22 | */ 23 | 24 | /** struct of ta_register_mam_channel_req_t */ 25 | typedef struct ta_register_mam_channel_req { 26 | char seed[NUM_TRYTES_ADDRESS + 1]; 27 | } ta_register_mam_channel_req_t; 28 | 29 | /** 30 | * @brief Allocate memory of ta_register_mam_channel_req_t 31 | * 32 | * @return 33 | * - struct of ta_register_mam_channel_req_t on success 34 | * - NULL on error 35 | */ 36 | ta_register_mam_channel_req_t* ta_register_mam_channel_req_new(); 37 | 38 | /** 39 | * @brief Free memory of ta_register_mam_channel_req_t 40 | * 41 | * @param[in] req Data type of ta_register_mam_channel_req_t 42 | */ 43 | void ta_register_mam_channel_req_free(ta_register_mam_channel_req_t** req); 44 | 45 | #ifdef __cplusplus 46 | } 47 | #endif 48 | 49 | #endif // REQUEST_TA_REGISTER_MAM_CHANNEL_H_ 50 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_send_mam.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_send_mam.h" 10 | 11 | ta_send_mam_req_t* send_mam_req_new() { 12 | ta_send_mam_req_t* req = (ta_send_mam_req_t*)malloc(sizeof(ta_send_mam_req_t)); 13 | if (req) { 14 | req->data = NULL; 15 | req->key = NULL; 16 | } 17 | 18 | return req; 19 | } 20 | 21 | status_t send_mam_req_v1_init(ta_send_mam_req_t* req) { 22 | if (req == NULL) { 23 | return SC_NULL; 24 | } 25 | 26 | memset(req->service_token, 0, SERVICE_TOKEN_LEN + 1); 27 | 28 | req->data = (send_mam_data_mam_v1_t*)malloc(sizeof(send_mam_data_mam_v1_t)); 29 | if (req->data == NULL) { 30 | return SC_OOM; 31 | } 32 | req->key = (send_mam_key_mam_v1_t*)malloc(sizeof(send_mam_key_mam_v1_t)); 33 | if (req->key == NULL) { 34 | return SC_OOM; 35 | } 36 | 37 | send_mam_data_mam_v1_t* data = req->data; 38 | data->seed = NULL; 39 | data->chid = NULL; 40 | data->message = NULL; 41 | data->ch_mss_depth = 6; 42 | 43 | send_mam_key_mam_v1_t* key = req->key; 44 | utarray_new(key->psk_array, &ut_str_icd); 45 | utarray_new(key->ntru_array, &ut_str_icd); 46 | 47 | return SC_OK; 48 | } 49 | 50 | static void send_mam_req_v1_free(ta_send_mam_req_t** req) { 51 | if ((*req)->data) { 52 | send_mam_data_mam_v1_t* data = (*req)->data; 53 | free(data->seed); 54 | free(data->chid); 55 | free(data->message); 56 | free((*req)->data); 57 | (*req)->data = NULL; 58 | } 59 | 60 | if ((*req)->key) { 61 | send_mam_key_mam_v1_t* key = (*req)->key; 62 | utarray_free(key->psk_array); 63 | utarray_free(key->ntru_array); 64 | free((*req)->key); 65 | (*req)->key = NULL; 66 | } 67 | } 68 | 69 | void send_mam_req_free(ta_send_mam_req_t** req) { 70 | if (!req || !(*req)) { 71 | return; 72 | } 73 | 74 | if ((*req)->protocol == MAM_V1) { 75 | send_mam_req_v1_free(req); 76 | } 77 | 78 | free(*req); 79 | *req = NULL; 80 | } 81 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_send_transfer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_send_transfer.h" 10 | 11 | ta_send_transfer_req_t* ta_send_transfer_req_new() { 12 | ta_send_transfer_req_t* req = (ta_send_transfer_req_t*)malloc(sizeof(ta_send_transfer_req_t)); 13 | if (req != NULL) { 14 | req->tag = NULL; 15 | req->address = NULL; 16 | memset(req->message, 0, sizeof(tryte_t) * NUM_TRYTES_MESSAGE); 17 | return req; 18 | } 19 | return NULL; 20 | } 21 | 22 | void ta_send_transfer_req_free(ta_send_transfer_req_t** req) { 23 | if (*req) { 24 | hash81_queue_free(&(*req)->tag); 25 | hash243_queue_free(&(*req)->address); 26 | free(*req); 27 | *req = NULL; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /accelerator/core/request/ta_send_transfer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef REQUEST_TA_SEND_TRANSFER_H_ 10 | #define REQUEST_TA_SEND_TRANSFER_H_ 11 | 12 | #include 13 | #include "common/macros.h" 14 | #include "common/trinary/flex_trit.h" 15 | #include "utils/containers/hash/hash243_queue.h" 16 | #include "utils/containers/hash/hash81_queue.h" 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | /** 23 | * @file accelerator/core/request/ta_send_transfer.h 24 | */ 25 | 26 | /** struct of ta_send_transfer_req_t */ 27 | typedef struct { 28 | /** Transfer value */ 29 | int value; 30 | /** Transfer tag is a 81 long flex trits hash queue. */ 31 | hash81_queue_t tag; 32 | /** Transfer address is a 243 long flex trits hash queue. */ 33 | hash243_queue_t address; 34 | /** @name message metadata */ 35 | /* @{ */ 36 | /** Transfer message is a 2187 long trytes array. */ 37 | tryte_t message[NUM_TRYTES_MESSAGE]; 38 | /** message trytes length */ 39 | int msg_len; 40 | /* @} */ 41 | } ta_send_transfer_req_t; 42 | 43 | /** 44 | * @brief Allocate memory of ta_send_transfer_req_t 45 | * 46 | * @return 47 | * - struct of ta_send_transfer_req_t on success 48 | * - NULL on error 49 | */ 50 | ta_send_transfer_req_t* ta_send_transfer_req_new(); 51 | 52 | /** 53 | * @brief Free memory of ta_send_transfer_req_t 54 | * 55 | * @param[in] req Data type of ta_send_transfer_req_t 56 | */ 57 | void ta_send_transfer_req_free(ta_send_transfer_req_t** req); 58 | 59 | #ifdef __cplusplus 60 | } 61 | #endif 62 | 63 | #endif // REQUEST_TA_SEND_TRANSFER_H_ 64 | -------------------------------------------------------------------------------- /accelerator/core/response/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "response", 3 | srcs = glob([ 4 | "*.c", 5 | ]), 6 | hdrs = glob([ 7 | "*.h", 8 | ]), 9 | include_prefix = "accelerator/core/response", 10 | visibility = ["//visibility:public"], 11 | deps = [ 12 | "//common", 13 | "//accelerator:build_option", 14 | "@org_iota_common//common:errors", 15 | "@org_iota_common//common/model:transaction", 16 | "@mam.c//mam/mam:message", 17 | "@org_iota_common//utils/containers/hash:hash243_queue", 18 | "@org_iota_common//utils/containers/hash:hash243_stack", 19 | ] + select({ 20 | "//accelerator:db_enable": ["//storage"], 21 | "//conditions:default": [], 22 | }), 23 | ) 24 | -------------------------------------------------------------------------------- /accelerator/core/response/response.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_RESPONSE_H_ 10 | #define RESPONSE_RESPONSE_H_ 11 | 12 | #include "ta_fetch_buffered_request_status.h" 13 | #include "ta_find_transactions.h" 14 | #include "ta_find_transactions_obj.h" 15 | #include "ta_recv_mam.h" 16 | #include "ta_send_mam.h" 17 | #include "ta_send_transfer.h" 18 | 19 | /** 20 | * @file accelerator/core/response/response.h 21 | * @brief Data structure of response type 22 | */ 23 | 24 | #endif // RESPONSE_RESPONSE_H_ 25 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_fetch_buffered_request_status.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_fetch_buffered_request_status.h" 10 | 11 | ta_fetch_buffered_request_status_res_t* ta_fetch_buffered_request_status_res_new() { 12 | ta_fetch_buffered_request_status_res_t* res = 13 | (ta_fetch_buffered_request_status_res_t*)malloc(sizeof(ta_fetch_buffered_request_status_res_t)); 14 | if (res) { 15 | res->bundle = NULL; 16 | bundle_transactions_new(&(res->bundle)); 17 | res->mam_result = NULL; 18 | res->status = MAM_BUFREQ_NOT_EXIST; 19 | } 20 | return res; 21 | } 22 | 23 | void ta_fetch_buffered_request_status_res_free(ta_fetch_buffered_request_status_res_t** res) { 24 | if (!res || !(*res)) { 25 | return; 26 | } 27 | 28 | bundle_transactions_free(&((*res)->bundle)); 29 | free((*res)->mam_result); 30 | free(*res); 31 | *res = NULL; 32 | } 33 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_fetch_buffered_request_status.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_TA_fetch_buffered_request_status_H_ 10 | #define RESPONSE_TA_fetch_buffered_request_status_H_ 11 | 12 | #include "common/macros.h" 13 | #include "common/model/bundle.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file accelerator/core/response/ta_fetch_buffered_request_status.h 21 | */ 22 | 23 | /** 24 | * The enumeration of the status of buffered requests 25 | */ 26 | typedef enum { 27 | MAM_BUFREQ_UNSENT /**< Buffered request hasn't be broadcasted */, 28 | MAM_BUFREQ_NOT_EXIST /**< A request with given UUID is not existed */, 29 | MAM_BUFREQ_SENT /**< Buffered request has be broadcasted */ 30 | } request_with_uuid_status_t; 31 | 32 | /** struct of ta_fetch_buffered_request_status_res */ 33 | typedef struct ta_fetch_buffered_request_status_res_s { 34 | bundle_transactions_t* bundle; /**< bundle transaction object. */ 35 | request_with_uuid_status_t status; /**< request status. */ 36 | char* mam_result; /**< the result of buffered MAM requests are in string. */ 37 | } ta_fetch_buffered_request_status_res_t; 38 | 39 | /** 40 | * @brief Allocate memory of ta_fetch_buffered_request_status_res_t 41 | * 42 | * @return 43 | * - struct of ta_fetch_buffered_request_status_res_t on success 44 | * - NULL on error 45 | */ 46 | ta_fetch_buffered_request_status_res_t* ta_fetch_buffered_request_status_res_new(); 47 | 48 | /** 49 | * @brief Free memory of ta_fetch_buffered_request_status_res_t 50 | * 51 | * @param[in] res Response in `ta_fetch_buffered_request_status_res_t` datatype 52 | */ 53 | void ta_fetch_buffered_request_status_res_free(ta_fetch_buffered_request_status_res_t** res); 54 | 55 | #ifdef __cplusplus 56 | } 57 | #endif 58 | 59 | #endif // RESPONSE_TA_FETCH_BUFFERED_REQUEST_STATUS_H_ 60 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_find_transactions.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_find_transactions.h" 10 | 11 | ta_find_transactions_by_tag_res_t* ta_find_transactions_res_new() { 12 | ta_find_transactions_by_tag_res_t* res = 13 | (ta_find_transactions_by_tag_res_t*)malloc(sizeof(ta_find_transactions_by_tag_res_t)); 14 | if (res) { 15 | res->hashes = NULL; 16 | } 17 | return res; 18 | } 19 | 20 | void ta_find_transactions_res_free(ta_find_transactions_by_tag_res_t** res) { 21 | if (!res || !(*res)) { 22 | return; 23 | } 24 | 25 | hash243_queue_free(&(*res)->hashes); 26 | free(*res); 27 | *res = NULL; 28 | } 29 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_find_transactions.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_TA_FIND_TRANSACTIONS_H_ 10 | #define RESPONSE_TA_FIND_TRANSACTIONS_H_ 11 | 12 | #include 13 | #include "utils/containers/hash/hash243_queue.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file accelerator/core/response/ta_find_transactions.h 21 | */ 22 | 23 | /** struct of ta_find_transactions_by_tag_res_t */ 24 | typedef struct ta_find_transactions_res { 25 | /** Transaction hashes is a 243 long flex trits hash queue. */ 26 | hash243_queue_t hashes; 27 | } ta_find_transactions_by_tag_res_t; 28 | 29 | /** 30 | * @brief Allocate memory of ta_find_transactions_by_tag_res_t 31 | * 32 | * @return 33 | * - struct of ta_find_transactions_by_tag_res_t on success 34 | * - NULL on error 35 | */ 36 | ta_find_transactions_by_tag_res_t* ta_find_transactions_res_new(); 37 | 38 | /** 39 | * @brief Free memory of ta_find_transactions_by_tag_res_t 40 | * 41 | * @param[in] res Pointer of pointer of ta_find_transactions_by_tag_res_t 42 | */ 43 | void ta_find_transactions_res_free(ta_find_transactions_by_tag_res_t** res); 44 | 45 | #ifdef __cplusplus 46 | } 47 | #endif 48 | 49 | #endif // RESPONSE_TA_FIND_TRANSACTIONS_H_ 50 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_find_transactions_obj.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_find_transactions_obj.h" 10 | 11 | static UT_icd txn_icd = {sizeof(iota_transaction_t), 0, 0, 0}; 12 | 13 | ta_find_transactions_obj_res_t* ta_find_transactions_obj_res_new() { 14 | ta_find_transactions_obj_res_t* res = (ta_find_transactions_obj_res_t*)malloc(sizeof(ta_find_transactions_obj_res_t)); 15 | if (res) { 16 | utarray_new(res->txn_obj, &txn_icd); 17 | } 18 | return res; 19 | } 20 | 21 | void ta_find_transactions_obj_res_free(ta_find_transactions_obj_res_t** res) { 22 | if (!res || !(*res)) { 23 | return; 24 | } 25 | 26 | if ((*res)->txn_obj) { 27 | utarray_free((*res)->txn_obj); 28 | } 29 | free(*res); 30 | *res = NULL; 31 | } 32 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_find_transactions_obj.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_TA_FIND_TRANSACTIONS_OBJ_H_ 10 | #define RESPONSE_TA_FIND_TRANSACTIONS_OBJ_H_ 11 | 12 | #include "./utarray.h" 13 | #include "common/model/transaction.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file accelerator/core/response/ta_find_transactions_obj.h 21 | */ 22 | 23 | /** struct of ta_find_transactions_obj_res_t */ 24 | typedef struct ta_find_transactions_obj_res { 25 | /**< Transaction objects is transaction_array_t. */ 26 | transaction_array_t* txn_obj; 27 | } ta_find_transactions_obj_res_t; 28 | 29 | /** 30 | * @brief Allocate memory of ta_find_transactions_obj_res_t 31 | * 32 | * @return 33 | * - struct of ta_find_transactions_obj_res_t on success 34 | * - NULL on error 35 | */ 36 | ta_find_transactions_obj_res_t* ta_find_transactions_obj_res_new(); 37 | 38 | /** 39 | * @brief Free memory of ta_find_transactions_obj_res_t 40 | * 41 | * @param[in] res Pointer of pointer of ta_find_transactions_obj_res_t object 42 | */ 43 | void ta_find_transactions_obj_res_free(ta_find_transactions_obj_res_t** res); 44 | 45 | #ifdef __cplusplus 46 | } 47 | #endif 48 | 49 | #endif // RESPONSE_TA_FIND_TRANSACTIONS_OBJ_H_ 50 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_recv_mam.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_recv_mam.h" 10 | ta_recv_mam_res_t* recv_mam_res_new() { 11 | ta_recv_mam_res_t* res = (ta_recv_mam_res_t*)malloc(sizeof(ta_recv_mam_res_t)); 12 | if (res) { 13 | memset(res->chid1, 0, NUM_TRYTES_ADDRESS + 1); 14 | utarray_new(res->payload_array, &ut_str_icd); 15 | } 16 | return res; 17 | } 18 | 19 | void recv_mam_res_free(ta_recv_mam_res_t** res) { 20 | if (!res || !(*res)) { 21 | return; 22 | } 23 | 24 | utarray_free((*res)->payload_array); 25 | free(*res); 26 | *res = NULL; 27 | } 28 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_recv_mam.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_TA_RECV_MAM_H_ 10 | #define RESPONSE_TA_RECV_MAM_H_ 11 | 12 | #include "common/macros.h" 13 | #include "common/ta_errors.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file accelerator/core/response/ta_recv_mam.h 21 | */ 22 | 23 | /** struct of ta_recv_mam_res_t */ 24 | typedef struct recv_mam_res_s { 25 | UT_array* payload_array; /**< An array of MAM messages */ 26 | char chid1[NUM_TRYTES_HASH + 1]; /**< The Channel ID of next Channel */ 27 | } ta_recv_mam_res_t; 28 | 29 | /** 30 | * @brief Allocate memory of ta_recv_mam_res_t 31 | * 32 | * @return 33 | * - The pointer of the ta_recv_mam_res_t struct 34 | * - NULL on error 35 | */ 36 | ta_recv_mam_res_t* recv_mam_res_new(); 37 | 38 | /** 39 | * @brief Free memory of ta_recv_mam_res_t 40 | * 41 | * @param[in] res Pointer of pointer of ta_recv_mam_res_t object 42 | */ 43 | void recv_mam_res_free(ta_recv_mam_res_t** res); 44 | 45 | #ifdef __cplusplus 46 | } 47 | #endif 48 | 49 | #endif // RESPONSE_TA_RECV_MAM_H_ 50 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_send_transfer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "ta_send_transfer.h" 10 | 11 | ta_send_transfer_res_t* ta_send_transfer_res_new() { 12 | ta_send_transfer_res_t* res = (ta_send_transfer_res_t*)malloc(sizeof(ta_send_transfer_res_t)); 13 | if (res) { 14 | res->hash = NULL; 15 | res->uuid = NULL; 16 | res->address = NULL; 17 | } 18 | return res; 19 | } 20 | 21 | void ta_send_transfer_res_free(ta_send_transfer_res_t** res) { 22 | if ((*res)) { 23 | free((*res)->uuid); 24 | free((*res)->address); 25 | hash243_queue_free(&(*res)->hash); 26 | free((*res)); 27 | *res = NULL; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /accelerator/core/response/ta_send_transfer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef RESPONSE_TA_SEND_TRANSFER_H_ 10 | #define RESPONSE_TA_SEND_TRANSFER_H_ 11 | 12 | #include 13 | #ifdef DB_ENABLE 14 | #include "storage/ta_storage.h" 15 | #endif 16 | #include "common/model/transaction.h" 17 | #include "utils/containers/hash/hash243_queue.h" 18 | #include "uuid/uuid.h" 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | /** 25 | * @file accelerator/core/response/ta_send_transfer.h 26 | */ 27 | 28 | /** struct of ta_send_transfer_res_t */ 29 | typedef struct { 30 | hash243_queue_t hash; /**< Transaction address is a 243 long flex trits hash queue. */ 31 | transaction_array_t* txn_array; /**< Transaction object array */ 32 | char* uuid; /**< Returned UUID for querying the buffered transaction */ 33 | tryte_t* address; /**< Returned transaction address of the buffered transaction */ 34 | #ifdef DB_ENABLE 35 | char uuid_string[DB_UUID_STRING_LENGTH]; /**< Returned UUID for querying the transactions in DB */ 36 | #endif 37 | } ta_send_transfer_res_t; 38 | 39 | /** 40 | * @brief Allocate memory of ta_send_transfer_res_t 41 | * 42 | * @return 43 | * - struct of ta_send_transfer_res_t on success 44 | * - NULL on error 45 | */ 46 | ta_send_transfer_res_t* ta_send_transfer_res_new(); 47 | 48 | /** 49 | * @brief Free memory of ta_send_transfer_res_t 50 | * 51 | * @param[in] res Pointer of pointer of ta_send_transfer_res_t object 52 | */ 53 | void ta_send_transfer_res_free(ta_send_transfer_res_t** res); 54 | 55 | #ifdef __cplusplus 56 | } 57 | #endif 58 | 59 | #endif // RESPONSE_TA_SEND_TRANSFER_H_ 60 | -------------------------------------------------------------------------------- /accelerator/core/serializer/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "serializer", 3 | srcs = ["serializer.c"], 4 | hdrs = ["serializer.h"], 5 | visibility = ["//visibility:public"], 6 | deps = [ 7 | ":ser_helper", 8 | ":ser_mam", 9 | "//accelerator:ta_config", 10 | "//common", 11 | "//accelerator:build_option", 12 | "//accelerator/core/request", 13 | "//accelerator/core/response", 14 | "//utils:fill_nines", 15 | ] + select({ 16 | "//accelerator:mqtt_enable": ["//connectivity/mqtt:mqtt_common"], 17 | "//conditions:default": [], 18 | }), 19 | ) 20 | 21 | cc_library( 22 | name = "ser_helper", 23 | srcs = ["ser_helper.c"], 24 | hdrs = ["ser_helper.h"], 25 | deps = [ 26 | "//accelerator/core/request", 27 | "//accelerator/core/response", 28 | "//common", 29 | "@cJSON", 30 | ], 31 | ) 32 | 33 | cc_library( 34 | name = "ser_mam", 35 | srcs = ["ser_mam.c"], 36 | hdrs = ["ser_mam.h"], 37 | deps = [ 38 | ":ser_helper", 39 | "//accelerator/core/request", 40 | "//accelerator/core/response", 41 | "//common", 42 | "@cJSON", 43 | ], 44 | ) 45 | -------------------------------------------------------------------------------- /accelerator/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "accelerator/core/periodical_task.h" 4 | #include "common/logger.h" 5 | #include "common/ta_errors.h" 6 | #include "connectivity/common.h" 7 | #include "connectivity/http/http.h" 8 | #include "pthread.h" 9 | #include "runtime_cli.h" 10 | #include "time.h" 11 | #include "utils/handles/signal.h" 12 | 13 | #define MAIN_LOGGER "main" 14 | 15 | static ta_core_t ta_core; 16 | static ta_http_t ta_http; 17 | static logger_id_t logger_id; 18 | 19 | static void ta_stop(int signal) { 20 | if (signal == SIGINT || signal == SIGTERM) { 21 | ta_http_stop(&ta_http); 22 | } 23 | } 24 | 25 | int main(int argc, char* argv[]) { 26 | if (signal_handle_register(SIGINT, ta_stop) == SIG_ERR || signal_handle_register(SIGTERM, ta_stop) == SIG_ERR) { 27 | return EXIT_FAILURE; 28 | } 29 | 30 | // Initialize logger 31 | if (ta_logger_init() != SC_OK) { 32 | return EXIT_FAILURE; 33 | } 34 | 35 | logger_id = logger_helper_enable(MAIN_LOGGER, LOGGER_DEBUG, true); 36 | 37 | // Initialize configurations with default value 38 | if (ta_core_default_init(&ta_core) != SC_OK) { 39 | return EXIT_FAILURE; 40 | } 41 | 42 | // Initialize configurations with file value 43 | if (ta_core_file_init(&ta_core, argc, argv) != SC_OK) { 44 | return EXIT_FAILURE; 45 | } 46 | 47 | // Initialize configurations with CLI value 48 | if (ta_core_cli_init(&ta_core, argc, argv) != SC_OK) { 49 | return EXIT_FAILURE; 50 | } 51 | 52 | if (ta_core_set(&ta_core) != SC_OK) { 53 | ta_log_error("Configure failed %s.\n", MAIN_LOGGER); 54 | return EXIT_FAILURE; 55 | } 56 | 57 | pthread_t health_thread; 58 | pthread_create(&health_thread, NULL, health_track, (void*)&ta_core); 59 | 60 | if (is_option_enabled(&ta_core.ta_conf, CLI_RUNTIME_CLI)) { 61 | pthread_t cli_thread; 62 | pthread_create(&cli_thread, NULL, cli_routine, (void*)&ta_core); 63 | } 64 | 65 | if (ta_http_init(&ta_http, &ta_core) != SC_OK) { 66 | ta_log_error("HTTP initialization failed %s.\n", MAIN_LOGGER); 67 | return EXIT_FAILURE; 68 | } 69 | 70 | if (ta_http_start(&ta_http) != SC_OK) { 71 | ta_log_error("Starting TA failed %s.\n", MAIN_LOGGER); 72 | goto cleanup; 73 | } 74 | 75 | log_info(logger_id, "Tangle-accelerator starts running\n"); 76 | ta_logger_switch(is_option_enabled(&ta_core.ta_conf, CLI_QUIET_MODE), true, &(ta_core.ta_conf)); 77 | 78 | // Once tangle-accelerator finished initializing, notify regression test script with unix domain socket 79 | notification_trigger(&ta_core.ta_conf); 80 | 81 | /* pause() cause TA to sleep until it catch a signal, 82 | * also the return value and errno should be -1 and EINTR on success. 83 | */ 84 | int sig_ret = pause(); 85 | if (sig_ret == -1 && errno != EINTR) { 86 | ta_log_error("Signal caught failed %s.\n", MAIN_LOGGER); 87 | return EXIT_FAILURE; 88 | } 89 | 90 | cleanup: 91 | log_info(logger_id, "Destroying TA configurations\n"); 92 | ta_logger_switch(true, false, &(ta_core.ta_conf)); 93 | ta_core_destroy(&ta_core); 94 | logger_helper_release(logger_id); 95 | if (logger_helper_destroy() != RC_OK) { 96 | ta_log_error("Destroying logger failed %s.\n", MAIN_LOGGER); 97 | return EXIT_FAILURE; 98 | } 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /accelerator/mqtt_main.c: -------------------------------------------------------------------------------- 1 | #include "accelerator/config.h" 2 | #include "common/ta_errors.h" 3 | #include "config.h" 4 | #include "connectivity/mqtt/duplex_callback.h" 5 | #include "connectivity/mqtt/duplex_utils.h" 6 | #include "connectivity/mqtt/mqtt_common.h" 7 | 8 | #define CONN_MQTT_LOGGER "conn-mqtt" 9 | 10 | ta_core_t ta_core; 11 | static logger_id_t logger_id; 12 | 13 | int main(int argc, char *argv[]) { 14 | status_t ret; 15 | mosq_config_t cfg; 16 | struct mosquitto *mosq = NULL; 17 | 18 | // Initialize logger 19 | if (ta_logger_init() != SC_OK) { 20 | return EXIT_FAILURE; 21 | } 22 | 23 | logger_id = logger_helper_enable(CONN_MQTT_LOGGER, LOGGER_DEBUG, true); 24 | 25 | // Initialize configurations with default value 26 | if (ta_core_default_init(&ta_core) != SC_OK) { 27 | return EXIT_FAILURE; 28 | } 29 | 30 | // Initialize configurations with configuration file 31 | if (ta_core_file_init(&ta_core, argc, argv) != SC_OK) { 32 | return EXIT_FAILURE; 33 | } 34 | 35 | // Initialize configurations with CLI value 36 | if (ta_core_cli_init(&ta_core, argc, argv) != SC_OK) { 37 | return EXIT_FAILURE; 38 | } 39 | 40 | if (ta_core_set(&ta_core) != SC_OK) { 41 | ta_log_error("Configure failed %s.\n", CONN_MQTT_LOGGER); 42 | return EXIT_FAILURE; 43 | } 44 | ta_mqtt_init(&ta_core); 45 | 46 | ta_logger_switch(is_option_enabled(&ta_core.ta_conf, CLI_QUIET_MODE), true, &(ta_core.ta_conf)); 47 | 48 | // Initialize `mosq` and `cfg` 49 | // if we want to operate this program under multi-threading, see https://github.com/eclipse/mosquitto/issues/450 50 | ret = duplex_config_init(&mosq, &cfg); 51 | if (ret != SC_OK) { 52 | ta_log_error("%d\n", ret); 53 | goto done; 54 | } 55 | 56 | // Set callback functions 57 | duplex_callback_func_set(mosq); 58 | 59 | // The following one line is used for testing if this server work fine with requests with given topics. 60 | // Uncomment it if it is necessitated 61 | // gossip_channel_set(&cfg, MQTT_HOST, "NB/test/room1", "NB/test/room2"); 62 | 63 | // Set the configures and message for testing 64 | ret = gossip_api_channels_set(&cfg, ta_core.ta_conf.mqtt_host, ta_core.ta_conf.mqtt_topic_root); 65 | if (ret != SC_OK) { 66 | ta_log_error("%d\n", ret); 67 | goto done; 68 | } 69 | 70 | // Set cfg as `userdata` field of `mosq` which allows the callback functions to use `cfg`. 71 | mosquitto_user_data_set(mosq, &cfg); 72 | 73 | log_info(logger_id, "Starting...\n"); 74 | 75 | // Start listening subscribing topics, once we received a message from the listening topics, we can send corresponding 76 | // message. 77 | do { 78 | // TODO Use logger to log some important steps in processing requests. 79 | log_info(logger_id, "Listening new requests.\n"); 80 | ret = duplex_client_start(mosq, &cfg); 81 | } while (!ret); 82 | 83 | done: 84 | mosquitto_destroy(mosq); 85 | mosquitto_lib_cleanup(); 86 | mosq_config_free(&cfg); 87 | ta_logger_switch(true, false, &(ta_core.ta_conf)); 88 | return ret; 89 | } 90 | -------------------------------------------------------------------------------- /accelerator/runtime_cli.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef ACCELERATOR_RUNTIME_CLI_H 10 | #define ACCELERATOR_RUNTIME_CLI_H 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | /** 21 | * @file accelerator/runtime_cli.h 22 | * @brief Runtime command-line utility 23 | */ 24 | 25 | /** 26 | * @brief Runtime command-line utility thread 27 | */ 28 | void *cli_routine(void *arg); 29 | 30 | /** 31 | * @brief Command state types in state machine 32 | */ 33 | enum { 34 | CMD_LAST, /**< The last subcommand, could be followed by zero or more parameters */ 35 | CMD_STATE, /**< Subcommands expected, should step to next state according to `next_state` */ 36 | }; 37 | struct cli_cmd; 38 | struct cli_list; 39 | 40 | /** 41 | * @brief Structure that holds the information of a (sub)command. 42 | */ 43 | typedef struct cli_cmd { 44 | const char *name; /**< Name of the command */ 45 | const char *describe; /**< Detailed description of the command */ 46 | const char *example; /**< Example usage of the command (should be empty string literal if not needed */ 47 | const int type; /**< Command state types */ 48 | union { 49 | struct cli_list *next_state; /**< Determine the next state to step (CMD_STATE) */ 50 | void (*fn)(char *cmd); /**< Determine the function to call (CMD_LAST) */ 51 | }; 52 | } ta_cli_cmd; 53 | 54 | /** 55 | * @brief Structure that holds the information of a state 56 | * 57 | * We define the different states using `ta_cli_list_t`, 58 | * each state can determine whether to step to next state (CMD_STATE) 59 | * or stop (CMD_LAST). 60 | */ 61 | typedef struct cli_list { 62 | const size_t size; /**< Number of (sub)commands in the state */ 63 | const struct cli_cmd list[]; /**< Array of (sub)commands */ 64 | } ta_cli_list_t; 65 | 66 | #ifdef __cplusplus 67 | } 68 | #endif 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /common/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "common", 5 | deps = [ 6 | "macros", 7 | ":debug", 8 | ":ta_errors", 9 | ":ta_logger", 10 | ], 11 | ) 12 | 13 | cc_library( 14 | name = "ta_errors", 15 | srcs = ["ta_errors.c"], 16 | hdrs = ["ta_errors.h"], 17 | ) 18 | 19 | cc_library( 20 | name = "ta_logger", 21 | srcs = ["logger.h"], 22 | defines = ["LOGGER_ENABLE"], 23 | deps = [ 24 | ":ta_errors", 25 | "@org_iota_common//utils:logger_helper", 26 | ], 27 | ) 28 | 29 | cc_library( 30 | name = "macros", 31 | hdrs = ["macros.h"], 32 | deps = [ 33 | "@mam.c//mam/mam:message", 34 | "@org_iota_common//common/model:transaction", 35 | "@org_iota_common//common/trinary:tryte", 36 | "@org_iota_common//utils/containers/hash:hash243_stack", 37 | "@org_iota_common//utils/containers/hash:hash_array", 38 | ], 39 | ) 40 | 41 | cc_library( 42 | name = "debug", 43 | srcs = ["debug.c"], 44 | hdrs = ["debug.h"], 45 | deps = [ 46 | ":ta_logger", 47 | "@org_iota_common//common/model:bundle", 48 | "@org_iota_common//common/model:transaction", 49 | ], 50 | ) 51 | -------------------------------------------------------------------------------- /common/debug.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 IOTA Stiftung 3 | * https://github.com/iotaledger/entangled 4 | * 5 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 6 | * All Rights Reserved. 7 | * This is free software; you can redistribute it and/or modify it under the 8 | * terms of the MIT license. A copy of the license can be found in the file 9 | * "LICENSE" at the root of this distribution. 10 | */ 11 | 12 | #ifndef COMMON_DEBUG_H_ 13 | #define COMMON_DEBUG_H_ 14 | 15 | #include "common/crypto/iss/v1/iss_kerl.h" 16 | #include "common/helpers/sign.h" 17 | #include "common/model/bundle.h" 18 | #include "common/trinary/trit_long.h" 19 | #include "common/trinary/tryte_long.h" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "common/crypto/curl-p/digest.h" 27 | #include "common/model/transaction.h" 28 | #include "common/trinary/trit_long.h" 29 | 30 | #include "logger.h" 31 | 32 | /** 33 | * @file common/debug.h 34 | * @brief Debugging tool for tangle-accelerator 35 | */ 36 | 37 | #ifdef __cplusplus 38 | extern "C" { 39 | #endif 40 | 41 | /** 42 | * Initialize logger 43 | */ 44 | void debug_logger_init(); 45 | 46 | /** 47 | * @brief Release logger 48 | * 49 | * @return 50 | * - zero on success 51 | * - EXIT_FAILURE on error 52 | */ 53 | int debug_logger_release(); 54 | 55 | /** 56 | * @brief Print the content of all the transaction objects in this bundle 57 | * 58 | * @param[in] bundle Bundle is going to dump message. 59 | * 60 | */ 61 | void dump_bundle(bundle_transactions_t *bundle); 62 | 63 | /** 64 | * @brief Print the all the contents this transaction object 65 | * 66 | * @param[in] tx_obj Bundle is going to dump message. 67 | * 68 | */ 69 | void dump_transaction_obj(iota_transaction_t *tx_obj); 70 | 71 | /** 72 | * @brief Compare two transaction objects 73 | * 74 | * @param[in] tx1 Compared transaction object one 75 | * @param[in] tx2 Compared transaction object two 76 | * 77 | * @return 78 | * - true on success 79 | * - false on error 80 | */ 81 | bool transaction_cmp(iota_transaction_t *tx1, iota_transaction_t *tx2); 82 | 83 | #ifdef __cplusplus 84 | } 85 | #endif 86 | 87 | #endif // COMMON_DEBUG_H_ 88 | -------------------------------------------------------------------------------- /common/macros.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef COMMON_MACROS_H_ 10 | #define COMMON_MACROS_H_ 11 | 12 | #include "common/model/bundle.h" 13 | #include "common/model/transaction.h" 14 | #include "common/trinary/trit_tryte.h" 15 | #include "mam/mam/message.h" 16 | #include "utils/containers/hash/hash243_stack.h" 17 | #include "utils/containers/hash/hash_array.h" 18 | 19 | #include 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | /** 25 | * @file common/macros.h 26 | * @brief Macros for tangle-accelerator 27 | */ 28 | 29 | typedef enum mam_protocol_e { MAM_V1 } mam_protocol_t; 30 | 31 | #define NUM_TRYTES_MAM_MSG_ID MAM_MSG_ID_SIZE / 3 32 | #define NUM_TRYTES_MAM_NTRU_PK_SIZE MAM_NTRU_PK_SIZE / 3 33 | /** 34 | * MAM_NTRU_SK_SIZE = 1024, so if we transform ntru secret key from trit to tryte, it would be 1024/3 = 341.33 \ 35 | */ 36 | #define NUM_TRYTES_MAM_NTRU_SK_SIZE 342 37 | #define NUM_TRYTES_MAM_PSK_KEY_SIZE MAM_PSK_KEY_SIZE / 3 38 | #define NUM_TRYTES_MAM_PSK_ID_SIZE MAM_PSK_ID_SIZE / 3 39 | 40 | #define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int : (-!!(e)); }))) 41 | #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) 42 | #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) 43 | #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr)) 44 | 45 | #define TRINARY_ALPHABET_LEN 27 /** 2 | #include 3 | #include 4 | 5 | #include "cJSON.h" 6 | #include "common.h" 7 | #include "common/logger.h" 8 | #include "common/ta_errors.h" 9 | 10 | #define CONN_LOGGER "connectivity" 11 | static logger_id_t logger_id; 12 | 13 | void conn_logger_init() { logger_id = logger_helper_enable(CONN_LOGGER, LOGGER_DEBUG, true); } 14 | 15 | int conn_logger_release() { 16 | logger_helper_release(logger_id); 17 | return 0; 18 | } 19 | 20 | status_t api_path_matcher(char const *const path, char *const regex_rule) { 21 | if (regex_rule == NULL) { 22 | ta_log_error("%s\n", ta_error_to_string(SC_NULL)); 23 | return SC_NULL; 24 | } 25 | regex_t reg; 26 | regmatch_t pmatch; 27 | status_t ret = SC_OK; 28 | int reg_flag = REG_EXTENDED; 29 | 30 | if (regcomp(®, regex_rule, reg_flag) != 0) { 31 | ta_log_error("%s\n", ta_error_to_string(SC_HTTP_INVALID_REGEX)); 32 | return SC_HTTP_INVALID_REGEX; 33 | } 34 | if (regexec(®, path, 1, &pmatch, 0) != 0) { 35 | // Did not match pattern 36 | ret = SC_HTTP_URL_NOT_MATCH; 37 | } else { 38 | if ((size_t)(pmatch.rm_eo - pmatch.rm_so) != strlen(path)) { 39 | ret = SC_HTTP_URL_NOT_MATCH; 40 | } 41 | } 42 | 43 | regfree(®); 44 | return ret; 45 | } 46 | 47 | status_t set_response_content(status_t ret, char **json_result) { 48 | int http_ret; 49 | if (ret == SC_OK) { 50 | return SC_HTTP_OK; 51 | } 52 | 53 | switch (ret) { 54 | case SC_CCLIENT_NOT_FOUND: 55 | case SC_MAM_NOT_FOUND: 56 | http_ret = SC_HTTP_NOT_FOUND; 57 | ta_log_error("%s\n", ta_error_to_string(SC_HTTP_NOT_FOUND)); 58 | *json_result = strdup(STR_HTTP_NOT_FOUND); 59 | break; 60 | case SC_CCLIENT_JSON_KEY: 61 | case SC_MAM_NO_PAYLOAD: 62 | case SC_HTTP_URL_NOT_MATCH: 63 | http_ret = SC_HTTP_BAD_REQUEST; 64 | ta_log_error("%s\n", ta_error_to_string(SC_HTTP_BAD_REQUEST)); 65 | *json_result = strdup(STR_HTTP_BAD_REQUEST); 66 | break; 67 | case SC_SERIALIZER_MESSAGE_OVERRUN: 68 | http_ret = SC_HTTP_BAD_REQUEST; 69 | ta_log_error("%s\n", ta_error_to_string(ret)); 70 | *json_result = strdup(STR_HTTP_BAD_REQUEST_MESSAGE_OVERRUN); 71 | break; 72 | default: 73 | http_ret = SC_HTTP_INTERNAL_SERVICE_ERROR; 74 | ta_log_error("%s\n", ta_error_to_string(SC_HTTP_INTERNAL_SERVICE_ERROR)); 75 | *json_result = strdup(STR_HTTP_INTERNAL_SERVICE_ERROR); 76 | break; 77 | } 78 | return http_ret; 79 | } 80 | -------------------------------------------------------------------------------- /connectivity/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CONN_COMMON_H 10 | #define CONN_COMMON_H 11 | #include "common/ta_errors.h" 12 | 13 | #ifdef __cplusplus 14 | extern "C" { 15 | #endif 16 | 17 | #define STR_HTTP_NOT_FOUND "{\"message\": \"Request not found\"}" 18 | #define STR_HTTP_BAD_REQUEST "{\"message\": \"Invalid request header\"}" 19 | #define STR_HTTP_BAD_REQUEST_MESSAGE_OVERRUN "{\"message\": \"In body 'message', requested message is too long.\"}" 20 | #define STR_HTTP_INTERNAL_SERVICE_ERROR "{\"message\": \"Internal service error\"}" 21 | #define STR_HTTP_REQUEST_SIZE_EXCEED "{\"message\": \"Request size exceed\"}" 22 | 23 | /** 24 | * @brief Match path with given regular expression rule 25 | * @param[in] path Path 26 | * @param[in] regex_rule Regex rule 27 | * 28 | * @return 29 | * - SC_NULL if regular expression is NULL 30 | * - SC_HTTP_INVALID_REGEX if failed to compile regular expression 31 | * - SC_HTTP_URL_NOT_MATCH if regular expression does not match the given path 32 | * - SC_OK on success 33 | */ 34 | status_t api_path_matcher(char const *const path, char *const regex_rule); 35 | 36 | /** 37 | * @brief Set http reponse content for given status_t code from functions 38 | * 39 | * @param[in] ret Status code returned from apis 40 | * @param[out] json_result Response content in json format 41 | * 42 | * @return HTTP status code 43 | */ 44 | status_t set_response_content(status_t ret, char **json_result); 45 | 46 | #ifdef __cplusplus 47 | } 48 | #endif 49 | 50 | #endif // CONN_COMMON_H 51 | -------------------------------------------------------------------------------- /connectivity/http/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "http", 3 | srcs = ["http.c"], 4 | hdrs = ["http.h"], 5 | visibility = ["//visibility:public"], 6 | deps = [ 7 | "//accelerator/core:apis", 8 | "//accelerator/core:proxy_apis", 9 | "//connectivity:common", 10 | "@libmicrohttpd", 11 | "@org_iota_common//utils:macros", 12 | ], 13 | ) 14 | -------------------------------------------------------------------------------- /connectivity/http/http.h: -------------------------------------------------------------------------------- 1 | #ifndef HTTP_HTTP_H_ 2 | #define HTTP_HTTP_H_ 3 | 4 | #include 5 | #include "accelerator/core/apis.h" 6 | #include "accelerator/core/proxy_apis.h" 7 | 8 | #ifdef __cplusplus 9 | extern "C" { 10 | #endif 11 | 12 | /** 13 | * @file connectivity/http/http.h 14 | * @brief Router of HTTP protocol 15 | */ 16 | 17 | typedef struct ta_http_s { 18 | void *daemon; 19 | ta_core_t *core; 20 | } ta_http_t; 21 | 22 | /** 23 | * Initializes an HTTP API 24 | * 25 | * @param http The HTTP status object 26 | * @param core An TA config information 27 | * 28 | * @return a status code 29 | */ 30 | status_t ta_http_init(ta_http_t *const http, ta_core_t *const core); 31 | 32 | /** 33 | * @brief Starts an HTTP API 34 | * 35 | * @param http The HTTP API 36 | * 37 | * @return a status code 38 | */ 39 | status_t ta_http_start(ta_http_t *const http); 40 | 41 | /** 42 | * @brief Stops an HTTP API 43 | * 44 | * @param http The HTTP API 45 | * 46 | * @return a status code 47 | */ 48 | status_t ta_http_stop(ta_http_t *const http); 49 | 50 | #ifdef __cplusplus 51 | } 52 | #endif 53 | 54 | #endif // HTTP_HTTP_H_ 55 | -------------------------------------------------------------------------------- /connectivity/mqtt/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "mqtt", 3 | srcs = [ 4 | "duplex_callback.c", 5 | "duplex_utils.c", 6 | ], 7 | hdrs = [ 8 | "duplex_callback.h", 9 | "duplex_utils.h", 10 | ], 11 | visibility = ["//visibility:public"], 12 | deps = [ 13 | ":mqtt_common", 14 | "//accelerator/core:apis", 15 | "//common", 16 | "//common:ta_errors", 17 | "//connectivity:common", 18 | "@org_iota_common//common/model:transaction", 19 | ], 20 | ) 21 | 22 | cc_library( 23 | name = "mqtt_common", 24 | srcs = [ 25 | "mqtt_common.c", 26 | "pub_utils.c", 27 | "sub_utils.c", 28 | ], 29 | hdrs = [ 30 | "mqtt_common.h", 31 | "pub_utils.h", 32 | "sub_utils.h", 33 | ], 34 | visibility = ["//accelerator/core/serializer:__pkg__"], 35 | deps = [ 36 | "//accelerator:ta_config", 37 | "//common:ta_errors", 38 | "//third_party:mosquitto", 39 | ], 40 | ) 41 | -------------------------------------------------------------------------------- /connectivity/mqtt/duplex_callback.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef MQTT_DUPLEX_CALLBACK_H_ 10 | #define MQTT_DUPLEX_CALLBACK_H_ 11 | 12 | #include "accelerator/core/apis.h" 13 | #include "common/model/transaction.h" 14 | #include "duplex_utils.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | /** 21 | * @file connectivity/mqtt/duplex_callback.h 22 | * @brief Callback functions to handle MQTT requests 23 | */ 24 | 25 | /** 26 | * @breif Initialize ta_core 27 | * 28 | * @param[in] core `struct ta_core_t` object 29 | */ 30 | void ta_mqtt_init(ta_core_t *const core); 31 | 32 | /** 33 | * @brief Interface for functions setting callback functions. 34 | * 35 | * @param[in] mosq `struct mosquitto` object 36 | * 37 | * @return 38 | * - SC_OK on success 39 | * - non-zero on error 40 | */ 41 | status_t duplex_callback_func_set(struct mosquitto *mosq); 42 | 43 | #ifdef __cplusplus 44 | } 45 | #endif 46 | 47 | #endif // MQTT_DUPLEX_CALLBACK_H_ 48 | -------------------------------------------------------------------------------- /connectivity/mqtt/pub_utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef MQTT_PUB_UTILS_H_ 10 | #define MQTT_PUB_UTILS_H_ 11 | 12 | #include "mqtt_common.h" 13 | #undef uthash_free 14 | #undef uthash_malloc 15 | #include "third_party/mosquitto/config.h" 16 | #include "third_party/mosquitto/lib/mqtt_protocol.h" 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | /** 23 | * @file connectivity/mqtt/pub_utils.h 24 | * @brief MQTT publisher utilities. 25 | */ 26 | 27 | /** 28 | * @brief Connect callback function of publisher. 29 | * 30 | * This callback function is called when the broker sends a CONNACK message in response to a connection owned by 31 | * publisher. 32 | */ 33 | void connect_callback_pub_func(struct mosquitto *mosq, void *obj, int result, int flags, 34 | const mosquitto_property *properties); 35 | 36 | /** 37 | * @brief Publish callback function of publisher. 38 | * 39 | * when a message initiated with has been sent to the broker. This callback will be called both if 40 | * the message is sent successfully, or if the broker responded with an error, which will be reflected in the 41 | * reason_code parameter. 42 | */ 43 | void publish_callback_pub_func(struct mosquitto *mosq, void *obj, int mid, int reason_code, 44 | const mosquitto_property *properties); 45 | 46 | /** 47 | * @brief Run `mosquitto_loop()` for publishing. 48 | * 49 | * @param[in] mosq `struct mosquitto` object 50 | * 51 | * @return 52 | * - SC_OK on success 53 | * - non-zero on error 54 | */ 55 | status_t publish_loop(struct mosquitto *mosq); 56 | 57 | /** 58 | * @brief Check if any error happened after initialization. 59 | * 60 | * @param[in] cfg `mosq_config_t` object 61 | * @param[in] client_type client types 62 | * 63 | * @return 64 | * - SC_OK on success 65 | * - non-zero on error 66 | */ 67 | status_t init_check_error(mosq_config_t *cfg, client_type_t client_type); 68 | 69 | #ifdef __cplusplus 70 | } 71 | #endif 72 | 73 | #endif // MQTT_PUB_UTILS_H_ 74 | -------------------------------------------------------------------------------- /connectivity/mqtt/sub_utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef MQTT_SUB_UTILS_H_ 10 | #define MQTT_SUB_UTILS_H_ 11 | 12 | #include "mqtt_common.h" 13 | #include "third_party/mosquitto/config.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file connectivity/mqtt/sub_utils.h 21 | * @brief MQTT subscriber utilities. 22 | */ 23 | 24 | /** 25 | * @brief Publish callback function of subscriber. 26 | * 27 | * when a message initiated with has been sent to the broker. This callback will be called both if 28 | * the message is sent successfully, or if the broker responded with an error, which will be reflected in the 29 | * reason_code parameter. 30 | */ 31 | void publish_callback_sub_func(struct mosquitto *mosq, void *obj, int mid, int reason_code, 32 | const mosquitto_property *properties); 33 | 34 | /** 35 | * @brief Connect callback function of subscriber. 36 | * 37 | * This callback function is called when a message is received from the broker. 38 | */ 39 | void message_callback_sub_func(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, 40 | const mosquitto_property *properties); 41 | 42 | /** 43 | * @brief Connect callback function of subscriber. 44 | * 45 | * This callback function is called when the broker sends a CONNACK message in response to a connection owned by 46 | * subscriber. 47 | */ 48 | void connect_callback_sub_func(struct mosquitto *mosq, void *obj, int result, int flags, 49 | const mosquitto_property *properties); 50 | 51 | /** 52 | * @brief Connect callback function of subscriber. 53 | * 54 | * This callback function is called when the broker responds to a subscription request. 55 | */ 56 | void subscribe_callback_sub_func(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos); 57 | 58 | #ifdef __cplusplus 59 | } 60 | #endif 61 | 62 | #endif // MQTT_SUB_UTILS_H_ 63 | -------------------------------------------------------------------------------- /connectivity/mqtt/usage.md: -------------------------------------------------------------------------------- 1 | # General Usage on MQTT Protocol support 2 | 3 | The format of MQTT request is the same as http request, but MQTT request has one more field is `Device ID`. 4 | 5 | ## Topic vs API table 6 | 7 | | topic | API | HTTP Method | 8 | | ------------- |:-------------: | -------------:| 9 | | tag/hashes | api_find_transactions_by_tag | GET | 10 | | tag/object | api_find_transactions_obj_by_tag | GET | 11 | | transaction | api_find_transaction_object_single | GET | 12 | | transaction/object | api_find_transaction_objects | POST | 13 | | transaction/send | api_send_transfer | POST | 14 | | tryte | api_send_trytes | POST | 15 | 16 | ## API request format 17 | 18 | APIs in POST method have almost the same format as MQTT requests have, there are one more field, `device_id` in MQTT requests. 19 | However, APIs in GET method would in a more different format, so the following are the examples of the requests of these APIs. 20 | 21 | ### api_find_transactions_by_tag 22 | 23 | ```json 24 | {"device_id":"", "tag":""} 25 | ``` 26 | 27 | ### api_find_transactions_obj_by_tag 28 | 29 | ```json 30 | {"device_id":"", "tag":""} 31 | ``` 32 | 33 | ### api_find_transaction_object_single 34 | 35 | ```json 36 | {"device_id":"", "hash":""} 37 | ``` 38 | 39 | ### api_find_transaction_objects 40 | 41 | ```json 42 | {"device_id":"", "hash":["", "", "..."]} 43 | ``` 44 | 45 | ### api_send_trytes 46 | 47 | ```json 48 | {"device_id":"", "trytes":""} 49 | ``` 50 | 51 | ## Examples 52 | 53 | Here is an example which uses mosquitto client to publish requests. 54 | 55 | ```bash 56 | $ mosquitto_pub -h -t root/topics/tag/hashes -m "{\"device_id\":\"\", \"tag\":\"\"}" 57 | ``` 58 | -------------------------------------------------------------------------------- /crypto/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "ecdh", 3 | srcs = ["ecdh.c"], 4 | hdrs = ["ecdh.h"], 5 | visibility = ["//visibility:public"], 6 | deps = [ 7 | "//common", 8 | "@mbedtls", 9 | ], 10 | ) 11 | -------------------------------------------------------------------------------- /crypto/ecdh.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #include "crypto/ecdh.h" 9 | 10 | #define ECDH_LOGGER "ecdh" 11 | static logger_id_t logger_id; 12 | 13 | void ecdh_logger_init() { logger_id = logger_helper_enable(ECDH_LOGGER, LOGGER_DEBUG, true); } 14 | 15 | int ecdh_logger_release() { 16 | logger_helper_release(logger_id); 17 | return 0; 18 | } 19 | 20 | status_t rand_gen_init(mbedtls_entropy_context *entropy, mbedtls_ctr_drbg_context *ctr_drbg, char *rand_seed, 21 | uint16_t seed_len) { 22 | int ret = 1; 23 | status_t sc = SC_OK; 24 | 25 | mbedtls_ctr_drbg_init(ctr_drbg); 26 | mbedtls_entropy_init(entropy); 27 | 28 | if ((ret = mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, entropy, (const unsigned char *)rand_seed, 29 | seed_len)) != 0) { 30 | ta_log_error("mbedtls_ctr_drbg_seed returned %d\n", ret); 31 | sc = SC_CRYPTO_RAND_ERR; 32 | } 33 | 34 | return sc; 35 | } 36 | 37 | status_t ecdh_gen_public_key(mbedtls_ecdh_context *ctx, mbedtls_ctr_drbg_context *ctr_drbg, unsigned char *pkey) { 38 | int ret = 1; 39 | status_t sc = SC_OK; 40 | 41 | ret = mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_CURVE25519); 42 | if (ret != 0) { 43 | ta_log_error("mbedtls_ecp_group_load returned %d\n", ret); 44 | sc = SC_CRYPTO_GENKEY_ERR; 45 | goto exit; 46 | } 47 | 48 | ret = mbedtls_ecdh_gen_public(&ctx->grp, &ctx->d, &ctx->Q, mbedtls_ctr_drbg_random, ctr_drbg); 49 | if (ret != 0) { 50 | ta_log_error("mbedtls_ecdh_gen_public returned %d\n", ret); 51 | sc = SC_CRYPTO_GENKEY_ERR; 52 | goto exit; 53 | } 54 | 55 | ret = mbedtls_mpi_write_binary(&ctx->Q.X, pkey, SHARE_DATA_LEN); 56 | if (ret != 0) { 57 | ta_log_error("mbedtls_mpi_write_binary returned %d\n", ret); 58 | sc = SC_CRYPTO_GENKEY_ERR; 59 | } 60 | 61 | exit: 62 | return sc; 63 | } 64 | 65 | status_t ecdh_compute_shared_secret(mbedtls_ecdh_context *ctx, mbedtls_ctr_drbg_context *ctr_drbg, 66 | unsigned char *input_shared_data) { 67 | int ret = 1; 68 | status_t sc = SC_OK; 69 | 70 | ret = mbedtls_mpi_lset(&ctx->Qp.Z, 1); 71 | if (ret != 0) { 72 | ta_log_error("mbedtls_mpi_lset returned %d\n", ret); 73 | sc = SC_CRYPTO_SECRET_ERR; 74 | goto exit; 75 | } 76 | 77 | ret = mbedtls_mpi_read_binary(&ctx->Qp.X, input_shared_data, SHARE_DATA_LEN); 78 | if (ret != 0) { 79 | ta_log_error("mbedtls_mpi_read_binary returned %d\n", ret); 80 | sc = SC_CRYPTO_SECRET_ERR; 81 | goto exit; 82 | } 83 | 84 | ret = mbedtls_ecdh_compute_shared(&ctx->grp, &ctx->z, &ctx->Qp, &ctx->d, mbedtls_ctr_drbg_random, ctr_drbg); 85 | if (ret != 0) { 86 | ta_log_error("mbedtls_ecdh_compute_shared returned %d\n", ret); 87 | sc = SC_CRYPTO_SECRET_ERR; 88 | } 89 | 90 | exit: 91 | return sc; 92 | } 93 | 94 | void rand_gen_release(mbedtls_entropy_context *entropy, mbedtls_ctr_drbg_context *ctr_drbg) { 95 | mbedtls_ctr_drbg_free(ctr_drbg); 96 | mbedtls_entropy_free(entropy); 97 | } 98 | -------------------------------------------------------------------------------- /crypto/ecdh.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef ECDH_COMMON_H 10 | #define ECDH_COMMON_H 11 | 12 | #include "common/logger.h" 13 | #include "common/ta_errors.h" 14 | #include "mbedtls/config.h" 15 | #include "mbedtls/ctr_drbg.h" 16 | #include "mbedtls/ecdh.h" 17 | #include "mbedtls/entropy.h" 18 | #include "mbedtls/platform.h" 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #define SHARE_DATA_LEN 32 25 | 26 | typedef struct rand_gen_s { 27 | mbedtls_entropy_context entropy; 28 | mbedtls_ctr_drbg_context ctr_drbg; 29 | } rand_gen_t; 30 | 31 | /** 32 | * @brief Initialize mbedtls random number generator 33 | * 34 | * @param[in] entropy Entropy contrext for randomess 35 | * @param[in] ctr_drbg Counter-mode block-cipher-based Deterministic Random Bit Generator object 36 | * @param[in] rand_seed Random seed for random number generator 37 | * @param[in] seed_len The length of random seed 38 | * 39 | * @return 40 | * - SC_OK on success 41 | * - non-zero on error 42 | */ 43 | status_t rand_gen_init(mbedtls_entropy_context *entropy, mbedtls_ctr_drbg_context *ctr_drbg, char *rand_seed, 44 | uint16_t seed_len); 45 | 46 | /** 47 | * @brief Initialize ECDH context and generate ECDH keypair 48 | * 49 | * @param[in] ctx ECDH context 50 | * @param[in] ctr_drbg Counter-mode block-cipher-based Deterministic Random Bit Generator object 51 | * @param[out] pkey Output public key which would be sent to counterpart 52 | * 53 | * @return 54 | * - SC_OK on success 55 | * - non-zero on error 56 | */ 57 | status_t ecdh_gen_public_key(mbedtls_ecdh_context *ctx, mbedtls_ctr_drbg_context *ctr_drbg, unsigned char *pkey); 58 | 59 | /** 60 | * @brief Compute the shared secret by Diffie–Hellman key exchange protocol 61 | * 62 | * @param[in] ctx ECDH context 63 | * @param[in] ctr_drbg Counter-mode block-cipher-based Deterministic Random Bit Generator object 64 | * @param[in] input_shared_data The public key sent by counterpart 65 | * 66 | * @return 67 | * - SC_OK on success 68 | * - non-zero on error 69 | */ 70 | status_t ecdh_compute_shared_secret(mbedtls_ecdh_context *ctx, mbedtls_ctr_drbg_context *ctr_drbg, 71 | unsigned char *input_shared_data); 72 | 73 | /** 74 | * @brief Release random number generator 75 | * 76 | * @param[in] entropy Entropy contrext for randomess 77 | * @param[in] ctr_drbg Counter-mode block-cipher-based Deterministic Random Bit Generator object 78 | * 79 | * @return 80 | * - SC_OK on success 81 | * - non-zero on error 82 | */ 83 | void rand_gen_release(mbedtls_entropy_context *entropy, mbedtls_ctr_drbg_context *ctr_drbg); 84 | 85 | #ifdef __cplusplus 86 | } 87 | #endif 88 | 89 | #endif // ECDH_COMMON_H 90 | -------------------------------------------------------------------------------- /docs/MAM-procedure.md: -------------------------------------------------------------------------------- 1 | # MAM Procedure 2 | 3 | Tangle-accelerator allows clients send MAM message and fetch MAM message through it. 4 | 5 | ## Channel Encryption 6 | 7 | Clients can encrypt a Channel in the first message they send to the Channel. All the messages under this Channel will be encrypted. This encryption system can serve as grouping different sets of subscribers. This encryption system, is based on the cryptographic algorithm provided by MAM, which are PSK and NTRU. 8 | 9 | ### PSK 10 | 11 | PSK is the abbreviation of Pre-Shared Key. It is a symmetric encryption algorithm. Subscribers share the same PSK keys have the same access authority for the messages on the MAM channel. 12 | However, the next Channel would not inherit the PSK keys in the last Channel. 13 | -------------------------------------------------------------------------------- /docs/OBD2-emulator.md: -------------------------------------------------------------------------------- 1 | # OBD2 emulator 2 | 3 | OBD2 emulator is a query server for endpoint OBDMonitor to get the vehicle response by the PID query on the CAN bus. 4 | The OBD2 emulator has been implemented according to the SAE standard. For more information. You can refer to [OBD-II PIDs](https://en.wikipedia.org/wiki/OBD-II_PIDs). 5 | 6 | ## How to build OBD2 emulator 7 | ``` 8 | bazel build //endpoint/OBDComp/emulator:obd-emulator 9 | ``` 10 | 11 | ## How to use OBD2 emulator 12 | 1. Confirm the virtual CAN driver has support. If virtual CAN is not available, you should re-configure the Linux kernel and build the corresponding image. 13 | ``` 14 | root@swi-mdm9x28-wp:~# zcat /proc/config.gz | grep VCAN 15 | CONFIG_CAN_VCAN=y 16 | ``` 17 | 2. Bring up CAN interface 18 | ``` 19 | ip link add dev vcan0 type vcan 20 | ifconfig vcan0 up 21 | ``` 22 | 3. Run the emulator 23 | ``` 24 | ./obd-emulator vcan0 25 | ``` 26 | -------------------------------------------------------------------------------- /docs/endpoint-platforms.md: -------------------------------------------------------------------------------- 1 | # Endpoint support platforms 2 | 3 | The following platforms are verified platforms of endpoint 4 | 5 | * simulator on x86_64 platform : The development platform for testing endpoint. 6 | * [AirPrime WP7702 LPWA Module](https://www.sierrawireless.com/products-and-solutions/embedded-solutions/products/wp7702/) : The product platform for endpoint. -------------------------------------------------------------------------------- /docs/endpoint-shell.md: -------------------------------------------------------------------------------- 1 | # Interactive shell for endpoint 2 | The Endpoint interactive shell is a diagnostic tool capable of executing specific commands to the device. The interactive shell had integrated some useful commands such as the test tool of radio connection, diagnostic commands of internet connection, AT command adapter and the test tool of TA transaction. 3 | 4 | # How to build and install endpoint shell 5 | First you need to install the leaf tool. See `docs/endpoint.md` 6 | Then build the shell app. 7 | ``` 8 | leaf shell 9 | mkapp -t wp77xx endpoint/shell.adef/ 10 | ``` 11 | Change the `wp77xx` for your specific target. 12 | Install shell app 13 | ``` 14 | update shell.wp77xx.update 15 | ``` 16 | Connect shell 17 | ``` 18 | sudo screen /dev/ttyUSB3 9600 19 | ``` 20 | You should check your specific ttyUSB interface. 21 | 22 | Use `help` to list all support commands. 23 | ``` 24 | > help 25 | ``` 26 | -------------------------------------------------------------------------------- /docs/permanode.md: -------------------------------------------------------------------------------- 1 | # Permanode 2 | 3 | The permanode solution is based on ScyllaDB, which is a NoSQL distributed database. `tangle-accelerator` implements a ScyllaDB backend to store the IOTA Tangle ledger and make it queriable. 4 | 5 | The ScyllaDB backend in `tangle-accelerator` supports the following APIs: 6 | 7 | - insert_transactions 8 | - get_trytes 9 | - find_transactions_by_bundle 10 | - find_transactions_by_address 11 | - find_transactions_by_tag 12 | - find_transactions_approvees 13 | - get_inclusion_status 14 | 15 | See [docs/build.md](docs/build.md) for more information about enabling the external storage. 16 | -------------------------------------------------------------------------------- /docs/reattacher.md: -------------------------------------------------------------------------------- 1 | # Transaction reattacher 2 | 3 | `Transaction reattacher` is a service that helps persistent pending transactions to be re-attached to the Tangle. A persistent transaction is a transaction that does not be confirmed more than 30 minutes. 4 | 5 | When enabling the external database for transaction reattachment, `Tangle-Accelerator` will store transactions issued by API [Send Transfer Message](https://github.com/DLTcollab/tangle-accelerator/wiki/Send-Transfer-Message). 6 | 7 | `Transaction reattacher` will periodically read pending transactions from a specific ScyllaDB cluster, and get the latest inclusion status of those transactions from an IOTA full node. `Reattacher` will update the newest inclusion status to the ScyllaDB cluster. For persistent transactions, `reattacher` performs reattachment, which will do tips selection and PoW for the original bundle, and reattach it to the Tangle. After reattachment, `reattacher` will update the new transaction hash to the ScyllaDB cluster. 8 | 9 | See [docs/build.md](docs/build.md) for more information about enabling transaction reattachment. 10 | 11 | ## Build Instructions 12 | 13 | `bazel build //reattacher` 14 | 15 | The reattacher support following options : 16 | 17 | * `DB_HOST`: binding address of ScyllDB cluster 18 | * `NODE_HOST`: binding address of IOTA full node 19 | * `NODE_PORT`: port of IOTA full node 20 | 21 | If you do not specify `DB_HOST` or `NODE_HOST`, the address will be set as `localhost`. 22 | -------------------------------------------------------------------------------- /docs/transaction-buffer.md: -------------------------------------------------------------------------------- 1 | # Transaction Buffer 2 | 3 | ## Introduction 4 | 5 | Failed transaction sending requests would be buffered in the redis server. 6 | 7 | ## Structure 8 | 9 | There are three lists used. 10 | 11 | ### 1. buffer list 12 | 13 | This list stores all the unsent failed requests. The key (name) of the list is stored in the `buffer_list_name` field of `ta_cache_t`object. 14 | Each element in this list is the UUID of the corresponding request. 15 | 16 | ### 2. done list 17 | 18 | This list stores all the sent failed requests. The key (name) of the list is stored in the `complete_list_name` field of `ta_cache_t`object. 19 | Each element in this list is the UUID of the corresponding request. 20 | 21 | ### 3. bundle list 22 | 23 | This list represents a bundle. In tangle-accelerator, we store each bundle generated by each request. A bundle in [`iota_common`](https://github.com/iotaledger/iota_common) is basically a list of transactions. Therefore, the data structure in the redis server is the same as the implementation in `iota_common`. It is a list of transaction objects in `flex_trit_t`, and the key (name) of this list is the UUID of the corresponding request. 24 | -------------------------------------------------------------------------------- /endpoint/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "endpoint_core", 5 | srcs = ["endpoint_core.c"], 6 | hdrs = [ 7 | "build/endpoint_generated.h", 8 | "endpoint_core.h", 9 | ], 10 | copts = [ 11 | "-Ibuild", 12 | ], 13 | defines = [ 14 | "EP_TA_HOST=localhost", 15 | "EP_TA_PORT=8000", 16 | "EP_SSL_SEED=nonce", 17 | ], 18 | visibility = ["//visibility:public"], 19 | deps = [ 20 | "//common:ta_errors", 21 | "//common:ta_logger", 22 | "//endpoint:cipher", 23 | "//endpoint:https", 24 | "//endpoint:text_serializer", 25 | "//utils:tryte_byte_conv", 26 | "@flatcc_0_6_0", 27 | ], 28 | ) 29 | 30 | cc_binary( 31 | name = "libendpoint.so", 32 | srcs = [ 33 | "endpoint_core.c", 34 | "endpoint_core.h", 35 | ], 36 | defines = [ 37 | "EP_TA_HOST=localhost", 38 | "EP_TA_PORT=8000", 39 | "EP_SSL_SEED=nonce", 40 | ], 41 | linkshared = True, 42 | deps = [ 43 | "//common:ta_errors", 44 | "//common:ta_logger", 45 | "//endpoint:cipher", 46 | "//endpoint:https", 47 | "//endpoint:text_serializer", 48 | "//utils:tryte_byte_conv", 49 | ], 50 | ) 51 | 52 | platform( 53 | name = "linux_arm", 54 | constraint_values = [ 55 | "@platforms//os:linux", 56 | # FIXME: The generic CPU name will be replaced in the future 57 | # ref: https://github.com/bazelbuild/platforms/blob/master/cpu/BUILD 58 | "@platforms//cpu:arm", 59 | ], 60 | ) 61 | 62 | cc_library( 63 | name = "cipher", 64 | srcs = ["cipher.c"], 65 | hdrs = ["cipher.h"], 66 | deps = [ 67 | "//common:ta_errors", 68 | "//common:ta_logger", 69 | "@mbedtls_2_16_6", 70 | ], 71 | ) 72 | 73 | cc_library( 74 | name = "https", 75 | srcs = ["https.c"], 76 | hdrs = ["https.h"], 77 | defines = select({ 78 | ":https_enable": ["ENDPOINT_HTTPS"], 79 | "//conditions:default": [], 80 | }), 81 | deps = [ 82 | "//common:ta_errors", 83 | "//endpoint/connectivity:conn_http", 84 | ], 85 | ) 86 | 87 | config_setting( 88 | name = "https_enable", 89 | values = {"define": "https=enable"}, 90 | ) 91 | 92 | cc_library( 93 | name = "text_serializer", 94 | srcs = ["text_serializer.c"], 95 | hdrs = ["text_serializer.h"], 96 | deps = [ 97 | ":cipher", 98 | "//common:ta_errors", 99 | "//common:ta_logger", 100 | ], 101 | ) 102 | -------------------------------------------------------------------------------- /endpoint/OBDComp/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "obd_pid", 5 | hdrs = ["obd_pid.h"], 6 | ) 7 | -------------------------------------------------------------------------------- /endpoint/OBDComp/can-bus/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "can-utils", 5 | srcs = ["can-utils.c"], 6 | hdrs = ["can-utils.h"], 7 | deps = [ 8 | "//common:ta_errors", 9 | ], 10 | ) 11 | -------------------------------------------------------------------------------- /endpoint/OBDComp/can-bus/can-utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "can-utils.h" 10 | 11 | // Linux headers 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include 18 | #include 19 | 20 | status_t can_open(char* dev, int* fd) { 21 | int s; 22 | struct sockaddr_can addr; 23 | struct ifreq ifr; 24 | status_t ret = SC_OK; 25 | if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { 26 | ret = SC_ENDPOINT_CAN_OPEN_ERROR; 27 | goto exit; 28 | } 29 | 30 | snprintf(ifr.ifr_name, IFNAMSIZ, "%s", dev); 31 | ioctl(s, SIOCGIFINDEX, &ifr); 32 | 33 | memset(&addr, 0, sizeof(addr)); 34 | addr.can_family = AF_CAN; 35 | addr.can_ifindex = ifr.ifr_ifindex; 36 | 37 | if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) { 38 | ret = SC_ENDPOINT_CAN_OPEN_ERROR; 39 | goto exit; 40 | } 41 | *fd = s; 42 | exit: 43 | if (ret != SC_OK) can_close(s); 44 | return ret; 45 | } 46 | 47 | status_t can_close(int fd) { 48 | if (close(fd) < 0) { 49 | return SC_ENDPOINT_CAN_CLOSE_ERROR; 50 | } 51 | return SC_OK; 52 | } 53 | 54 | status_t can_send(int fd, struct can_frame* frame) { 55 | if (write(fd, frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) { 56 | return SC_ENDPOINT_CAN_SEND_ERROR; 57 | } 58 | return SC_OK; 59 | } 60 | 61 | status_t can_recv(int fd, struct can_frame* frame) { 62 | if (read(fd, frame, sizeof(struct can_frame)) < 0) { 63 | return SC_ENDPOINT_CAN_RECV_ERROR; 64 | } 65 | return SC_OK; 66 | } 67 | -------------------------------------------------------------------------------- /endpoint/OBDComp/can-bus/can-utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef CAN_UTILS_H 10 | #define CAN_UTILS_H 11 | 12 | /** 13 | * @file endpoint/OBDComp/can-bus/can-utils.h 14 | */ 15 | 16 | #include "common/ta_errors.h" 17 | 18 | #include 19 | #include 20 | 21 | /** 22 | * @brief Open CAN BUS socket 23 | * 24 | * @param[in] dev CAN BUS device 25 | * @param[out] fd File descriptor 26 | * @return 27 | * - SC_OK on success 28 | * - SC_ENDPOINT_CAN_OPEN_ERROR on failed 29 | */ 30 | status_t can_open(char* dev, int* fd); 31 | 32 | /** 33 | * @brief Receive CAN BUS packet 34 | * 35 | * @param[in] fd File descriptor 36 | * @param[in] frame The buffer to store CAN BUS packet 37 | * @return 38 | * - SC_OK on success 39 | * - SC_ENDPOINT_CAN_RECV_ERROR on failed 40 | */ 41 | status_t can_recv(int fd, struct can_frame* frame); 42 | 43 | /** 44 | * @brief Send CAN BUS packet 45 | * 46 | * @param[in] fd File descriptor 47 | * @param[in] frame The CAN BUS packet to be sent 48 | * @return 49 | * - SC_OK on success 50 | * - SC_ENDPOINT_CAN_SEND_ERROR on failed 51 | */ 52 | status_t can_send(int fd, struct can_frame* frame); 53 | 54 | /** 55 | * @brief Close CAN BUS file descriptor 56 | * 57 | * @param[in] fd File descriptor 58 | * @return 59 | * - SC_OK on success 60 | * - SC_ENDPOINT_CAN_CLOSE_ERROR on failed 61 | */ 62 | status_t can_close(int fd); 63 | 64 | #endif // CAN_UTILS_H 65 | -------------------------------------------------------------------------------- /endpoint/OBDComp/emulator/BUILD: -------------------------------------------------------------------------------- 1 | cc_binary( 2 | name = "obd-emulator", 3 | srcs = [ 4 | "obd_emulator.c", 5 | "obd_emulator.h", 6 | ], 7 | deps = [ 8 | "//common:ta_errors", 9 | "//common:ta_logger", 10 | "//endpoint/OBDComp:obd_pid", 11 | "//endpoint/OBDComp/can-bus:can-utils", 12 | ], 13 | ) 14 | -------------------------------------------------------------------------------- /endpoint/OBDComp/emulator/obd_emulator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef OBD_EMULATOR_H 10 | #define OBD_EMULATOR_H 11 | 12 | #include 13 | 14 | /** 15 | * @file endpoint/OBDComp/emulator/obd_emulator.h 16 | */ 17 | 18 | // default can interface for obd emulator 19 | #define OBD_EMULATOR_INTERFACE "vcan0" 20 | #define OBD_EMULATOR_DEFAULT_VIN "1234567890ABCDEFG" 21 | #define OBD_EMULATOR_DEFAULT_VIN_LEN 17 22 | 23 | #define OBD_BROADCAST_ID 0x7DF 24 | #define OBD_FIRST_ECU_RESPONSE 0x7E8 25 | #define OBD_LAST_ECU_RESPONSE 0x7EF 26 | 27 | // An ECU responds to a message with an ID 8 less than the request 28 | // For example, the engine control unit responds with 0x7E0 (8 less than 0x7E8) 29 | #define OBD_REQUEST_RESPONSE_OFFSET 8 30 | 31 | enum OBD2_SERVICE { OBD2_SERVICE_01 = 0x01, OBD2_SERVICE_09 = 0x09 }; 32 | 33 | #endif // OBD_EMULATOR_H 34 | -------------------------------------------------------------------------------- /endpoint/OBDComp/emulator/script.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | SUDO=false 6 | if which sudo &>/dev/null; then 7 | SUDO=true 8 | fi 9 | 10 | # Bring up virtual CAN interface 11 | if [ "$SUDO" == true ]; then 12 | sudo ip link add dev vcan0 type vcan 13 | sudo ifconfig vcan0 up 14 | else 15 | ip link add dev vcan0 type vcan 16 | ifconfig vcan0 up 17 | fi 18 | 19 | if [[ $(ip link | grep vcan0) = 0 ]]; then 20 | echo "The virtual CAN interface is not activated" 21 | echo "Please check your kernel configuration" 22 | exit 1 23 | fi 24 | -------------------------------------------------------------------------------- /endpoint/OBDComp/endpointService/Component.cdef: -------------------------------------------------------------------------------- 1 | sources: 2 | { 3 | ${CURDIR}/../../endpoint_core.c 4 | 5 | // include the specific platform 6 | #if ${LEGATO_TARGET} = localhost 7 | ${CURDIR}/../../platform/simulator/impl.c 8 | #else 9 | ${CURDIR}/../../platform/legato-target/impl.c 10 | #endif 11 | 12 | ${CURDIR}/../../../output_base/external/org_iota_common/utils/logger_helper.c 13 | 14 | ${CURDIR}/../../../output_base/external/http_parser/http_parser.c 15 | 16 | ${CURDIR}/../../cipher.c 17 | ${CURDIR}/../../connectivity/conn_http.c 18 | ${CURDIR}/../../https.c 19 | ${CURDIR}/../../text_serializer.c 20 | ${CURDIR}/../../../utils/tryte_byte_conv.c 21 | 22 | endpoint_service.c 23 | } 24 | 25 | cflags: 26 | { 27 | -g -O0 28 | 29 | -I${CURDIR}/../../../ 30 | 31 | // The header files under this directory are downloaded only when the corresponding 'bazel build' command is used 32 | -I${CURDIR}/../../../output_base/execroot/__main__/bazel-out/k8-fastbuild/bin/external/org_iota_common 33 | 34 | -I${CURDIR}/../../../output_base/external/com_github_uthash/src 35 | -I${CURDIR}/../../../output_base/external/com_github_embear_logger/include 36 | -I${CURDIR}/../../../output_base/external/org_iota_common 37 | -I${CURDIR}/../../../output_base/external/http_parser 38 | -I${CURDIR}/../../../output_base/external/mbedtls_2_16_6/include 39 | } 40 | 41 | requires: 42 | { 43 | device: 44 | { 45 | [rw] /dev/ttyHS0 /dev/ttyHS0 46 | } 47 | 48 | api: 49 | { 50 | secStoreGlobal = le_secStore.api 51 | modemServices/le_sim.api 52 | modemServices/le_mdc.api 53 | le_data.api [manual-start] 54 | } 55 | } 56 | 57 | provides: 58 | { 59 | api: 60 | { 61 | endpoint.api 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /endpoint/OBDComp/endpointService/endpoint_service.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "endpoint_core.h" 14 | #include "legato.h" 15 | 16 | int endpoint_Send_mam_message(const char *host, const char *port, const char *ssl_seed, const char *mam_seed, 17 | const uint8_t *message, const size_t message_size, const uint8_t *private_key, 18 | const size_t private_keySize, const char *device_id) { 19 | LE_DEBUG("endpoint: message length: %zu\nsend mam message:%s", message_size, message); 20 | int ret = send_mam_message(host, port, ssl_seed, mam_seed, message, message_size, private_key, device_id); 21 | return ret; 22 | } 23 | 24 | COMPONENT_INIT {} 25 | -------------------------------------------------------------------------------- /endpoint/OBDComp/monitor/BUILD: -------------------------------------------------------------------------------- 1 | cc_binary( 2 | name = "monitor", 3 | srcs = [ 4 | "monitor.c", 5 | ], 6 | deps = [ 7 | "//common:ta_errors", 8 | "//endpoint/OBDComp:obd_pid", 9 | "//endpoint/OBDComp/can-bus:can-utils", 10 | ], 11 | ) 12 | -------------------------------------------------------------------------------- /endpoint/OBDComp/monitor/Component.cdef: -------------------------------------------------------------------------------- 1 | sources: 2 | { 3 | monitor.c 4 | ../can-bus/can-utils.c 5 | #if ${LEGATO_TARGET} = localhost 6 | ${CURDIR}/../../platform/simulator/impl.c 7 | #else 8 | ${CURDIR}/../../platform/legato-target/impl.c 9 | #endif 10 | } 11 | 12 | cflags: 13 | { 14 | -g -O0 15 | 16 | -I${CURDIR}/../../../ 17 | -I${CURDIR}/../../platform/ 18 | -I${CURDIR}/../can-bus/ 19 | } 20 | 21 | requires: 22 | { 23 | device: 24 | { 25 | [rw] /dev/ttyHS0 /dev/ttyHS0 26 | } 27 | 28 | api: 29 | { 30 | secStoreGlobal = le_secStore.api 31 | modemServices/le_sim.api 32 | modemServices/le_mdc.api 33 | le_data.api [manual-start] 34 | endpoint.api 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /endpoint/OBDMonitor.adef: -------------------------------------------------------------------------------- 1 | executables: 2 | { 3 | OBDService = ( OBDComp/monitor ) 4 | endpointService = ( OBDComp/endpointService ) 5 | } 6 | 7 | processes: 8 | { 9 | run: 10 | { 11 | (endpointService) 12 | } 13 | } 14 | 15 | sandboxed: true 16 | start: auto 17 | 18 | requires: 19 | { 20 | file: 21 | { 22 | // needed for curl itself: 23 | /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 24 | /usr/bin/curl /usr/bin/curl 25 | 26 | // needed for networking: 27 | /lib/libnss_compat.so.2 /lib/ 28 | /lib/libnss_files.so.2 /lib/ 29 | /lib/libnss_dns.so.2 /lib/ 30 | /lib/libresolv.so.2 /lib/ 31 | /etc/nsswitch.conf /etc/ 32 | /etc/hosts /etc/ 33 | /etc/resolv.conf /etc/ 34 | 35 | /bin/sh /bin/sh 36 | /bin/date /bin/date 37 | } 38 | } 39 | 40 | bindings: 41 | { 42 | OBDService.monitor.endpoint -> endpointService.endpointService.endpoint 43 | OBDService.monitor.secStoreGlobal -> secStore.secStoreGlobal 44 | OBDService.monitor.le_sim -> modemService.le_sim 45 | OBDService.monitor.le_mdc -> modemService.le_mdc 46 | OBDService.monitor.le_data -> dataConnectionService.le_data 47 | 48 | endpointService.endpointService.secStoreGlobal -> secStore.secStoreGlobal 49 | endpointService.endpointService.le_sim -> modemService.le_sim 50 | endpointService.endpointService.le_mdc -> modemService.le_mdc 51 | endpointService.endpointService.le_data -> dataConnectionService.le_data 52 | } 53 | 54 | extern: 55 | { 56 | endpointService.endpointService.endpoint 57 | } 58 | -------------------------------------------------------------------------------- /endpoint/build-legato.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -uo pipefail 4 | 5 | COMMON_FILE="tests/endpoint/common.sh" 6 | 7 | if [ ! -f "$COMMON_FILE" ]; then 8 | echo "$COMMON_FILE is not exists." 9 | echo "Always execute this script in top-level directory." 10 | exit 1 11 | fi 12 | source $COMMON_FILE 13 | 14 | if [ ! -d "legato" ]; then 15 | if ! download_legato_repo; then 16 | echo "Download Legato AF failed. Try to download again..." 17 | rm -rf legato/ .repo/ 18 | if ! download_legato_repo; then 19 | echo "Failed to download the Legato AF. Please check your connection" 20 | exit 1 21 | fi 22 | fi 23 | build_legato_repo 24 | fi 25 | -------------------------------------------------------------------------------- /endpoint/cipher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_CIPHER_H 10 | #define UTILS_CIPHER_H 11 | 12 | #include 13 | #include 14 | #include "common/ta_errors.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | /** 21 | * @file endpoint/cipher.h 22 | */ 23 | 24 | #define AES_BLOCK_SIZE 16 25 | #define AES_CBC_KEY_SIZE AES_BLOCK_SIZE * 2 26 | #define AES_IV_SIZE AES_BLOCK_SIZE 27 | #define IMSI_LEN 16 28 | #define TA_AES_KEY_BITS 256 29 | #define TA_AES_HMAC_SIZE AES_BLOCK_SIZE * 2 30 | 31 | /** context of aes cipher */ 32 | typedef struct ta_cipher_ctx { 33 | uint8_t* plaintext; /**< Plaintext */ 34 | size_t plaintext_len; /**< Plaintext length */ 35 | uint8_t* ciphertext; /**< Ciphertext */ 36 | size_t ciphertext_len; /**< Ciphertext length */ 37 | uint8_t iv[AES_IV_SIZE]; /**< Initialization vector, mbedtls_aes needs r/w iv[] */ 38 | const uint8_t* key; /**< Encryption key */ 39 | const size_t keybits; /**< Bits of key, valid options are 128,192,256 bits */ 40 | const char* device_id; /**< Device id */ 41 | uint8_t hmac[TA_AES_HMAC_SIZE]; /**< r/w buffer for hash-based message authentication code */ 42 | uint64_t timestamp; /**< Timestamp for generate hmac */ 43 | } ta_cipher_ctx; 44 | 45 | /** 46 | * @brief Initialize logger of cipher 47 | */ 48 | void cipher_logger_init(); 49 | 50 | /** 51 | * @brief Release logger of cipher 52 | * 53 | * @return 54 | * - zero on success 55 | * - EXIT_FAILURE on error 56 | */ 57 | int cipher_logger_release(); 58 | 59 | /** 60 | * @brief Encrypt plaintext 61 | * 62 | * @param[in] cipher_ctx The ta_cipher_ctx to be encrypted 63 | * 64 | * @return #status_t 65 | */ 66 | status_t aes_encrypt(ta_cipher_ctx* cipher_ctx); 67 | 68 | /** 69 | * @brief Decrypt ciphertext 70 | * 71 | * @param[in] cipher_ctx The ta_cipher_ctx to be decrypted 72 | * 73 | * @return #status_t 74 | */ 75 | status_t aes_decrypt(ta_cipher_ctx* cipher_ctx); 76 | 77 | #ifdef __cplusplus 78 | } 79 | #endif 80 | 81 | #endif // UTILS_CIPHER_H 82 | -------------------------------------------------------------------------------- /endpoint/connectivity/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "conn_http", 5 | srcs = ["conn_http.c"], 6 | hdrs = [ 7 | "conn_http.h", 8 | ], 9 | deps = [ 10 | "//common:ta_errors", 11 | "//common:ta_logger", 12 | "//pem:cert", 13 | "@http_parser", 14 | "@mbedtls_2_16_6", 15 | ], 16 | ) 17 | -------------------------------------------------------------------------------- /endpoint/diagnose.adef: -------------------------------------------------------------------------------- 1 | executables: 2 | { 3 | diagnose = ( diagnoseComp ) 4 | } 5 | 6 | processes: 7 | { 8 | run: 9 | { 10 | (diagnose) 11 | } 12 | } 13 | 14 | bindings: 15 | { 16 | diagnose.diagnoseComp.le_gnss -> positioningService.le_gnss 17 | diagnose.diagnoseComp.le_mrc -> modemService.le_mrc 18 | } 19 | 20 | start: manual 21 | -------------------------------------------------------------------------------- /endpoint/diagnoseComp/Component.cdef: -------------------------------------------------------------------------------- 1 | requires: 2 | { 3 | api: 4 | { 5 | modemServices/le_mrc.api 6 | positioning/le_gnss.api 7 | } 8 | } 9 | 10 | sources: 11 | { 12 | diagnose.c 13 | } 14 | 15 | cflags: 16 | { 17 | -g -O0 18 | } 19 | -------------------------------------------------------------------------------- /endpoint/diagnoseComp/diagnose.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "diagnose.h" 10 | 11 | #include "le_gnss_interface.h" 12 | #include "le_mrc_interface.h" 13 | 14 | static void hardware_logging(le_timer_Ref_t timer) { 15 | static char time_str[30]; 16 | static size_t copied_bytes = 0; 17 | static int32_t latitude = 0, longitude = 0, accuracy = 0; 18 | static uint32_t quality = 0; 19 | static le_gnss_SampleRef_t position_sample; 20 | static le_result_t result; 21 | 22 | // Signal strength 23 | result = le_mrc_GetSignalQual(&quality); 24 | switch (result) { 25 | case LE_OK: 26 | LE_INFO("Signal strength: %d\n", quality); 27 | break; 28 | default: 29 | LE_ERROR("Fail to get signal strength\n"); 30 | break; 31 | } 32 | 33 | // GPS 34 | position_sample = le_gnss_GetLastSampleRef(); 35 | result = le_gnss_GetLocation(position_sample, &latitude, &longitude, &accuracy); 36 | switch (result) { 37 | case LE_OK: 38 | LE_INFO("Latitude: %lf, Longitude: %lf, Horizontal accuracy: %d\n", (double)latitude / 1000000, 39 | (double)longitude / 1000000, accuracy); 40 | break; 41 | case LE_FAULT: 42 | LE_ERROR("Fail to get location data\n"); 43 | break; 44 | case LE_OUT_OF_RANGE: 45 | LE_ERROR("At least one retrieved value is invalid (set to INT32_MAX)\n"); 46 | LE_INFO("Latitude: %lf, Longitude: %lf, Horizontal accuracy: %d\n", (double)latitude / 1000000, 47 | (double)longitude / 1000000, accuracy); 48 | break; 49 | default: 50 | break; 51 | } 52 | 53 | // Time 54 | result = le_clk_GetLocalDateTimeString(LE_CLK_STRING_FORMAT_DATE_TIME, time_str, sizeof(time_str), &copied_bytes); 55 | switch (result) { 56 | case LE_OK: 57 | LE_INFO("Time: %s\n", time_str); 58 | break; 59 | case LE_OVERFLOW: 60 | LE_ERROR("Overflow of time string\n"); 61 | break; 62 | default: 63 | break; 64 | } 65 | } 66 | 67 | COMPONENT_INIT { 68 | le_timer_Ref_t timer; 69 | le_clk_Time_t interval = {3 /*sec*/, 0 /*usec*/}; 70 | le_gnss_State_t gnss_state; 71 | 72 | // GPS state checking and activation 73 | gnss_state = le_gnss_GetState(); 74 | if (gnss_state != LE_GNSS_STATE_ACTIVE) { 75 | le_gnss_Start(); 76 | le_gnss_Enable(); 77 | } 78 | 79 | // Timer for hardware logging 80 | timer = le_timer_Create("diagnose_timer"); 81 | le_timer_SetInterval(timer, interval); 82 | le_timer_SetRepeat(timer, 0); 83 | le_timer_SetHandler(timer, hardware_logging); 84 | le_timer_Start(timer); 85 | } 86 | -------------------------------------------------------------------------------- /endpoint/diagnoseComp/diagnose.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef DIAGNOSE_H 10 | #define DIAGNOSE_H 11 | 12 | #include "legato.h" 13 | 14 | /** 15 | * @file endpoint/diagnoseComp/diagnose.h 16 | */ 17 | 18 | /** 19 | * @brief Log the information from hardware 20 | * 21 | * @param[in] timer The timer of the function. It would be passed by the timer API le_timer_SetHandler(). 22 | */ 23 | static void hardware_logging(le_timer_Ref_t timer); 24 | 25 | #endif // DIAGNOSE_H 26 | -------------------------------------------------------------------------------- /endpoint/endpoint.adef: -------------------------------------------------------------------------------- 1 | executables: 2 | { 3 | endpoint = ( endpointComp ) 4 | } 5 | 6 | processes: 7 | { 8 | run: 9 | { 10 | (endpoint) 11 | } 12 | } 13 | 14 | requires: 15 | { 16 | file: 17 | { 18 | // needed for curl itself: 19 | /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 20 | /usr/bin/curl /usr/bin/curl 21 | 22 | // needed for networking: 23 | /lib/libnss_compat.so.2 /lib/ 24 | /lib/libnss_files.so.2 /lib/ 25 | /lib/libnss_dns.so.2 /lib/ 26 | /lib/libresolv.so.2 /lib/ 27 | /etc/nsswitch.conf /etc/ 28 | /etc/hosts /etc/ 29 | /etc/resolv.conf /etc/ 30 | 31 | /bin/sh /bin/sh 32 | /bin/date /bin/date 33 | } 34 | } 35 | 36 | #if ${LEGATO_TARGET} = localhost 37 | #else 38 | bindings: 39 | { 40 | endpoint.endpointComp.secStoreGlobal -> secStore.secStoreGlobal 41 | endpoint.endpointComp.le_sim -> modemService.le_sim 42 | endpoint.endpointComp.le_mdc -> modemService.le_mdc 43 | endpoint.endpointComp.le_data -> dataConnectionService.le_data 44 | } 45 | #endif 46 | sandboxed: false 47 | start: manual 48 | -------------------------------------------------------------------------------- /endpoint/endpoint.api: -------------------------------------------------------------------------------- 1 | DEFINE MAX_HOST_LENGTH = 64; 2 | DEFINE MAX_PORT_LENGTH = 64; 3 | DEFINE MAX_SSL_SEED_LENGTH = 1024; 4 | DEFINE MAM_SEED_LENGTH = 81; 5 | DEFINE MAX_MESSAGE_LENGTH = 4096; 6 | DEFINE PRIVATE_KEY_LENGTH = 32; 7 | DEFINE DEVICE_ID_LENGTH = 17; 8 | 9 | FUNCTION int32 Send_mam_message 10 | ( 11 | string host[MAX_HOST_LENGTH] IN, 12 | string port[MAX_PORT_LENGTH] IN, 13 | string ssl_seed[MAX_SSL_SEED_LENGTH] IN, 14 | string mam_seed[MAM_SEED_LENGTH] IN, 15 | uint8 message[MAX_MESSAGE_LENGTH] IN, 16 | uint8 private_key[PRIVATE_KEY_LENGTH] IN, 17 | string device_id[DEVICE_ID_LENGTH] IN 18 | ); 19 | -------------------------------------------------------------------------------- /endpoint/endpointComp/Component.cdef: -------------------------------------------------------------------------------- 1 | sources: 2 | { 3 | ${CURDIR}/../endpoint_core.c 4 | 5 | // include the specific platform 6 | #if ${LEGATO_TARGET} = localhost 7 | ${CURDIR}/../platform/simulator/impl.c 8 | #else 9 | ${CURDIR}/../platform/legato-target/impl.c 10 | #endif 11 | 12 | ${CURDIR}/../../output_base/external/org_iota_common/utils/logger_helper.c 13 | 14 | ${CURDIR}/../../output_base/external/http_parser/http_parser.c 15 | 16 | ${CURDIR}/../../endpoint/cipher.c 17 | ${CURDIR}/../../endpoint/connectivity/conn_http.c 18 | ${CURDIR}/../../endpoint/https.c 19 | ${CURDIR}/../../endpoint/text_serializer.c 20 | ${CURDIR}/../../utils/tryte_byte_conv.c 21 | 22 | endpoint.c 23 | } 24 | 25 | cflags: 26 | { 27 | -g -O0 28 | 29 | -I${CURDIR}/../.. 30 | 31 | // The header files under this directory are downloaded only when the corresponding 'bazel build' command is used 32 | -I${CURDIR}/../../output_base/execroot/__main__/bazel-out/k8-fastbuild/bin/external/org_iota_common 33 | 34 | -I${CURDIR}/../../output_base/external/com_github_uthash/src 35 | -I${CURDIR}/../../output_base/external/com_github_embear_logger/include 36 | -I${CURDIR}/../../output_base/external/org_iota_common 37 | -I${CURDIR}/../../output_base/external/http_parser 38 | -I${CURDIR}/../../output_base/external/mbedtls_2_16_6/include 39 | } 40 | 41 | #if ${LEGATO_TARGET} = localhost 42 | #else 43 | requires: 44 | { 45 | device: 46 | { 47 | [rw] /dev/ttyHS0 /dev/ttyHS0 48 | } 49 | 50 | api: 51 | { 52 | le_secStore.api 53 | modemServices/le_sim.api 54 | modemServices/le_mdc.api 55 | le_data.api [manual-start] 56 | } 57 | } 58 | #endif 59 | -------------------------------------------------------------------------------- /endpoint/endpointComp/endpoint.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef ENDPOINT_H 10 | #define ENDPOINT_H 11 | 12 | /** 13 | * @file endpoint/endpointComp/endpoint.h 14 | */ 15 | 16 | /** 17 | * @brief Print the help message of endpoint application 18 | */ 19 | static void print_help(void); 20 | 21 | #endif // ENDPOINT_H 22 | -------------------------------------------------------------------------------- /endpoint/endpoint_core.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef ENDPOINT_CORE_H 10 | #define ENDPOINT_CORE_H 11 | 12 | #define ADDR_LEN 81 13 | #define MAX_MSG_LEN 1024 14 | 15 | #include 16 | #include 17 | #include "common/ta_errors.h" 18 | 19 | /** 20 | * @file endpoint/endpoint_core.h 21 | */ 22 | 23 | /** 24 | * @brief Initialization of endpoint 25 | */ 26 | void endpoint_init(void); 27 | 28 | /** 29 | * @brief Destruction of endpoint 30 | */ 31 | void endpoint_destroy(void); 32 | 33 | /** 34 | * @brief Send transaction information to tangle accelerator 35 | * 36 | * @param[in] host The host of the tangle-accelerator 37 | * @param[in] port The port of the tangle-accelerator 38 | * @param[in] ssl_seed The random seed of the SSL configuration 39 | * @param[in] mam_seed Channel root seed. It is an 81-trytes string 40 | * @param[in] message Message payload of the MAM packet in ASCII 41 | * @param[in] private_key Private key from device 42 | * @param[in] device_id Device id from device 43 | * 44 | * @return #status_t 45 | */ 46 | status_t send_mam_message(const char* host, const char* port, const char* ssl_seed, const char* mam_seed, 47 | const uint8_t* message, const size_t msg_len, const uint8_t* private_key, 48 | const char* device_id); 49 | /** 50 | * @brief Resolve the server address name 51 | * 52 | * @param[in] host The domain name of the host 53 | * @param[out] result The buffer to store the IPV4 address output 54 | * @return #status_t 55 | */ 56 | status_t resolve_ip_address(const char* host, char* result); 57 | 58 | #endif // ENDPOINT_CORE_H 59 | -------------------------------------------------------------------------------- /endpoint/https.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_HTTPS_H 10 | #define UTILS_HTTPS_H 11 | 12 | #include 13 | #include "common/ta_errors.h" 14 | 15 | #ifdef __cplusplus 16 | extern "C" { 17 | #endif 18 | 19 | /** 20 | * @file endpoint/https.h 21 | */ 22 | 23 | /* struct type of HTTP(S) response */ 24 | typedef struct { 25 | char* buffer; /**< Message body **/ 26 | size_t len; /**< Length of message body */ 27 | } https_response_t; 28 | 29 | /* struct type of HTTP(S) context */ 30 | typedef struct { 31 | const char* host; /**< HTTP(S) host */ 32 | const int port; /**< HTTP(S) port */ 33 | const char* api; /**< API path for POST or GET request to HTTP(S) server, i.e "transaction/". It must be in string. */ 34 | const char* ssl_seed; /**< Seed for ssl connection. This column is optional. */ 35 | https_response_t* s_req; /**< [in] The message to send */ 36 | https_response_t* s_res; /**< [out] The message body of HTTP(S) response */ 37 | } https_ctx_t; 38 | 39 | /** 40 | * @brief Initialize logger of HTTP(S) 41 | */ 42 | void https_logger_init(); 43 | 44 | /** 45 | * @brief Release logger of https 46 | * 47 | * @return 48 | * - zero on success 49 | * - EXIT_FAILURE on error 50 | */ 51 | int https_logger_release(); 52 | 53 | /** 54 | * @brief Send a POST request message via HTTP(S) protocol 55 | * 56 | * @param[in, out] ctx The pointer points to http context 57 | * 58 | * @return #status_t 59 | */ 60 | status_t send_https_msg(https_ctx_t* ctx); 61 | 62 | #ifdef __cplusplus 63 | } 64 | #endif 65 | #endif // UTILS_HTTPS_H 66 | -------------------------------------------------------------------------------- /endpoint/platform/impl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #include 9 | #include 10 | #include "common/ta_errors.h" 11 | 12 | #include "interfaces.h" 13 | #include "legato.h" 14 | 15 | #define ENDPOINT_DEVICE_KEY_NAME "Device key" 16 | 17 | /** 18 | * @brief Set the device key 19 | * 20 | * @param[in] key The uint8_t array of the private key 21 | * @return 22 | * - SC_OK on success 23 | * - SC_ENDPOINT_SET_KEY_ERROR on error 24 | */ 25 | status_t set_device_key(const char *key); 26 | 27 | /** 28 | * @brief Get the device key 29 | * 30 | * @param[out] key The output array for the private key 31 | * @return 32 | * - SC_OK on success 33 | * - SC_ENDPOINT_GET_KEY_ERROR on error 34 | */ 35 | status_t get_device_key(uint8_t *key); 36 | 37 | /** 38 | * @brief Get the device id 39 | * 40 | * @param[out] id The output array for the device id 41 | * @return 42 | * - SC_OK on success 43 | * - SC_ENDPOINT_GET_DEVICE_ID_ERROR on error 44 | */ 45 | status_t get_device_id(char *id); 46 | -------------------------------------------------------------------------------- /endpoint/platform/legato-target/impl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "endpoint/platform/impl.h" 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include "endpoint/cipher.h" 21 | 22 | #include "legato.h" 23 | 24 | #include "interfaces.h" 25 | 26 | static le_sim_Id_t SimId; 27 | 28 | status_t set_device_key(const char *key) { 29 | if (key == NULL) { 30 | LE_ERROR("Failed to get key"); 31 | return SC_ENDPOINT_SET_KEY_ERROR; 32 | } 33 | 34 | uint8_t private_key[AES_CBC_KEY_SIZE] = {}; 35 | memcpy(private_key, key, AES_CBC_KEY_SIZE); 36 | 37 | le_result_t result = secStoreGlobal_Write(ENDPOINT_DEVICE_KEY_NAME, private_key, AES_CBC_KEY_SIZE); 38 | 39 | if (result != LE_OK) { 40 | LE_ERROR("Failed to set private key"); 41 | return SC_ENDPOINT_SET_KEY_ERROR; 42 | } 43 | return SC_OK; 44 | } 45 | 46 | status_t get_device_key(uint8_t *key) { 47 | if (key == NULL) { 48 | LE_ERROR("Failed to get key"); 49 | return SC_ENDPOINT_GET_KEY_ERROR; 50 | } 51 | 52 | size_t key_size = AES_CBC_KEY_SIZE; 53 | uint8_t private_key[AES_CBC_KEY_SIZE] = {}; 54 | 55 | le_result_t result = secStoreGlobal_Read(ENDPOINT_DEVICE_KEY_NAME, private_key, &key_size); 56 | 57 | switch (result) { 58 | case LE_OK: 59 | LE_DEBUG("Success to get device key"); 60 | return SC_OK; 61 | case LE_OVERFLOW: 62 | case LE_NOT_FOUND: 63 | case LE_UNAVAILABLE: 64 | case LE_FAULT: 65 | default: 66 | LE_ERROR("Failed to get device key"); 67 | return SC_ENDPOINT_GET_KEY_ERROR; 68 | } 69 | } 70 | 71 | static status_t cm_sim_GetSimImsi(char *sim_id) { 72 | char *imsi = sim_id; 73 | status_t ret = SC_OK; 74 | 75 | if (le_sim_GetIMSI(SimId, imsi, LE_SIM_IMSI_BYTES) != LE_OK) { 76 | imsi[0] = '\0'; 77 | ret = SC_ENDPOINT_GET_DEVICE_ID_ERROR; 78 | } 79 | 80 | return ret; 81 | } 82 | 83 | status_t get_device_id(char *device_id) { 84 | if (cm_sim_GetSimImsi(device_id) != SC_OK) { 85 | return SC_ENDPOINT_GET_DEVICE_ID_ERROR; 86 | } 87 | return SC_OK; 88 | } 89 | -------------------------------------------------------------------------------- /endpoint/shell.adef: -------------------------------------------------------------------------------- 1 | executables: 2 | { 3 | shell = ( shellComp ) 4 | } 5 | 6 | processes: 7 | { 8 | run: 9 | { 10 | (shell) 11 | } 12 | } 13 | 14 | bundles: 15 | { 16 | file: 17 | { 18 | 19 | #if file_exists($LEGATO_SYSROOT/usr/bin/ping) 20 | [rx] $LEGATO_SYSROOT/usr/bin/ping /bin/ 21 | #endif 22 | #if file_exists($LEGATO_SYSROOT/sbin/route) 23 | [rx] $LEGATO_SYSROOT/sbin/route /sbin/ 24 | #endif 25 | } 26 | } 27 | requires: 28 | { 29 | file: 30 | { 31 | // needed for curl: 32 | /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 33 | /usr/bin/curl /usr/bin/curl 34 | 35 | // needed for networking: 36 | /lib/libnss_compat.so.2 /lib/ 37 | /lib/libnss_files.so.2 /lib/ 38 | /lib/libnss_dns.so.2 /lib/ 39 | /lib/libresolv.so.2 /lib/ 40 | /etc/nsswitch.conf /etc/ 41 | /etc/hosts /etc/ 42 | /etc/resolv.conf /etc/ 43 | } 44 | 45 | device: 46 | { 47 | /dev/ttyHS0 /dev/ttyHS0 48 | /dev/ttyAT /dev/ttyAT 49 | } 50 | } 51 | 52 | bindings: 53 | { 54 | shell.shellComp.secStoreGlobal -> secStore.secStoreGlobal 55 | shell.shellComp.le_sim -> modemService.le_sim 56 | shell.shellComp.le_mdc -> modemService.le_mdc 57 | shell.shellComp.le_data -> dataConnectionService.le_data 58 | } 59 | 60 | start: auto 61 | sandboxed: false 62 | -------------------------------------------------------------------------------- /endpoint/shellComp/Component.cdef: -------------------------------------------------------------------------------- 1 | requires: 2 | { 3 | component: 4 | { 5 | ${LEGATO_ROOT}/components/3rdParty/curl 6 | } 7 | 8 | lib: 9 | { 10 | curl 11 | } 12 | 13 | api: 14 | { 15 | secStoreGlobal = le_secStore.api 16 | modemServices/le_sim.api 17 | modemServices/le_mdc.api 18 | le_data.api [manual-start] 19 | } 20 | } 21 | 22 | sources: 23 | { 24 | shell.c 25 | #if ${LEGATO_TARGET} = localhost 26 | ${CURDIR}/../platform/simulator/impl.c 27 | #else 28 | ${CURDIR}/../platform/legato-target/impl.c 29 | #endif 30 | ${CURDIR}/../../output_base/external/org_iota_common/utils/logger_helper.c 31 | 32 | } 33 | 34 | cflags: 35 | { 36 | -g -O0 37 | -lcurl 38 | 39 | -I${CURDIR}/../.. 40 | // The header files under this directory are downloaded only when the corresponding 'bazel build' command is used 41 | -I${CURDIR}/../../output_base/execroot/__main__/bazel-out/k8-fastbuild/bin/external/org_iota_common 42 | 43 | -I${CURDIR}/../../output_base/external/com_github_uthash/src 44 | -I${CURDIR}/../../output_base/external/com_github_embear_logger/include 45 | -I${CURDIR}/../../output_base/external/org_iota_common 46 | } 47 | -------------------------------------------------------------------------------- /endpoint/shellComp/shell.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef SHELL_H 10 | #define SHELL_H 11 | 12 | /** 13 | * @file endpoint/shellComp/shell.h 14 | */ 15 | 16 | #define SHELL_USING_DEVICE "/dev/ttyHS0" 17 | #define ATCMD_USING_DEVICE "/dev/ttyAT" 18 | #define UART_BAUDRATE B9600 19 | #define AT_BAUDRATE B115200 20 | 21 | typedef struct { 22 | char* name; 23 | char* desc; 24 | int (*cmd)(char**); 25 | } command; 26 | 27 | #endif // SHELL_H 28 | -------------------------------------------------------------------------------- /endpoint/tests/regression/BUILD: -------------------------------------------------------------------------------- 1 | cc_test( 2 | name = "test_http", 3 | srcs = [ 4 | "test_http.c", 5 | ], 6 | deps = [ 7 | "//endpoint:https", 8 | "//endpoint/connectivity:conn_http", 9 | "//tests:logger_lib", 10 | "//tests:test_define", 11 | ], 12 | ) 13 | -------------------------------------------------------------------------------- /endpoint/tests/regression/driver.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [ "$#" -ne 3 ]; then 4 | echo "Usage: ./driver.sh [NODE_HOST] [NODE_PORT] [TEST_TA_PORT]" >&2 5 | exit 1 6 | fi 7 | 8 | IOTA_NODE=$1 9 | IOTA_PORT=$2 10 | TEST_TA_PORT=$3 11 | 12 | set -uo pipefail 13 | RED='\033[0;31m' 14 | GREEN='\033[0;32m' 15 | NC='\033[0m' # No Color 16 | EP_TEST_CONFIG=(asan tsan ubsan) 17 | 18 | function cleanup() { 19 | kill -9 "${TA}" 20 | } 21 | 22 | function success() { 23 | cleanup 24 | echo -e "${GREEN}ALL test passed${NC}" 25 | exit 0 26 | } 27 | 28 | function failed() { 29 | cleanup 30 | echo -e "${RED}Unit-test: ${TEST_CASE} not passed${NC}" 31 | exit 1 32 | } 33 | 34 | function run_test_suite() { 35 | bazel test -c dbg --config "$1" //endpoint/tests/regression/... --test_arg=localhost --test_arg="$TEST_TA_PORT" 36 | ret=$? 37 | if [[ ret -ne 0 ]]; then 38 | TEST_CASE="$1" 39 | failed 40 | fi 41 | } 42 | 43 | function start_ta() { 44 | # Create tangle-accelerator for unit-test 45 | bazel run //accelerator -- --ta_port="$TEST_TA_PORT" --node_host="$IOTA_NODE" --node_port="$IOTA_PORT" --cache=on & 46 | TA=$! 47 | # Wait until tangle-accelerator has been initialized 48 | echo "==============Wait for TA starting==============" 49 | while read -r line; do 50 | if [[ "$line" == "TA-START" ]]; then 51 | echo "$line" 52 | fi 53 | done <<<$(nc -U -l $socket | tr '\0' '\n') 54 | echo "==============TA has successfully started==============" 55 | } 56 | 57 | echo "Start unit-test for endpoint" 58 | start_ta 59 | 60 | # Run endpoint unit-test 61 | for i in ${EP_TEST_CONFIG[*]}; do 62 | run_test_suite "$i" 63 | done 64 | 65 | # Finish 66 | success 67 | -------------------------------------------------------------------------------- /endpoint/tests/regression/test_http.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "common/ta_errors.h" 4 | #include "endpoint/connectivity/conn_http.h" 5 | #include "endpoint/https.h" 6 | #include "http_parser.h" 7 | #include "tests/test_define.h" 8 | 9 | static char* TEST_TA_HOST; 10 | static char* TEST_TA_PORT; 11 | 12 | #define TEST_GET_REQUEST "GET /address HTTP/1.1\r\nHOST: %s\r\n\r\n" 13 | #define TEST_API "transaction/" 14 | 15 | #define TEST_POST_MESSAGE \ 16 | "{\ 17 | \"value\": 0,\ 18 | \"message\": \"ZBCDKDTCFDTCSCEAQCMDEAHDPCBDVC9DTCRAPCRCRCTC9DTCFDPCHDCDFD\",\ 19 | \"tag\": \"POWEREDBYTANGLEACCELERATOR9\",\ 20 | \"address\": \"POWEREDBYTANGLEACCELERATOR9999999999999999999999999999999999999999999999999999999\"\ 21 | }" 22 | 23 | #define POST_REQUEST \ 24 | "POST /transaction/ HTTP/1.1\r\n\ 25 | Host: %s:%d\r\n\ 26 | Connection: Keep-Alive\r\n\ 27 | Content-Type: application/json\r\n\ 28 | Content-Length: 224\r\n\ 29 | \r\n\ 30 | " TEST_POST_MESSAGE "\r\n\r\n" 31 | 32 | #define BUF_SIZE 4096 33 | 34 | static char* req = NULL; 35 | static https_response_t my_data; 36 | 37 | void setUp(void) { conn_http_logger_init(); } 38 | 39 | void tearDown(void) { 40 | conn_http_logger_release(); 41 | free(my_data.buffer); 42 | free(req); 43 | } 44 | 45 | void test_http(void) { 46 | connect_info_t info = {.https = false}; 47 | char post_message[BUF_SIZE] = {0}, response[BUF_SIZE] = {0}; 48 | char post_request[BUF_SIZE] = {0}; 49 | http_parser parser; 50 | http_parser_settings settings = {}; 51 | parser.data = &my_data; 52 | 53 | snprintf(post_message, BUF_SIZE, "%s", TEST_POST_MESSAGE); 54 | 55 | set_post_request(TEST_API, TEST_TA_HOST, atoi(TEST_TA_PORT), post_message, &req); 56 | snprintf(post_request, BUF_SIZE, POST_REQUEST, TEST_TA_HOST, atoi(TEST_TA_PORT)); 57 | TEST_ASSERT_EQUAL_INT8_ARRAY(post_request, req, sizeof(POST_REQUEST)); 58 | 59 | TEST_ASSERT_EQUAL_INT(SC_OK, http_open(&info, "nonce", TEST_TA_HOST, TEST_TA_PORT)); 60 | TEST_ASSERT_EQUAL_INT(SC_OK, http_send_request(&info, req)); 61 | TEST_ASSERT_EQUAL_INT(SC_OK, http_read_response(&info, response, sizeof(response) / sizeof(char))); 62 | TEST_ASSERT_EQUAL_INT(SC_OK, http_close(&info)); 63 | 64 | http_parser_init(&parser, HTTP_RESPONSE); 65 | http_parser_execute(&parser, &settings, response, strlen(response)); 66 | 67 | TEST_ASSERT_EQUAL_INT(SC_HTTP_OK, parser.status_code); 68 | } 69 | 70 | int main(int argc, char** argv) { 71 | UNITY_BEGIN(); 72 | if (argc != 3) { 73 | printf("usage: ./test_endpoint_core [TA_HOST] [TA_PORT]"); 74 | return UNITY_END(); 75 | } 76 | 77 | TEST_TA_HOST = argv[1]; 78 | TEST_TA_PORT = argv[2]; 79 | 80 | if (ta_logger_init() != SC_OK) { 81 | return EXIT_FAILURE; 82 | } 83 | 84 | RUN_TEST(test_http); 85 | 86 | return UNITY_END(); 87 | } 88 | -------------------------------------------------------------------------------- /endpoint/tests/unit-test/BUILD: -------------------------------------------------------------------------------- 1 | cc_test( 2 | name = "test_text_serializer", 3 | srcs = [ 4 | "test_text_serializer.c", 5 | ], 6 | deps = [ 7 | "//endpoint:cipher", 8 | "//endpoint:text_serializer", 9 | "//tests:logger_lib", 10 | "//tests:test_define", 11 | ], 12 | ) 13 | 14 | cc_test( 15 | name = "test_cipher", 16 | srcs = [ 17 | "test_cipher.c", 18 | ], 19 | deps = [ 20 | "//endpoint:cipher", 21 | "//tests:logger_lib", 22 | "//tests:test_define", 23 | ], 24 | ) 25 | -------------------------------------------------------------------------------- /endpoint/text_serializer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_TEXT_SERIALIZER_H 10 | #define UTILS_TEXT_SERIALIZER_H 11 | 12 | #include 13 | #include 14 | #include "common/ta_errors.h" 15 | #include "endpoint/cipher.h" 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | /** 22 | * @file endpoint/text_serializer.h 23 | */ 24 | 25 | /** 26 | * @brief Initialize logger of text serializer 27 | */ 28 | void text_serializer_logger_init(); 29 | 30 | /** 31 | * @brief Release logger of text serializer 32 | * 33 | * @return 34 | * - zero on success 35 | * - EXIT_FAILURE on error 36 | */ 37 | int text_serialize_logger_release(); 38 | 39 | /** 40 | * @brief Serialize ciphertext and initialize vector together, the out put message 41 | * format show as below: 42 | * - initialize vector(16 bytes) 43 | * - timestamp (20 bytes) 44 | * - hmac (32 bytes) 45 | * - ciphertext length(10 bytes) 46 | * - ciphertext(other bytes) 47 | * 48 | * @param[in] ctx The cipher context to be serialized 49 | * @param[out] out_msg Pointer to output message 50 | * @param[out] out_msg_len Pointer to length of serialized message 51 | * 52 | * @return 53 | * - SC_OK on success 54 | * - SC_UTILS_TEXT_SERIALIZE on error 55 | */ 56 | status_t serialize_msg(const ta_cipher_ctx *ctx, char *out_msg, size_t *out_msg_len); 57 | 58 | /** 59 | * @brief Deserialize message from serialize_msg 60 | * 61 | * @param[in] msg Pointer to serialize message 62 | * @param[in,out] ctx The cipher context to be deserialized 63 | * 64 | * @return 65 | * - SC_OK on success 66 | * - SC_UTILS_TEXT_DESERIALIZE on error 67 | * @see #serialize_msg 68 | */ 69 | status_t deserialize_msg(const char *msg, ta_cipher_ctx *ctx); 70 | #ifdef __cplusplus 71 | } 72 | #endif 73 | #endif // UTILS_TEXT_SERIALIZER_H 74 | -------------------------------------------------------------------------------- /hooks/buildifier: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | buildifier -showlog -mode=fix $(find $(git rev-parse --show-toplevel) | grep -E "WORKSPACE|BUILD(\.(bazel|bzl))?\$") 4 | -------------------------------------------------------------------------------- /hooks/ci_buildifier_check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | buildifier -mode=check $(find . -type f | grep -E "WORKSPACE|BUILD(\.(bazel|bzl))?\$" | egrep -v -f hooks/format-exclude-list) 4 | -------------------------------------------------------------------------------- /hooks/ci_format_check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | root=$(git rev-parse --show-toplevel) 4 | status=0 5 | for file in $(find "${@}" -type f | grep -E "\.(c|cc|cpp|h|hh|hpp)\$" | grep -Ev "/third_party/"); do 6 | filepath="$root/$file" 7 | output=$(diff <(cat $filepath) <(clang-format -style=file -fallback-style=none $filepath)) 8 | if [ $? -ne 0 ]; then 9 | echo -e "\nFile \e[31m\""$file"\"\e[39m is not compliant with the coding style" 10 | echo "$output" 11 | status=1 12 | fi 13 | done 14 | exit $status 15 | -------------------------------------------------------------------------------- /hooks/format-exclude-list: -------------------------------------------------------------------------------- 1 | third_party 2 | output_base 3 | legato 4 | _build_endpoint 5 | -------------------------------------------------------------------------------- /hooks/formatter: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | for file in $(find $(git rev-parse --show-toplevel) | egrep "\.(c|cc|cpp|h|hh|hpp|m|mm)\$" | egrep -v -f hooks/format-exclude-list); do 4 | clang-format -style=file -fallback-style=none -i $file 5 | done 6 | 7 | for file in $(find $(git rev-parse --show-toplevel) | egrep "\BUILD\$" | egrep -v -f hooks/format-exclude-list); do 8 | buildifier $file 9 | done 10 | buildifier WORKSPACE 11 | 12 | for file in $(find $(git rev-parse --show-toplevel) | egrep "\.sh\$" | egrep -v -f hooks/format-exclude-list); do 13 | shfmt -w $file 14 | done 15 | -------------------------------------------------------------------------------- /hooks/pre-commit/01-buildifier-check: -------------------------------------------------------------------------------- 1 | ../scripts/buildifier_check -------------------------------------------------------------------------------- /hooks/pre-commit/02-format-check: -------------------------------------------------------------------------------- 1 | ../scripts/format_check -------------------------------------------------------------------------------- /hooks/pre-commit/03-function-check: -------------------------------------------------------------------------------- 1 | ../scripts/function_check -------------------------------------------------------------------------------- /hooks/scripts/buildifier_check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | buildifier -mode=check $(git ls-files $(git rev-parse --show-toplevel) | grep -E "WORKSPACE|BUILD(\.(bazel|bzl))?\$") 4 | -------------------------------------------------------------------------------- /hooks/scripts/format_check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | root=$(git rev-parse --show-toplevel) 4 | status=0 5 | for file in $(git diff --staged --name-only | grep -E "\.(c|cc|cpp|h|hh|hpp)\$"); do 6 | filepath="$root/$file" 7 | output=$(diff <(cat $filepath) <(clang-format -style=file -fallback-style=none $filepath)) 8 | if [ $? -ne 0 ]; then 9 | echo -e "\nFile \""$file"\" is not compliant with the coding style" 10 | echo "$output" 11 | status=1 12 | fi 13 | done 14 | exit $status 15 | -------------------------------------------------------------------------------- /hooks/scripts/function_check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | root=$(git rev-parse --show-toplevel) 4 | banned="([^f]gets\()|(sprintf\()|(strcpy\()" 5 | status=0 6 | for file in $(git diff --staged --name-only | grep -E "\.(c|cc|cpp|h|hh|hpp)\$"); do 7 | filepath="${root}/${file}" 8 | output=$(grep -nrE "${banned}" "${filepath}") 9 | if [ ! -z "${output}" ]; then 10 | echo "Dangerous function detected in ${filepath}" 11 | echo "${output}" 12 | status=1 13 | fi 14 | done 15 | exit $status 16 | -------------------------------------------------------------------------------- /hooks/toolchains.rc: -------------------------------------------------------------------------------- 1 | 2 | build:aarch64 --crosstool_top=@iota_toolchains//tools/aarch64--glibc--bleeding-edge-2018.07-1:toolchain 3 | build:aarch64 --cpu=aarch64 4 | build:aarch64 --host_crosstool_top=@bazel_tools//tools/cpp:toolchain 5 | 6 | build:armv7 --crosstool_top=@iota_toolchains//tools/armv7-eabihf--glibc--bleeding-edge-2018.07-1:toolchain 7 | build:armv7 --cpu=armeabi-v7a 8 | build:armv7 --host_crosstool_top=@bazel_tools//tools/cpp:toolchain 9 | 10 | build:i686 --crosstool_top=@iota_toolchains//tools/x86-i686--glibc--bleeding-edge-2018.07-1:toolchain 11 | build:i686 --cpu=i686 12 | build:i686 --host_crosstool_top=@bazel_tools//tools/cpp:toolchain 13 | 14 | build:x86_64 --crosstool_top=@iota_toolchains//tools/x86-64-core-i7--glibc--bleeding-edge-2018.07-1:toolchain 15 | build:x86_64 --cpu=x86_64 16 | build:x86_64 --host_crosstool_top=@bazel_tools//tools/cpp:toolchain 17 | 18 | build:emscripten --crosstool_top=@iota_toolchains//tools/emscripten:toolchain 19 | build:emscripten --cpu=emscripten 20 | build:emscripten --host_crosstool_top=@bazel_tools//tools/cpp:toolchain 21 | -------------------------------------------------------------------------------- /pem/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "cert", 5 | hdrs = ["ca_crt.inc"], 6 | ) 7 | -------------------------------------------------------------------------------- /pem/README.md: -------------------------------------------------------------------------------- 1 | # Certificate Authority 2 | 3 | Don't edit files inside this directory.The cert.pem and the key.pem is only for the build system. 4 | To use the customized certificate, build the system with macro `make PEM=/path/to/cert.pem` instead. 5 | -------------------------------------------------------------------------------- /pem/cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFSTCCAzGgAwIBAgIUUQNsnBOMlO9Qm3KUHj+hMl2ReEwwDQYJKoZIhvcNAQEL 3 | BQAwNDELMAkGA1UEBhMCVFcxEzARBgNVBAgMClNvbWUtU3RhdGUxEDAOBgNVBAoM 4 | B0JpaWxhYnMwHhcNMjAwNDI3MDMzNTM4WhcNMjAwNTI3MDMzNTM4WjA0MQswCQYD 5 | VQQGEwJUVzETMBEGA1UECAwKU29tZS1TdGF0ZTEQMA4GA1UECgwHQmlpbGFiczCC 6 | AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAM9catWM0Qs9QvnPazGCRfD0 7 | /Hfv4IO8ObUIDCxR0tOm2NDW517UnuBqb5Gl1a34/t1CzgYWNkhcCPrJvO3xiVs3 8 | HnCD68jAAuwHE/84FsKMtTkXZ7e+5sFeIpok8iely5UH8dDYYBDVVx7/dWJLRZqK 9 | /Py3cdEz72aqzhbZFQErLzsw9qUuPREFTZFj0H2y45/hq61AM2Df3o2ELMWtVVus 10 | c7zcttNoul+hpuRSDfV2RuozeRO0NmVrh+6Hzb8nCBrHMuHNuDwh60Ji2XYsoWQS 11 | LYy5l8Pt6tfyo2UCR5wrJ21ttxFzD0i9Gs9zDH6fhMXyrxcJZDOSaJ+J//WGCj/O 12 | JsWx61eiNWgV5COIWBCqaOZfna3AusHQNWci4jYa0/1lhbig+xxpGxo+7LewCedU 13 | bOZO1ce6d+Sek7tdX3tliDehHJN63KTCQMeCtg8YUcb4hYf/kjRAZ4NMVB63ZBA2 14 | d9T1ZkAfBQh18IX7CxZt+ye6ixYtTDxOjKCcmiUoyztXfp5LwKHyTZ0pHukCPUp7 15 | qoT6L/HksKhjyS2V6ELFxn6dqKCZ010jgG1K1QfrCwqlVPbhzCLXcv5/N40g/KIa 16 | VTBMty4MwTBdSVf9QbYo6haQy4YAWP47OdH4Ef3J4xe4YnRFzOGajBeRV7EVOoJ4 17 | E2op4JIxcMRkd7GqPd5BAgMBAAGjUzBRMB0GA1UdDgQWBBRP4RwMH69jTnyWW8N3 18 | t2hizlCUwTAfBgNVHSMEGDAWgBRP4RwMH69jTnyWW8N3t2hizlCUwTAPBgNVHRMB 19 | Af8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQArKZ1ZnVLWqcGESdeJfw7EoQI4 20 | agl4Yz70pZg6AHnNNSdJfAUFN6Z4PWJADU13S26GGTcMAS3vJJ2SEfd34FmvLPZi 21 | 8nLw3mgK31xy35PH3DukWzlqlHEPaK/R77h3TtCKuI89B+1h0rzIya/lTtn4M+iK 22 | duZvDXLbzy960WEIREzZTj1LgHvsd/y7jLmD3Yab5ZnvsVE3dhGpOwqGCl1ZMITX 23 | bNDHsAK3kns/icbZBALGYrGc8n0FrgyzdjqZfuIBUyA/3AGom+ze/nMoDVTa88iX 24 | eF3LZP1Xs6NKrHZVy8AIPMxt3m6d+jquv0A/4ujcIbe/BA5646iwks5QMJklgCI5 25 | zdxhPFu/4eGdoZ64GxKCPobL1B8OErKWeklRdkgUOY1239CJCuzMjGTzQfaFRRpl 26 | TJEz8NSk4LQGjdQ759DIxFy/wXg7SuX2XUGMfPPNwOO9MucEC7eCZEH45puN1ffc 27 | +VckbEbwqP0RwEFKdOX5HpaRDcSVaEL/pEN2EpRDUvQo0KL1LMALnT0Y6FKUgDpZ 28 | 0icAMuUkgYOHzL2WTBj6pRdR2zU/+RCdjdcvvTSgpX42cI5BQnaPkIALGzexmtm/ 29 | srbMmDGCpAbIAn0RhUllGu3PCWh6OWPhjHhNgI1INzIIrGnBXsf7BqAmRVWE1jwJ 30 | fSbGqNJpCmB6KR4axg== 31 | -----END CERTIFICATE----- 32 | -------------------------------------------------------------------------------- /reattacher/BUILD: -------------------------------------------------------------------------------- 1 | cc_binary( 2 | name = "reattacher", 3 | srcs = ["reattacher_main.c"], 4 | deps = [ 5 | "//accelerator:ta_config", 6 | "//storage", 7 | "@iota.c//cclient/api", 8 | ], 9 | ) 10 | -------------------------------------------------------------------------------- /storage/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "storage", 3 | hdrs = ["ta_storage.h"], 4 | visibility = ["//visibility:public"], 5 | deps = [ 6 | ":scylladb_identity", 7 | ":scylladb_permanode", 8 | ], 9 | ) 10 | 11 | cc_library( 12 | name = "scylladb_identity", 13 | srcs = ["scylladb_identity.c"], 14 | hdrs = ["scylladb_identity.h"], 15 | linkopts = ["-lcassandra"], 16 | deps = [ 17 | ":scylladb_client", 18 | "@com_github_uthash//:uthash", 19 | ], 20 | ) 21 | 22 | cc_library( 23 | name = "scylladb_client", 24 | srcs = ["scylladb_client.c"], 25 | hdrs = [ 26 | "scylladb_client.h", 27 | ], 28 | linkopts = [ 29 | "-lcassandra", 30 | ], 31 | deps = [ 32 | ":scylladb_utils", 33 | ], 34 | ) 35 | 36 | cc_library( 37 | name = "scylladb_permanode", 38 | srcs = ["scylladb_permanode.c"], 39 | hdrs = ["scylladb_permanode.h"], 40 | linkopts = ["-lcassandra"], 41 | deps = [ 42 | ":scylladb_client", 43 | "@com_github_uthash//:uthash", 44 | "@iota.c//cclient/request:requests", 45 | "@iota.c//cclient/response:responses", 46 | "@org_iota_common//utils/containers/hash:hash243_queue", 47 | "@org_iota_common//utils/containers/hash:hash8019_queue", 48 | ], 49 | ) 50 | 51 | cc_library( 52 | name = "scylladb_utils", 53 | srcs = ["scylladb_utils.c"], 54 | hdrs = ["scylladb_utils.h"], 55 | linkopts = ["-lcassandra"], 56 | deps = [ 57 | "//common", 58 | "@org_iota_common//common/model:bundle", 59 | ], 60 | ) 61 | -------------------------------------------------------------------------------- /storage/scylladb_client.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #ifndef STORAGE_SCYLLADB_CLIENT_H_ 9 | #define STORAGE_SCYLLADB_CLIENT_H_ 10 | #ifdef __cplusplus 11 | extern "C" { 12 | #endif 13 | 14 | #include "scylladb_utils.h" 15 | 16 | /** 17 | * @file storage/scylladb_client.h 18 | * @brief ScyllaDB client service for connection and executing queries. 19 | */ 20 | 21 | #define DB_UUID_STRING_LENGTH CASS_UUID_STRING_LENGTH 22 | 23 | /* 24 | * DB_USAGE_NULL is for non-preserved usage and user-defined keyspace. 25 | * Call db_init_identity_keyspace to give the keyspace name. 26 | * This method could be enhanced by supporting user-defined keyspace name when 27 | * specific the preserved usage. 28 | */ 29 | typedef enum { DB_USAGE_REATTACH = 0, DB_USAGE_PERMANODE, DB_USAGE_NULL, NUM_DB_USAGE } db_client_usage_t; 30 | typedef struct { 31 | CassCluster* cluster; 32 | CassSession* session; 33 | char* host; 34 | /**< CassUuidGen is a UUID generator object, which is thread-safe to generate UUIDs */ 35 | CassUuidGen* uuid_gen; 36 | bool enabled; /**< switch of db connection */ 37 | } db_client_service_t; 38 | 39 | /** 40 | * @brief init ScyllaDB client service and connect to specific cluster 41 | * 42 | * @param[out] service ScyllaDB client service 43 | * @param[in] usage specfic usage for db client service 44 | * @return 45 | * - SC_OK on success 46 | * - non-zero on error 47 | */ 48 | status_t db_client_service_init(db_client_service_t* service, db_client_usage_t usage); 49 | 50 | /** 51 | * @brief free ScyllaDB client service 52 | * 53 | * @param[in] service ScyllaDB client service 54 | * @return 55 | * - SC_OK on success 56 | * - non-zero on error 57 | */ 58 | status_t db_client_service_free(db_client_service_t* service); 59 | 60 | #ifdef __cplusplus 61 | } 62 | #endif 63 | 64 | #endif // STORAGE_SCYLLADB_CLIENT_H_ 65 | -------------------------------------------------------------------------------- /storage/scylladb_utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #ifndef STORAGE_SCYLLADB_UTILS_H_ 9 | #define STORAGE_SCYLLADB_UTILS_H_ 10 | #ifdef __cplusplus 11 | extern "C" { 12 | #endif 13 | #include 14 | #include "cassandra.h" 15 | #include "common/logger.h" 16 | 17 | /** 18 | * @file storage/scylladb_utils.h 19 | * @brief Universal functions, the logger and headers for ScyllaDB driver. 20 | */ 21 | 22 | logger_id_t scylladb_logger_id; 23 | 24 | /** 25 | * @brief execute CQL query 26 | * 27 | * @param[in] session used to execute queries and maintains cluster state 28 | * @param[in] query executing query 29 | * @return 30 | * - CASS_OK on success 31 | * - non-zero on error 32 | */ 33 | CassError execute_query(CassSession* session, const char* query); 34 | 35 | /** 36 | * @brief prepare CQL query 37 | * 38 | * @param[in] session used to execute queries and maintains cluster state 39 | * @param[in] query pararing query 40 | * @return 41 | * - CASS_OK on success 42 | * - non-zero on error 43 | */ 44 | CassError prepare_query(CassSession* session, const char* query, const CassPrepared** prepared); 45 | 46 | /** 47 | * @brief execute CQL statement 48 | * 49 | * @param[in] session used to execute queries and maintains cluster state 50 | * @param[in] statement executing statement 51 | * @return 52 | * - CASS_OK on success 53 | * - non-zero on error 54 | */ 55 | CassError execute_statement(CassSession* session, CassStatement* statement); 56 | 57 | /** 58 | * @brief combine three strings to a CQL query 59 | * 60 | * @param[in] head_desc first part of query 61 | * @param[in] position keyspace name or table name 62 | * @param[in] left_desc left part of query 63 | * @return 64 | * - SC_OK on success 65 | * - non-zero on error 66 | */ 67 | status_t make_query(char** result, const char* head_desc, const char* position, const char* left_desc); 68 | 69 | /** 70 | * @brief create ScyllaDB keyspace 71 | * 72 | * @param[in] session used to execute queries and maintains cluster state 73 | * @param[in] keyspace_name name of keyspace to be created 74 | * @return 75 | * - SC_OK on success 76 | * - non-zero on error 77 | */ 78 | status_t create_keyspace(CassSession* session, const char* keyspace_name); 79 | 80 | /** 81 | * @brief clear all data in the specific ScyllaDB table without droping the table 82 | * 83 | * @param[in] session used to execute queries and maintains cluster state 84 | * @param[in] table_name The name of table to be truncated 85 | * @return 86 | * - SC_OK on success 87 | * - non-zero on error 88 | */ 89 | status_t db_truncate_table(CassSession* session, const char* table_name); 90 | 91 | /** 92 | * Initialize logger 93 | */ 94 | void scylladb_logger_init(); 95 | 96 | /** 97 | * Release logger 98 | * 99 | * @return 100 | * - zero on success 101 | * - EXIT_FAILURE on error 102 | */ 103 | int scylladb_logger_release(); 104 | 105 | #ifdef __cplusplus 106 | } 107 | #endif 108 | 109 | #endif // STORAGE_SCYLLADB_UTILS_H_ -------------------------------------------------------------------------------- /storage/ta_storage.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #ifndef STORAGE_TA_STORAGE_H_ 9 | #define STORAGE_TA_STORAGE_H_ 10 | #ifdef __cplusplus 11 | extern "C" { 12 | #endif 13 | 14 | #include "scylladb_identity.h" 15 | #include "scylladb_permanode.h" 16 | 17 | /** 18 | * @file storage/ta_storage.h 19 | * @brief The high level header for TA storage driver. 20 | */ 21 | 22 | #ifdef __cplusplus 23 | } 24 | #endif 25 | 26 | #endif // STORAGE_TA_STORAGE_H_ -------------------------------------------------------------------------------- /tests/BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "test_define", 3 | hdrs = ["test_define.h"], 4 | visibility = ["//visibility:public"], 5 | deps = [ 6 | "//accelerator:ta_config", 7 | "@unity", 8 | ], 9 | ) 10 | 11 | cc_library( 12 | name = "common", 13 | srcs = ["common.c"], 14 | hdrs = ["common.h"], 15 | visibility = ["//visibility:public"], 16 | deps = [ 17 | "//accelerator:ta_config", 18 | "//common", 19 | ], 20 | ) 21 | 22 | cc_library( 23 | name = "logger_lib", 24 | visibility = [ 25 | "//endpoint/tests/regression:__pkg__", 26 | "//endpoint/tests/unit-test:__pkg__", 27 | "//tests:__subpackages__", 28 | ], 29 | deps = select({ 30 | "//accelerator:mqtt_enable": ["//connectivity/mqtt"], 31 | "//conditions:default": ["//connectivity/http"], 32 | }), 33 | ) 34 | -------------------------------------------------------------------------------- /tests/api/BUILD: -------------------------------------------------------------------------------- 1 | cc_test( 2 | name = "driver", 3 | srcs = [ 4 | "driver.c", 5 | ], 6 | deps = [ 7 | "//accelerator/core:apis", 8 | "//accelerator/core:proxy_apis", 9 | "//tests:common", 10 | "//tests:logger_lib", 11 | "//tests:test_define", 12 | "@cJSON", 13 | ], 14 | ) 15 | 16 | cc_binary( 17 | name = "driver_stat", 18 | srcs = [ 19 | "driver.c", 20 | ] + select({ 21 | "//accelerator:mqtt_enable": ["//connectivity/mqtt"], 22 | "//conditions:default": ["//connectivity/http"], 23 | }), 24 | defines = ["ENABLE_STAT"], 25 | deps = [ 26 | "//accelerator/core:apis", 27 | "//accelerator/core:proxy_apis", 28 | "//tests:common", 29 | "//tests:logger_lib", 30 | "//tests:test_define", 31 | "@cJSON", 32 | ], 33 | ) 34 | 35 | cc_test( 36 | name = "test_periodical_task", 37 | srcs = [ 38 | "test_periodical_task.c", 39 | ], 40 | deps = [ 41 | "//accelerator/core", 42 | "//accelerator/core:apis", 43 | "//accelerator/core:periodical_task", 44 | "//tests:common", 45 | "//tests:logger_lib", 46 | "//tests:test_define", 47 | ], 48 | ) 49 | 50 | cc_test( 51 | name = "mam_test", 52 | srcs = [ 53 | "mam_test.c", 54 | ], 55 | deps = [ 56 | "//accelerator/core:apis", 57 | "//accelerator/core:proxy_apis", 58 | "//common", 59 | "//tests:common", 60 | "//tests:logger_lib", 61 | "//tests:test_define", 62 | ], 63 | ) 64 | 65 | cc_test( 66 | name = "test_mam_psk", 67 | srcs = [ 68 | "test_mam_psk.c", 69 | ], 70 | deps = [ 71 | "//accelerator/core:apis", 72 | "//accelerator/core:proxy_apis", 73 | "//common", 74 | "//tests:common", 75 | "//tests:logger_lib", 76 | "//tests:test_define", 77 | ], 78 | ) 79 | 80 | cc_test( 81 | name = "test_write_until_next_channel", 82 | srcs = [ 83 | "test_write_until_next_channel.c", 84 | ], 85 | deps = [ 86 | "//accelerator/core:apis", 87 | "//accelerator/core:proxy_apis", 88 | "//common", 89 | "//tests:common", 90 | "//tests:logger_lib", 91 | "//tests:test_define", 92 | ], 93 | ) 94 | 95 | cc_test( 96 | name = "test_write_with_chid", 97 | srcs = [ 98 | "test_write_with_chid.c", 99 | ], 100 | deps = [ 101 | "//accelerator/core:apis", 102 | "//accelerator/core:proxy_apis", 103 | "//common", 104 | "//tests:common", 105 | "//tests:logger_lib", 106 | "//tests:test_define", 107 | ], 108 | ) 109 | -------------------------------------------------------------------------------- /tests/common.c: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | #include "accelerator/cli_info.h" 3 | #include "stdlib.h" 4 | 5 | static struct ta_cli_argument_s driver_cli_arguments_g[] = { 6 | {"hash", required_argument, NULL, 'H', "testing transaction hashes"}, 7 | {"tag", required_argument, NULL, 'T', "testing transaction tag"}, 8 | {NULL, 0, NULL, 0, NULL}}; 9 | 10 | struct option* driver_cli_build_options() { 11 | int driver_cli_arg_size = sizeof(driver_cli_arguments_g) / sizeof(driver_cli_arguments_g[0]); 12 | struct option* driver_long_options = 13 | (struct option*)realloc(cli_build_options(), (cli_cmd_num + 2) * sizeof(struct option)); 14 | for (int i = 0; i < driver_cli_arg_size; i++) { 15 | driver_long_options[(cli_cmd_num - 1) + i].name = driver_cli_arguments_g[i].name; 16 | driver_long_options[(cli_cmd_num - 1) + i].has_arg = driver_cli_arguments_g[i].has_arg; 17 | driver_long_options[(cli_cmd_num - 1) + i].flag = driver_cli_arguments_g[i].flag; 18 | driver_long_options[(cli_cmd_num - 1) + i].val = driver_cli_arguments_g[i].val; 19 | } 20 | 21 | return driver_long_options; 22 | } 23 | 24 | status_t driver_core_cli_init(ta_core_t* const core, int argc, char** argv, driver_test_cases_t* test_cases) { 25 | int key = 0; 26 | status_t ret = SC_OK; 27 | struct option* long_options = driver_cli_build_options(); 28 | 29 | while ((key = getopt_long(argc, argv, "hvH:T:", long_options, NULL)) != -1) { 30 | switch (key) { 31 | case 'h': 32 | ta_usage(); 33 | exit(EXIT_SUCCESS); 34 | case 'v': 35 | printf("%s\n", TA_VERSION); 36 | exit(EXIT_SUCCESS); 37 | case 'H': 38 | // Take the arguments as testing transaction hashes 39 | if (test_cases) { 40 | for (int i = 0; i < TXN_HASH_NUM; i++) { 41 | if (!test_cases->txn_hash[i]) { 42 | test_cases->txn_hash[i] = optarg; 43 | } 44 | } 45 | } 46 | break; 47 | case 'T': 48 | // Take the arguments as testing transaction tag 49 | if (test_cases) { 50 | test_cases->tag = optarg; 51 | } 52 | break; 53 | default: 54 | ret = cli_core_set(core, key, optarg); 55 | break; 56 | } 57 | if (ret != SC_OK) { 58 | break; 59 | } 60 | } 61 | 62 | free(long_options); 63 | return ret; 64 | } 65 | 66 | static double diff_time(struct timespec start, struct timespec end) { 67 | struct timespec diff; 68 | if (end.tv_nsec - start.tv_nsec < 0) { 69 | diff.tv_sec = end.tv_sec - start.tv_sec - 1; 70 | diff.tv_nsec = end.tv_nsec - start.tv_nsec + 1000000000; 71 | } else { 72 | diff.tv_sec = end.tv_sec - start.tv_sec; 73 | diff.tv_nsec = end.tv_nsec - start.tv_nsec; 74 | } 75 | return (diff.tv_sec + diff.tv_nsec / 1000000000.0); 76 | } 77 | 78 | void test_time_end(struct timespec* start, struct timespec* end, double* sum) { 79 | clock_gettime(CLOCK_REALTIME, end); 80 | double difference = diff_time(*start, *end); 81 | #if defined(ENABLE_STAT) 82 | printf("%lf\n", difference); 83 | #endif 84 | *sum += difference; 85 | } 86 | 87 | void rand_trytes_init() { 88 | // We use ASLR which stands for Address Space Layout Randomization, and we can assume each address of functions inside 89 | // loaded program is randomized 90 | srand(getpid() ^ ((unsigned long)(&rand_trytes_init))); 91 | } 92 | -------------------------------------------------------------------------------- /tests/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include 10 | #include 11 | #include "accelerator/config.h" 12 | #include "common/ta_errors.h" 13 | 14 | #define TXN_HASH_NUM 2 15 | 16 | typedef struct driver_test_cases_s { 17 | char* txn_hash[TXN_HASH_NUM]; 18 | char* tag; 19 | } driver_test_cases_t; 20 | 21 | /** 22 | * @brief Set option list for `get_long()` 23 | * 24 | * @return 25 | * - pointer of a `struct option` array on success 26 | * - NULL on error 27 | */ 28 | struct option* driver_cli_build_options(); 29 | 30 | /** 31 | * @brief Initialize configurations with default values for driver tests 32 | * 33 | * @param[in] core Pointer to Tangle-accelerator core configuration structure 34 | * @param[in] argc Pointer to Tangle-accelerator core configuration structure 35 | * @param[in] argv Pointer to Tangle-accelerator core configuration structure 36 | * @param[in] test_cases Pointer to Tangle-accelerator core configuration structure 37 | * 38 | * @return 39 | * - SC_OK on success 40 | * - non-zero on error 41 | */ 42 | status_t driver_core_cli_init(ta_core_t* const core, int argc, char** argv, driver_test_cases_t* test_cases); 43 | 44 | /** 45 | * @brief Start testing clock 46 | * 47 | * @param[out] start `struct timespec` object for recording starting time. 48 | */ 49 | static inline void test_time_start(struct timespec* start) { clock_gettime(CLOCK_REALTIME, start); } 50 | 51 | /** 52 | * @brief Initialize configurations with default values 53 | * 54 | * @param[in] start `struct timespec` object for recording starting time. 55 | * @param[out] end `struct timespec` object for recording ending time. 56 | * @param[out] sum The total elapsing time. 57 | * 58 | */ 59 | void test_time_end(struct timespec* start, struct timespec* end, double* sum); 60 | 61 | /** 62 | * @brief Initialize random number generator. Call it before 'gen_rand_trytes()'. 63 | */ 64 | void rand_trytes_init(); 65 | 66 | /** 67 | * @brief Generate a random tryte combination with given length 68 | * 69 | * @param[in] len The length of generated trytes 70 | * @param[out] trytes Output trytes combination 71 | */ 72 | static inline void gen_rand_trytes(int len, tryte_t* trytes) { 73 | const char tryte_alphabet[] = "NOPQRSTUVWXYZ9ABCDEFGHIJKLM"; 74 | 75 | for (int i = 0; i < len; i++) { 76 | trytes[i] = tryte_alphabet[rand() % TRINARY_ALPHABET_LEN]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /tests/coverity_analysis.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | make 4 | bazel build //accelerator 5 | make clean 6 | 7 | make 8 | bazel build --define db=enable //accelerator 9 | make clean 10 | 11 | make MQTT 12 | bazel build --define mqtt=enable //accelerator 13 | make clean 14 | -------------------------------------------------------------------------------- /tests/endpoint/common.sh: -------------------------------------------------------------------------------- 1 | LEGATO_VERSION="20.04.0" 2 | 3 | function download_legato_repo() { 4 | echo "Downloading Legato AF" 5 | repo init -u git://github.com/legatoproject/manifest -m legato/releases/${LEGATO_VERSION}.xml 6 | repo sync 7 | } 8 | 9 | function build_legato_repo() { 10 | if [ ! -d "legato" ]; then 11 | echo "Please download the Legato AF first" 12 | exit 1 13 | fi 14 | 15 | if [ ! -f "legato/Makefile" ]; then 16 | echo "The Makefile inside legato project is missing" 17 | echo "Please remove the legato directory and download Legato AF again." 18 | exit 1 19 | fi 20 | 21 | echo "Building Legato AF" 22 | make -C legato localhost 23 | } 24 | 25 | function setup_leaf() { 26 | if ! which "leaf"; then 27 | echo "Please install Legato leaf first" 28 | exit 1 29 | fi 30 | leaf --non-interactive setup legato-latest -p "$1" 31 | } 32 | 33 | function validate_host() { 34 | if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then 35 | return 0 36 | fi 37 | if host "$1" >/dev/null 2>&1; then 38 | return 0 39 | fi 40 | echo "Please enter a valid host or ip address" 41 | exit 1 42 | } 43 | 44 | function validate_port() { 45 | re='^[0-9]+$' 46 | if ! [[ $1 =~ $re ]]; then 47 | echo "Please enter a valid port number" 48 | exit 1 49 | fi 50 | } 51 | -------------------------------------------------------------------------------- /tests/endpoint/test-endpoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Usage: ./test-endpoint.sh [HOST or IP] [PORT] 3 | 4 | if [ "$#" -ne 4 ]; then 5 | echo "Usage: ./test-endpoint.sh [HOST or IP] [PORT] [mam seed] [test message]" >&2 6 | exit 1 7 | fi 8 | 9 | set -euo pipefail 10 | 11 | COMMON_FILE="tests/endpoint/common.sh" 12 | 13 | if [ ! -f "$COMMON_FILE" ]; then 14 | echo "$COMMON_FILE is not exists." 15 | exit 1 16 | fi 17 | source $COMMON_FILE 18 | 19 | TA_HOST="$1" 20 | TA_PORT="$2" 21 | MAM_SEED="$3" 22 | MESSAGE="$4" 23 | # Check ip is validity or not 24 | validate_host "$1" 25 | validate_port "$2" 26 | 27 | # Create endpoint app 28 | make EP_TA_HOST="$TA_HOST" EP_TA_PORT="$TA_PORT" legato 29 | 30 | # Start TA server for testing 31 | bazel run //accelerator -- --ta_port="$TA_PORT" --cache=on & 32 | TA=$! 33 | trap "kill -9 ${TA};" INT # Trap SIGINT from Ctrl-C to stop TA 34 | 35 | sleep 10 36 | 37 | endpoint/_build_endpoint/localhost/app/endpoint/staging/read-only/bin/endpoint --host="$TA_HOST" --port="$TA_PORT" --mam-seed="$MAM_SEED" --msg="$MESSAGE" 38 | ret_code=$? 39 | 40 | kill -9 ${TA} 41 | exit $ret_code 42 | -------------------------------------------------------------------------------- /tests/endpoint/test-target.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Usage: ./test-target.sh [HOST or IP] [PORT] [LEGATO_TARGET] 3 | SUPPORT_TARGETS=('wp77xx') 4 | 5 | if [ "$#" -ne 3 ]; then 6 | echo "Usage: ./test-target.sh [HOST or IP] [PORT] [LEGATO_TARGET]" >&2 7 | echo "For example: ./test-target.sh localhost 8000 wp77xx" >&2 8 | exit 1 9 | fi 10 | 11 | COMMON_FILE="tests/endpoint/common.sh" 12 | 13 | if [ ! -f "$COMMON_FILE" ]; then 14 | echo "The $COMMON_FILE doesn't exist." 15 | exit 1 16 | fi 17 | source $COMMON_FILE 18 | 19 | # Check ip is validity or not 20 | validate_host "$1" 21 | validate_port "$2" 22 | 23 | # Check the target 24 | if ! grep -q "$SUPPORT_TARGETS" <<< "$3"; then 25 | echo "The target "$3" doesn't support." 26 | exit 1 27 | fi 28 | 29 | set -euo pipefail 30 | 31 | if ! env | grep LEAF >/dev/null; then 32 | echo "error: You must to setup the correct leaf profile and enter the leaf shell first" 33 | exit 1 34 | fi 35 | 36 | make TESTS=true EP_TA_HOST="$1" EP_TA_PORT="$2" EP_TARGET="$3" legato 37 | -------------------------------------------------------------------------------- /tests/regression/common.sh: -------------------------------------------------------------------------------- 1 | # Build options 2 | setup_build_opts() { 3 | # The options are separated by '|', the format is as follows 4 | # | 5 | OPTIONS=( 6 | "|" 7 | "|--node_host ${NODE_HOST}" 8 | "|--node_port ${NODE_PORT}" 9 | "|--ta_host ${TA_HOST}" 10 | "|--quiet" 11 | "--define build_type=debug|" 12 | "--define build_type=profile|" 13 | ) 14 | success=() 15 | fail=() 16 | } 17 | 18 | # Set sanitizer options 19 | setup_sanitizer_opts() { 20 | SAN_OPTIONS=( 21 | "--config=asan" 22 | "--config=tsan" 23 | "--config=ubsan" 24 | ) 25 | success=() 26 | fail=() 27 | } 28 | 29 | # Check environment variables 30 | check_env() { 31 | ENV_NAME=( 32 | "NODE_HOST" 33 | "NODE_PORT" 34 | "TA_HOST" 35 | "TA_PORT" 36 | "DB_HOST" 37 | ) 38 | 39 | echo "Checking environment variables" 40 | echo "==============================" 41 | 42 | for ((i = 0; i < ${#ENV_NAME[@]}; i++)); do 43 | name=${ENV_NAME[${i}]} 44 | if [[ -z ${!name} ]]; then 45 | echo "${name} not set" 46 | fail=1 47 | else 48 | echo "${name} is set to ${!name}" 49 | fi 50 | done 51 | 52 | echo "==============================" 53 | 54 | [ -z ${fail} ] || exit 1 55 | } 56 | 57 | # Parse command line arguments 58 | get_cli_args() { 59 | shift 60 | remaining_args=$@ # Get the remaining arguments 61 | } 62 | -------------------------------------------------------------------------------- /tests/regression/load_test_suite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DLTcollab/tangle-accelerator/c775a7834301a34c76bc5f2bd953a4891e46e732/tests/regression/load_test_suite/__init__.py -------------------------------------------------------------------------------- /tests/regression/load_test_suite/readme.md: -------------------------------------------------------------------------------- 1 | # Load test 2 | ## What is Load test? 3 | This is an [introduction](https://www.blazemeter.com/blog/performance-testing-vs-load-testing-vs-stress-testing/?utm_source=blog&utm_medium=BM_blog&utm_campaign=why-load-testing-is-important) of load test from a tool `BlazeMeter` 4 | 5 | Extract from it: 6 | 7 | > Load testing is testing that checks how systems function under a heavy number of concurrent virtual users performing transactions over a certain period of time. Or in other words, how systems handle heavy load volumes. 8 | 9 | > Stress testing is testing that checks the upper limits of your system by testing it under `extreme loads.` 10 | 11 | This is the reason why this `load test` package can implement `stress test` when giving an enormous number of client. 12 | 13 | ## Implementation of Send Transfer Load test 14 | Load test is based on common package build for unit test. 15 | 16 | The most important part of package is the following function `SendTransfer().test()` 17 | I use `multiprocessing` in python to create virtual clients. 18 | With mulitprocessing.Manager() package, it'll collect `error_rate` and `response time` of each client. 19 | Every client will send transfers depends on given number `transfer_num` for every sample. 20 | 21 | `SendTransfer().test()` will collect samples from `client_min` to `client_max` moved with `stepsize`. 22 | Ascending client number is benefit to observe how memory usage increase. 23 | 24 | The elapsed time in load test is a crucial statistics, which is response time here. 25 | We can use dumpfile() to dump average response time, standard deviation of response time, and error rate. 26 | The plot() function give us a brief view of how response time scattered. 27 | 28 | -------------------------------------------------------------------------------- /tests/regression/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2022.12.7 2 | chardet==3.0.4 3 | idna==2.7 4 | paho-mqtt==1.5.0 5 | requests==2.20.0 6 | urllib3==1.26.5 7 | -------------------------------------------------------------------------------- /tests/regression/router-sanitizer.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | source tests/regression/common.sh 4 | 5 | check_env 6 | setup_sanitizer_opts 7 | 8 | # Get command line arguments 9 | # Current arguments parsed are 10 | get_cli_args $@ 11 | 12 | # Install prerequisites 13 | make 14 | pip3 install --user -r tests/regression/requirements.txt 15 | 16 | # FIXME: Check Redis status 17 | redis-server & 18 | 19 | # Iterate over all available build options 20 | for ((i = 0; i < ${#SAN_OPTIONS[@]}; i++)); do 21 | option=${SAN_OPTIONS[${i}]} 22 | socket=$(mktemp) 23 | 24 | bazel run accelerator ${option} -c dbg -- --ta_port=${TA_PORT} --socket=${socket} & 25 | TA=$! 26 | trap "kill -9 ${TA};" INT # Trap SIGINT from Ctrl-C to stop TA 27 | 28 | # if tangle-accelerator takes more than 30 secs to initialize, then exit and return failure. 29 | timeout 30 tests/regression/ta_waiting.sh 30 | ret_code=$? 31 | if [[ $ret_code -eq 124 ]]; then 32 | echo "Timeout in initializing tangle-accelerator." 33 | kill -9 ${TA} 34 | exit 1 35 | elif [[ $ret_code -eq 1 ]]; then 36 | echo "Failed to connect to UNIX domain socket." 37 | kill -9 ${TA} 38 | exit 1 39 | fi 40 | 41 | python3 tests/regression/runner.py ${remaining_args} --url ${TA_HOST}:${TA_PORT} 42 | rc=$? 43 | 44 | if [ $rc -ne 0 ]; then 45 | echo "Build sanitizer '${option}' failed" 46 | fail+=("${option}") 47 | else 48 | success+=("${option}") 49 | fi 50 | 51 | bazel clean 52 | wait $(kill -9 ${TA}) 53 | done 54 | 55 | echo "--------- Successful build options ---------" 56 | for ((i = 0; i < ${#success[@]}; i++)); do echo ${success[${i}]}; done 57 | echo "----------- Failed build options -----------" 58 | for ((i = 0; i < ${#fail[@]}; i++)); do echo ${fail[${i}]}; done 59 | 60 | if [ ${#fail[@]} -gt 0 ]; then 61 | exit 1 62 | fi 63 | -------------------------------------------------------------------------------- /tests/regression/run-api-with-db.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | source tests/regression/common.sh 4 | 5 | check_env 6 | setup_build_opts 7 | 8 | # Get command line arguments 9 | # Current arguments parsed are 10 | get_cli_args $@ 11 | 12 | # Install prerequisites 13 | make 14 | pip3 install --user -r tests/regression/requirements.txt 15 | 16 | # FIXME: Check Redis status 17 | redis-server & 18 | 19 | # Iterate over all available build options 20 | for ((i = 0; i < ${#OPTIONS[@]}; i++)); do 21 | option=${OPTIONS[${i}]} 22 | cli_arg=$(echo ${option} | cut -d '|' -f 2) 23 | build_arg=$(echo ${option} | cut -d '|' -f 1) 24 | socket=$(mktemp) 25 | 26 | bazel run accelerator --define db=enable ${build_arg} -- --ta_port=${TA_PORT} ${cli_arg} --db_host=${DB_HOST} --socket=${socket} --proxy_passthrough & 27 | TA=$! 28 | trap "kill -9 ${TA};" INT # Trap SIGINT from Ctrl-C to stop TA 29 | 30 | # if tangle-accelerator takes more than 30 secs to initialize, then exit and return failure. 31 | timeout 30 tests/regression/ta_waiting.sh 32 | ret_code=$? 33 | if [[ $ret_code -eq 124 ]]; then 34 | echo "Timeout in initializing tangle-accelerator." 35 | kill -9 ${TA} 36 | exit 1 37 | elif [[ $ret_code -eq 1 ]]; then 38 | echo "Failed to connect to UNIX domain socket." 39 | kill -9 ${TA} 40 | exit 1 41 | fi 42 | 43 | python3 tests/regression/runner.py ${remaining_args} --url ${TA_HOST}:${TA_PORT} 44 | rc=$? 45 | 46 | if [ $rc -ne 0 ]; then 47 | echo "Build option '${option}' failed" 48 | fail+=("${option}") 49 | else 50 | success+=("${option}") 51 | fi 52 | 53 | bazel clean 54 | wait $(kill -9 ${TA}) 55 | done 56 | 57 | echo "--------- Successful build options ---------" 58 | for ((i = 0; i < ${#success[@]}; i++)); do echo ${success[${i}]}; done 59 | echo "----------- Failed build options -----------" 60 | for ((i = 0; i < ${#fail[@]}; i++)); do echo ${fail[${i}]}; done 61 | 62 | if [ ${#fail[@]} -gt 0 ]; then 63 | exit 1 64 | fi 65 | -------------------------------------------------------------------------------- /tests/regression/run-api-with-mqtt.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | source tests/regression/common.sh 4 | 5 | check_env 6 | setup_build_opts 7 | 8 | # Get command line arguments 9 | # Current arguments parsed are 10 | get_cli_args $@ 11 | 12 | # Install prerequisites 13 | make MQTT 14 | pip3 install --user -r tests/regression/requirements.txt 15 | 16 | # FIXME: Check Redis status 17 | redis-server & 18 | 19 | # Iterate over all available build options 20 | for ((i = 0; i < ${#OPTIONS[@]}; i++)); do 21 | option=${OPTIONS[${i}]} 22 | cli_arg=${option} | cut -d '|' -f 1 23 | build_arg=${option} | cut -d '|' -f 2 24 | socket=$(mktemp) 25 | 26 | bazel run accelerator --define mqtt=enable ${build_arg} -- --quiet --ta_port=${TA_PORT} ${cli_arg} --socket=${socket} --proxy_passthrough & 27 | TA=$! 28 | trap "kill -9 ${TA};" INT # Trap SIGINT from Ctrl-C to stop TA 29 | 30 | # if tangle-accelerator takes more than 30 secs to initialize, then exit and return failure. 31 | timeout 30 tests/regression/ta_waiting.sh 32 | ret_code=$? 33 | if [[ $ret_code -eq 124 ]]; then 34 | echo "Timeout in initializing tangle-accelerator." 35 | kill -9 ${TA} 36 | exit 1 37 | elif [[ $ret_code -eq 1 ]]; then 38 | echo "Failed to connect to UNIX domain socket." 39 | kill -9 ${TA} 40 | exit 1 41 | fi 42 | 43 | python3 tests/regression/runner.py ${remaining_args} --url "localhost" --mqtt 44 | rc=$? 45 | 46 | if [ $rc -ne 0 ]; then 47 | echo "Build option '${option}' failed" 48 | fail+=("${option}") 49 | else 50 | success+=("${option}") 51 | fi 52 | 53 | bazel clean 54 | wait $(kill -9 ${TA}) 55 | done 56 | 57 | echo "--------- Successful build options ---------" 58 | for ((i = 0; i < ${#success[@]}; i++)); do echo ${success[${i}]}; done 59 | echo "----------- Failed build options -----------" 60 | for ((i = 0; i < ${#fail[@]}; i++)); do echo ${fail[${i}]}; done 61 | 62 | if [ ${#fail[@]} -gt 0 ]; then 63 | exit 1 64 | fi 65 | -------------------------------------------------------------------------------- /tests/regression/run-api.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | source tests/regression/common.sh 4 | 5 | check_env 6 | setup_build_opts 7 | 8 | # Get command line arguments 9 | # Current arguments parsed are 10 | get_cli_args $@ 11 | 12 | # Install prerequisites 13 | make 14 | pip3 install --user -r tests/regression/requirements.txt 15 | 16 | # FIXME: Check Redis status 17 | redis-server & 18 | 19 | # Iterate over all available build options 20 | for ((i = 0; i < ${#OPTIONS[@]}; i++)); do 21 | option=${OPTIONS[${i}]} 22 | cli_arg=$(echo ${option} | cut -d '|' -f 2) 23 | build_arg=$(echo ${option} | cut -d '|' -f 1) 24 | socket=$(mktemp) 25 | 26 | bazel run accelerator ${build_arg} -- --ta_port=${TA_PORT} ${cli_arg} --proxy_passthrough --socket=${socket} & 27 | TA=$! 28 | trap "kill -9 ${TA};" INT # Trap SIGINT from Ctrl-C to stop TA 29 | 30 | # if tangle-accelerator takes more than 30 secs to initialize, then exit and return failure. 31 | timeout 30 tests/regression/ta_waiting.sh 32 | ret_code=$? 33 | if [[ $ret_code -eq 124 ]]; then 34 | echo "Timeout in initializing tangle-accelerator." 35 | kill -9 ${TA} 36 | exit 1 37 | elif [[ $ret_code -eq 1 ]]; then 38 | echo "Failed to connect to UNIX domain socket." 39 | kill -9 ${TA} 40 | exit 1 41 | fi 42 | 43 | python3 tests/regression/runner.py ${remaining_args} --url ${TA_HOST}:${TA_PORT} 44 | rc=$? 45 | 46 | if [ $rc -ne 0 ]; then 47 | echo "Build option '${option}' failed" 48 | fail+=("${option}") 49 | else 50 | success+=("${option}") 51 | fi 52 | 53 | bazel clean 54 | wait $(kill -9 ${TA}) 55 | done 56 | 57 | echo "--------- Successful build options ---------" 58 | for ((i = 0; i < ${#success[@]}; i++)); do echo ${success[${i}]}; done 59 | echo "----------- Failed build options -----------" 60 | for ((i = 0; i < ${#fail[@]}; i++)); do echo ${fail[${i}]}; done 61 | 62 | if [ ${#fail[@]} -gt 0 ]; then 63 | exit 1 64 | fi 65 | -------------------------------------------------------------------------------- /tests/regression/runner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 4 | # All Rights Reserved. 5 | # This is free software; you can redistribute it and/or modify it under the 6 | # terms of the MIT license. A copy of the license can be found in the file 7 | # "LICENSE" at the root of this distribution. 8 | 9 | # Run in Python3 10 | from common import * 11 | import os 12 | import sys 13 | import unittest 14 | import logging 15 | 16 | # Run all the API Test here 17 | if __name__ == '__main__': 18 | ver = sys.version_info 19 | if ver.major < 3 or (ver.major == 3 and ver.minor < 6): 20 | raise Exception("Must be using Python 3.6 or greater") 21 | 22 | parse_cli_arg() 23 | 24 | suite_path = os.path.join(os.path.dirname(__file__), "test_suite") 25 | sys.path.append(suite_path) 26 | unsuccessful_module = [] 27 | for module in os.listdir(suite_path): 28 | if module[-3:] == ".py": 29 | mod = __import__(module[:-3], locals(), globals()) 30 | suite = unittest.TestLoader().loadTestsFromModule(mod) 31 | result = unittest.TextTestRunner(verbosity=0).run(suite) 32 | if not result.wasSuccessful(): 33 | unsuccessful_module.append(module) 34 | 35 | if len(unsuccessful_module): 36 | print(f"Error module: {unsuccessful_module}") 37 | exit(1) 38 | -------------------------------------------------------------------------------- /tests/regression/ta_waiting.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | socket=$1 4 | 5 | # Whether tangle-accelerator successfully initialzed 6 | success=0 7 | 8 | start_notification="TA-START" 9 | # Wait until tangle-accelerator has been initialized 10 | echo "==============Wait for TA starting==============" 11 | while read -r line; do 12 | if [[ "$line" == "$start_notification" ]]; then 13 | echo "nc info: $line" 14 | success=1 15 | fi 16 | done <<<$(nc -U -l $socket | tr '\0' '\n') 17 | echo "==============TA has successfully started==============" 18 | 19 | if [ "$success" -eq 1 ]; then 20 | exit 0 21 | else 22 | exit 1 23 | fi 24 | -------------------------------------------------------------------------------- /tests/unit-test/BUILD: -------------------------------------------------------------------------------- 1 | cc_test( 2 | name = "test_cache", 3 | srcs = [ 4 | "test_cache.c", 5 | ], 6 | linkopts = ["-luuid"], 7 | deps = [ 8 | "//tests:logger_lib", 9 | "//tests:test_define", 10 | "//utils/cache", 11 | "@unity", 12 | ], 13 | ) 14 | 15 | cc_test( 16 | name = "test_serializer", 17 | srcs = [ 18 | "test_serializer.c", 19 | ], 20 | deps = [ 21 | "//accelerator/core/serializer", 22 | "//tests:common", 23 | "//tests:logger_lib", 24 | "//tests:test_define", 25 | ], 26 | ) 27 | 28 | cc_test( 29 | name = "test_pow", 30 | srcs = [ 31 | "test_pow.c", 32 | ], 33 | deps = [ 34 | "//accelerator/core:pow", 35 | "//tests:logger_lib", 36 | "//tests:test_define", 37 | ], 38 | ) 39 | 40 | cc_test( 41 | name = "test_scylladb", 42 | srcs = [ 43 | "test_scylladb.c", 44 | ], 45 | deps = [ 46 | "//storage", 47 | "//tests:logger_lib", 48 | "//tests:test_define", 49 | ], 50 | ) 51 | 52 | cc_test( 53 | name = "test_timer", 54 | srcs = [ 55 | "test_timer.c", 56 | ], 57 | deps = [ 58 | "//connectivity/http", 59 | "//tests:logger_lib", 60 | "//tests:test_define", 61 | "//utils:timer", 62 | ], 63 | ) 64 | 65 | cc_test( 66 | name = "test_tryte_byte_conv", 67 | srcs = [ 68 | "test_tryte_byte_conv.c", 69 | ], 70 | deps = [ 71 | "//tests:logger_lib", 72 | "//tests:test_define", 73 | "//utils:tryte_byte_conv", 74 | ], 75 | ) 76 | 77 | cc_test( 78 | name = "test_crypto", 79 | srcs = ["test_crypto.c"], 80 | deps = [ 81 | "//crypto:ecdh", 82 | "//tests:logger_lib", 83 | "//tests:test_define", 84 | "@mbedtls", 85 | ], 86 | ) 87 | -------------------------------------------------------------------------------- /tests/unit-test/test_cache.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include 10 | #include "tests/test_define.h" 11 | #include "utils/cache/cache.h" 12 | #include "uuid/uuid.h" 13 | 14 | char test_uuid[UUID_STR_LEN] = {}; 15 | 16 | void test_cache_del(void) { 17 | char* key = test_uuid; 18 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_del(key)); 19 | } 20 | 21 | void test_cache_get(void) { 22 | char* key = test_uuid; 23 | char* res = NULL; 24 | 25 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_get(key, &res)); 26 | TEST_ASSERT_EQUAL_STRING(CACHE_VALUE, res); 27 | free(res); 28 | } 29 | 30 | void test_cache_set(void) { 31 | char* key = test_uuid; 32 | 33 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_set(key, strlen(key), CACHE_VALUE, strlen(CACHE_VALUE), 0)); 34 | } 35 | 36 | void test_cache_timeout(void) { 37 | char* key = test_uuid; 38 | char* res = NULL; 39 | const int timeout = 2; 40 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_set(key, strlen(key), CACHE_VALUE, strlen(CACHE_VALUE), timeout)); 41 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_get(key, &res)); 42 | free(res); 43 | res = NULL; 44 | sleep(timeout + 1); 45 | TEST_ASSERT_EQUAL_INT(SC_CACHE_FAILED_RESPONSE, cache_get(key, &res)); 46 | free(res); 47 | } 48 | 49 | void test_generate_uuid(void) { 50 | uuid_t bin_uuid; 51 | uuid_generate_random(bin_uuid); 52 | uuid_unparse(bin_uuid, test_uuid); 53 | 54 | TEST_ASSERT_TRUE(test_uuid[0]); 55 | } 56 | 57 | void test_cache_list_push(void) { 58 | TEST_ASSERT_EQUAL_INT( 59 | SC_OK, cache_list_push(TEST_UUID_LIST_NAME, strlen(TEST_UUID_LIST_NAME), TEST_UUID, strlen(TEST_UUID))); 60 | } 61 | 62 | void test_cache_list_at(void) { 63 | char res[UUID_STR_LEN]; 64 | 65 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_list_at(TEST_UUID_LIST_NAME, -1, UUID_STR_LEN, res)); 66 | TEST_ASSERT_EQUAL_STRING(TEST_UUID, res); 67 | } 68 | 69 | void test_cache_list_size(void) { 70 | int len = 0; 71 | 72 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_list_size(TEST_UUID_LIST_NAME, &len)); 73 | TEST_ASSERT_EQUAL_INT(1, len); 74 | } 75 | 76 | void test_cache_list_pop(void) { 77 | char res[UUID_STR_LEN]; 78 | 79 | TEST_ASSERT_EQUAL_INT(SC_OK, cache_list_pop(TEST_UUID_LIST_NAME, res)); 80 | TEST_ASSERT_EQUAL_STRING(TEST_UUID, res); 81 | } 82 | 83 | void test_cache_occupied_space() { TEST_ASSERT_GREATER_THAN(-1, cache_occupied_space()); } 84 | 85 | int main(void) { 86 | UNITY_BEGIN(); 87 | pthread_rwlock_t* rwlock = NULL; 88 | cache_init(&rwlock, true, REDIS_HOST, REDIS_PORT); 89 | RUN_TEST(test_generate_uuid); 90 | RUN_TEST(test_cache_set); 91 | RUN_TEST(test_cache_get); 92 | RUN_TEST(test_cache_del); 93 | RUN_TEST(test_cache_timeout); 94 | RUN_TEST(test_cache_list_push); 95 | RUN_TEST(test_cache_list_at); 96 | RUN_TEST(test_cache_list_size); 97 | RUN_TEST(test_cache_list_pop); 98 | RUN_TEST(test_cache_occupied_space); 99 | cache_stop(&rwlock); 100 | return UNITY_END(); 101 | } 102 | -------------------------------------------------------------------------------- /tests/unit-test/test_crypto.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "crypto/ecdh.h" 10 | #include "tests/test_define.h" 11 | 12 | void test_srv_cli_communication(void) { 13 | rand_gen_t rand_gen; 14 | mbedtls_ecdh_context ecdh_srv, ecdh_cli; 15 | unsigned char cli_to_srv[SHARE_DATA_LEN], srv_to_cli[SHARE_DATA_LEN]; 16 | 17 | // initialize ECDH object for server side and client side 18 | mbedtls_ecdh_init(&ecdh_srv); 19 | mbedtls_ecdh_init(&ecdh_cli); 20 | 21 | TEST_ASSERT_EQUAL_INT32(SC_OK, 22 | rand_gen_init(&rand_gen.entropy, &rand_gen.ctr_drbg, TEST_UUID, strlen(TEST_UUID) + 1)); 23 | 24 | // [client] initialize ECDH context and generate public key 25 | TEST_ASSERT_EQUAL_INT32(SC_OK, ecdh_gen_public_key(&ecdh_cli, &rand_gen.ctr_drbg, cli_to_srv)); 26 | 27 | // [server] initialize ECDH context and generate public key 28 | TEST_ASSERT_EQUAL_INT32(SC_OK, ecdh_gen_public_key(&ecdh_srv, &rand_gen.ctr_drbg, srv_to_cli)); 29 | 30 | // [server] compute shared secret with peer's public key 31 | TEST_ASSERT_EQUAL_INT32(SC_OK, ecdh_compute_shared_secret(&ecdh_srv, &rand_gen.ctr_drbg, cli_to_srv)); 32 | 33 | // [client] compute shared secret with peer's public key 34 | TEST_ASSERT_EQUAL_INT32(SC_OK, ecdh_compute_shared_secret(&ecdh_cli, &rand_gen.ctr_drbg, srv_to_cli)); 35 | 36 | // Check if the two shared secret are the same 37 | TEST_ASSERT_EQUAL_INT32(0, mbedtls_mpi_cmp_mpi(&ecdh_cli.z, &ecdh_srv.z)); 38 | 39 | rand_gen_release(&rand_gen.entropy, &rand_gen.ctr_drbg); 40 | mbedtls_ecdh_free(&ecdh_srv); 41 | mbedtls_ecdh_free(&ecdh_cli); 42 | } 43 | 44 | int main(void) { 45 | UNITY_BEGIN(); 46 | 47 | // Initialize logger 48 | if (ta_logger_init() != SC_OK) { 49 | return EXIT_FAILURE; 50 | } 51 | 52 | ecdh_logger_init(); 53 | RUN_TEST(test_srv_cli_communication); 54 | ecdh_logger_release(); 55 | 56 | return UNITY_END(); 57 | } 58 | -------------------------------------------------------------------------------- /tests/unit-test/test_pow.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "accelerator/core/pow.h" 10 | #include "tests/test_define.h" 11 | 12 | void test_pow_flex(void) { 13 | int mwm = 9; 14 | flex_trit_t tx_trits[FLEX_TRIT_SIZE_8019]; 15 | flex_trit_t* nonce_trits; 16 | flex_trit_t null_trits[mwm]; 17 | 18 | flex_trits_from_trytes(tx_trits, NUM_TRITS_SERIALIZED_TRANSACTION, (const tryte_t*)TRYTES_2673_1, 19 | NUM_TRYTES_SERIALIZED_TRANSACTION, NUM_TRYTES_SERIALIZED_TRANSACTION); 20 | 21 | nonce_trits = ta_pow_flex(tx_trits, mwm); 22 | 23 | /* Validation */ 24 | flex_trits_slice(null_trits, mwm, nonce_trits, NUM_TRITS_NONCE, NUM_TRITS_NONCE - mwm, mwm); 25 | TEST_ASSERT_TRUE(flex_trits_are_null(null_trits, mwm / 3)); 26 | 27 | free(nonce_trits); 28 | } 29 | 30 | void test_pow_bundle(void) { 31 | bundle_transactions_t* bundle = NULL; 32 | flex_trit_t tx_trits[FLEX_TRIT_SIZE_8019]; 33 | flex_trit_t hash_trits_1[FLEX_TRIT_SIZE_243]; 34 | flex_trit_t hash_trits_2[FLEX_TRIT_SIZE_243]; 35 | iota_transaction_t tx; 36 | 37 | bundle_transactions_new(&bundle); 38 | flex_trits_from_trytes(tx_trits, NUM_TRITS_SERIALIZED_TRANSACTION, (const tryte_t*)TRYTES_2673_1, 39 | NUM_TRYTES_SERIALIZED_TRANSACTION, NUM_TRYTES_SERIALIZED_TRANSACTION); 40 | transaction_deserialize_from_trits(&tx, tx_trits, false); 41 | bundle_transactions_add(bundle, &tx); 42 | 43 | flex_trits_from_trytes(hash_trits_1, NUM_TRITS_HASH, (const tryte_t*)TRYTES_81_1, NUM_TRYTES_HASH, NUM_TRYTES_HASH); 44 | flex_trits_from_trytes(hash_trits_2, NUM_TRITS_HASH, (const tryte_t*)TRYTES_81_2, NUM_TRYTES_HASH, NUM_TRYTES_HASH); 45 | ta_pow(bundle, hash_trits_1, hash_trits_2, 9); 46 | 47 | // bundle to trytes 48 | iota_transaction_t* tx_iter = NULL; 49 | BUNDLE_FOREACH(bundle, tx_iter) { 50 | TEST_ASSERT_FALSE(memcmp(transaction_trunk(tx_iter), hash_trits_1, sizeof(flex_trit_t) * FLEX_TRIT_SIZE_243)); 51 | TEST_ASSERT_FALSE(memcmp(transaction_branch(tx_iter), hash_trits_2, sizeof(flex_trit_t) * FLEX_TRIT_SIZE_243)); 52 | } 53 | 54 | bundle_transactions_free(&bundle); 55 | } 56 | 57 | int main(void) { 58 | UNITY_BEGIN(); 59 | 60 | // Initialize logger 61 | if (ta_logger_init() != SC_OK) { 62 | return EXIT_FAILURE; 63 | } 64 | 65 | pow_logger_init(); 66 | pow_init(); 67 | RUN_TEST(test_pow_flex); 68 | RUN_TEST(test_pow_bundle); 69 | pow_destroy(); 70 | pow_logger_release(); 71 | return UNITY_END(); 72 | } 73 | -------------------------------------------------------------------------------- /tests/unit-test/test_timer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include 10 | #include "tests/test_define.h" 11 | #include "utils/timer.h" 12 | 13 | int finite_thread(void *args) { 14 | long x = *(int *)args; 15 | pthread_exit((void *)x); 16 | } 17 | 18 | int infinite_thread(void *args) { 19 | long x = *(int *)args; 20 | while (1) { 21 | // Cancellation point 22 | pthread_testcancel(); 23 | } 24 | pthread_exit((void *)x); 25 | } 26 | 27 | void test_timer_finite(void) { 28 | const struct itimerspec timeout = {.it_interval = {.tv_sec = 0, .tv_nsec = 0}, 29 | .it_value = {.tv_sec = 1, .tv_nsec = 0}}; 30 | int *args = (int *)malloc(sizeof(int)); 31 | TEST_ASSERT(args != NULL); 32 | *args = 7; 33 | 34 | ta_timer_t *timer_id = ta_timer_start(&timeout, finite_thread, args); 35 | TEST_ASSERT(timer_id != NULL); 36 | 37 | int *rval; 38 | int ret = ta_timer_stop(timer_id, (void **)&rval); 39 | TEST_ASSERT(ret == SC_OK); 40 | TEST_ASSERT((intptr_t)rval == *args); 41 | 42 | free(args); 43 | } 44 | 45 | void test_timer_infinite(void) { 46 | const struct itimerspec timeout = {.it_interval = {.tv_sec = 0, .tv_nsec = 0}, 47 | .it_value = {.tv_sec = 1, .tv_nsec = 0}}; 48 | int *args = (int *)malloc(sizeof(int)); 49 | TEST_ASSERT(args != NULL); 50 | *args = 7; 51 | 52 | ta_timer_t *timer_id = ta_timer_start(&timeout, infinite_thread, args); 53 | TEST_ASSERT(timer_id != NULL); 54 | 55 | int *rval; 56 | int ret = ta_timer_stop(timer_id, (void **)&rval); 57 | TEST_ASSERT(ret == SC_UTILS_TIMER_EXPIRED); 58 | 59 | free(args); 60 | } 61 | 62 | int main(void) { 63 | UNITY_BEGIN(); 64 | 65 | // Initialize logger 66 | if (ta_logger_init() != SC_OK) { 67 | return EXIT_FAILURE; 68 | } 69 | 70 | timer_logger_init(); 71 | RUN_TEST(test_timer_finite); 72 | RUN_TEST(test_timer_infinite); 73 | timer_logger_release(); 74 | return UNITY_END(); 75 | } 76 | -------------------------------------------------------------------------------- /tests/unit-test/test_tryte_byte_conv.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include "tests/test_define.h" 13 | #include "utils/tryte_byte_conv.h" 14 | 15 | void setUp(void) {} 16 | 17 | void tearDown(void) {} 18 | 19 | void test_bytes_trytes_bytes_conv(void) { 20 | const uint8_t test_str[1024] = {48, 48, 48, 48, 48, 0, 48, 48, 48, 48, 48, 48, 48, 48, 21 | 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48}; 22 | const int str_len = 28; 23 | char enc_msg[1024] = {0}, dec_msg[1024] = {0}; 24 | 25 | bytes_to_trytes(test_str, str_len, enc_msg); 26 | trytes_to_bytes((uint8_t*)enc_msg, strlen(enc_msg), dec_msg); 27 | 28 | TEST_ASSERT_EQUAL_INT8_ARRAY(test_str, dec_msg, str_len); 29 | } 30 | 31 | int main(void) { 32 | UNITY_BEGIN(); 33 | 34 | RUN_TEST(test_bytes_trytes_bytes_conv); 35 | 36 | return UNITY_END(); 37 | } 38 | -------------------------------------------------------------------------------- /third_party/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_import( 4 | name = "dcurl", 5 | hdrs = [ 6 | "dcurl/src/dcurl.h", 7 | "dcurl/src/trinary.h", 8 | ], 9 | shared_library = "dcurl/build/libdcurl.so", 10 | ) 11 | 12 | cc_library( 13 | name = "mosquitto", 14 | srcs = ["mosquitto/lib/libmosquitto.so.1"], 15 | hdrs = [ 16 | "mosquitto/config.h", 17 | "mosquitto/lib/mosquitto.h", 18 | "mosquitto/lib/mqtt_protocol.h", 19 | ], 20 | ) 21 | -------------------------------------------------------------------------------- /third_party/BUILD.hiredis: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "hiredis", 3 | srcs = [ 4 | "dict.h", 5 | "fmacros.h", 6 | "hiredis.h", 7 | "net.h", 8 | "read.h", 9 | "sdsalloc.h", 10 | "sds.h", 11 | "dict.c", 12 | "hiredis.c", 13 | "net.c", 14 | "read.c", 15 | "sds.c", 16 | ], 17 | hdrs = [ 18 | "hiredis.h", 19 | "net.h", 20 | ], 21 | include_prefix = "hiredis", 22 | copts = [ 23 | "-Wno-unused-function" 24 | ], 25 | visibility = ["//visibility:public"], 26 | ) 27 | -------------------------------------------------------------------------------- /third_party/flatcc.BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "flatcc_0_6_0", 3 | srcs = glob(["src/*.c"]), 4 | hdrs = glob( 5 | [ 6 | "include/flatcc/*.h", 7 | "include/flatcc/**/*.h", 8 | ], 9 | ), 10 | include_prefix = "flatcc", 11 | strip_include_prefix = "include/flatcc", 12 | visibility = ["//visibility:public"], 13 | ) 14 | -------------------------------------------------------------------------------- /third_party/mbedtls.BUILD: -------------------------------------------------------------------------------- 1 | cc_library( 2 | name = "mbedtls_2_16_6", 3 | srcs = glob(["library/*.c"]), 4 | hdrs = glob(["include/mbedtls/*.h"]) + glob(["include/psa/*.h"]), 5 | include_prefix = "mbedtls", 6 | strip_include_prefix = "include/mbedtls", 7 | visibility = ["//visibility:public"], 8 | ) 9 | -------------------------------------------------------------------------------- /third_party/third_party.bzl: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 2 | 3 | def load_hiredis(): 4 | http_archive( 5 | name = "hiredis", 6 | url = "https://github.com/redis/hiredis/archive/v0.14.0.tar.gz", 7 | strip_prefix = "hiredis-0.14.0", 8 | sha256 = 9 | "042f965e182b80693015839a9d0278ae73fae5d5d09d8bf6d0e6a39a8c4393bd", 10 | build_file = "//third_party:BUILD.hiredis", 11 | ) 12 | 13 | def third_party_deps(): 14 | load_hiredis() 15 | -------------------------------------------------------------------------------- /utils/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "fill_nines", 5 | srcs = ["fill_nines.h"], 6 | deps = [ 7 | "//common:ta_errors", 8 | "@org_iota_common//common/model:transaction", 9 | ], 10 | ) 11 | 12 | cc_library( 13 | name = "bundle_array", 14 | srcs = ["bundle_array.h"], 15 | deps = [ 16 | "//common:ta_errors", 17 | "@com_github_uthash//:uthash", 18 | "@org_iota_common//common/model:bundle", 19 | ], 20 | ) 21 | 22 | cc_library( 23 | name = "hash_algo_djb2", 24 | hdrs = ["hash_algo_djb2.h"], 25 | ) 26 | 27 | cc_library( 28 | name = "timer", 29 | srcs = ["timer.c"], 30 | hdrs = ["timer.h"], 31 | linkopts = [ 32 | "-lpthread", 33 | "-lrt", 34 | ], 35 | deps = [ 36 | "//common:ta_errors", 37 | "//common:ta_logger", 38 | ], 39 | ) 40 | 41 | cc_library( 42 | name = "char_buffer_str", 43 | srcs = ["char_buffer_str.h"], 44 | deps = ["@org_iota_common//utils:char_buffer"], 45 | ) 46 | 47 | cc_library( 48 | name = "tryte_byte_conv", 49 | srcs = ["tryte_byte_conv.c"], 50 | hdrs = ["tryte_byte_conv.h"], 51 | deps = ["//common:ta_errors"], 52 | ) 53 | 54 | cc_library( 55 | name = "cpuinfo", 56 | hdrs = ["cpuinfo.h"], 57 | ) 58 | -------------------------------------------------------------------------------- /utils/cache/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | cc_library( 4 | name = "cache", 5 | srcs = ["backend_redis.c"], 6 | hdrs = ["cache.h"], 7 | deps = [ 8 | "//common:ta_errors", 9 | "//common:ta_logger", 10 | "@hiredis", 11 | "@org_iota_common//common/trinary:flex_trit", 12 | ], 13 | ) 14 | -------------------------------------------------------------------------------- /utils/char_buffer_str.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_CHAR_BUFFER_STR_H_ 10 | #define UTILS_CHAR_BUFFER_STR_H_ 11 | 12 | #include 13 | #include 14 | #include "common/ta_errors.h" 15 | #include "utils/char_buffer.h" 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | /** 22 | * @file utils/char_buffer_str.h 23 | * @brief Get string from 'char_buffer_t' object. 24 | */ 25 | 26 | /** 27 | * @brief Get string from char_buffer_t 28 | * @param[in] char_buff char_buffer_t object 29 | * @param[out] json_result Response message 30 | * 31 | * @return 32 | * - SC_OK on success 33 | * - non-zero on error 34 | */ 35 | static inline status_t str_from_char_buffer(char_buffer_t* char_buff, char** json_result) { 36 | if (char_buff == NULL) { 37 | return SC_NULL; 38 | } 39 | 40 | *json_result = strdup(char_buff->data); 41 | if (*json_result == NULL) { 42 | return SC_OOM; 43 | } 44 | 45 | return SC_OK; 46 | } 47 | 48 | #ifdef __cplusplus 49 | } 50 | #endif 51 | 52 | #endif // UTILS_CHAR_BUFFER_STR_H_ 53 | -------------------------------------------------------------------------------- /utils/cpuinfo.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_CPUINFO_H_ 10 | #define UTILS_CPUINFO_H_ 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | /* Required for get_nprocs_conf() on Linux */ 17 | #if defined(__linux__) 18 | #include 19 | #endif 20 | 21 | /** 22 | * @file utils/cpuinfo.h 23 | * @brief Utility functions for acquiring CPU information. 24 | */ 25 | 26 | /* On Mac OS X, define our own get_nprocs_conf() */ 27 | #if defined(__APPLE__) || defined(__FreeBSD__) 28 | #include 29 | static unsigned int get_nprocs_conf() { 30 | int num_proc = 0; 31 | size_t size = sizeof(num_proc); 32 | if (sysctlbyname("hw.ncpu", &num_proc, &size, NULL, 0)) return 1; 33 | return (unsigned int)num_proc; 34 | } 35 | #endif 36 | 37 | /** 38 | * @brief Get the thread number per physical processor. 39 | * 40 | * - GNU/Linux: Acquire the thread number by parsing the CPU information. 41 | * - macOS: Acquire the thread number by doing the calculation of 42 | * (logical processor number / physical processor number). 43 | * @return The thread number per physical processor. 44 | * @retval 1 Hyperthreading disabled. 45 | * @retval 2 Hyperthreading enabled. 46 | * @retval -1 Unexpected error. 47 | */ 48 | static inline int get_nthds_per_phys_proc() { 49 | int nthread; 50 | #if defined(__linux__) 51 | FILE *fd; 52 | char nthd[4]; 53 | 54 | fd = popen("LC_ALL=C lscpu | grep 'Thread(s) per core' | awk '{printf $4}'", "r"); 55 | if (fd == NULL) return -1; 56 | if (fgets(nthd, sizeof(nthd), fd) == NULL) return -1; 57 | nthread = (int)strtol(nthd, NULL, 10); 58 | if (errno == ERANGE || nthread == 0) { 59 | pclose(fd); 60 | return -1; 61 | } 62 | 63 | if (pclose(fd) == -1) return -1; 64 | #elif defined(__APPLE__) 65 | FILE *fd; 66 | char p_proc[4], l_proc[4]; 67 | int phys_proc, logic_proc; 68 | 69 | fd = popen("sysctl hw.physicalcpu | awk '{printf $2}'", "r"); 70 | if (fd == NULL) return -1; 71 | if (fgets(p_proc, sizeof(p_proc), fd) == NULL) return -1; 72 | fd = popen("sysctl hw.logicalcpu | awk '{printf $2}'", "r"); 73 | if (fd == NULL) return -1; 74 | if (fgets(l_proc, sizeof(l_proc), fd) == NULL) return -1; 75 | phys_proc = (int)strtol(p_proc, NULL, 10); 76 | if (errno == ERANGE || phys_proc == 0) { 77 | return -1; 78 | } 79 | logic_proc = (int)strtol(l_proc, NULL, 10); 80 | if (errno == ERANGE || logic_proc == 0) { 81 | return -1; 82 | } 83 | 84 | nthread = logic_proc / phys_proc; 85 | 86 | if (pclose(fd) == -1) return -1; 87 | #else 88 | nthread = 1; 89 | #endif 90 | return nthread; 91 | } 92 | 93 | #ifdef __cplusplus 94 | } 95 | #endif 96 | #endif // UTILS_CPUINFO_H_ 97 | -------------------------------------------------------------------------------- /utils/fill_nines.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_FILL_NINES_H_ 10 | #define UTILS_FILL_NINES_H_ 11 | 12 | #include 13 | #include 14 | #include 15 | #include "common/model/transaction.h" 16 | #include "common/ta_errors.h" 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | /** 23 | * @file utils/fill_nines.h 24 | * @brief Padding string with 9s to assigned length 25 | * 26 | * 9 would be mapped to 0 in the trinary system of IOTA. Therefore, when the legnth of the input string is less than the 27 | * length of a certain IOTA transaction field, the user can use this function to use 9's as padding and make the input 28 | * string long enough. 29 | */ 30 | 31 | /** 32 | * @brief Patch input string with nines into assigned length. 33 | * 34 | * @param[out] new_str Output patched string 35 | * @param[in] old_str Input string which needs to be patched 36 | * @param[in] new_str_len assigned output string length 37 | * 38 | * @return 39 | * - SC_OK on success 40 | * - non-zero on error 41 | */ 42 | static inline status_t fill_nines(char* new_str, const char* const old_str, size_t new_str_len) { 43 | if (!new_str || !old_str || new_str_len != NUM_TRYTES_TAG) { 44 | return SC_NULL; 45 | } 46 | 47 | int old_str_len = strlen(old_str); 48 | strncpy(new_str, old_str, old_str_len); 49 | 50 | int diff = new_str_len - old_str_len; 51 | if (diff) { 52 | memset((new_str + old_str_len), '9', diff); 53 | } else { 54 | return SC_UTILS_WRONG_INPUT_ARG; 55 | } 56 | new_str[new_str_len] = '\0'; 57 | 58 | return SC_OK; 59 | } 60 | 61 | #ifdef __cplusplus 62 | } 63 | #endif 64 | 65 | #endif // UTILS_FILL_NINES_H_ 66 | -------------------------------------------------------------------------------- /utils/hash_algo_djb2.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | #ifndef UTILS_HASH_ALGO_DJB2_H_ 9 | #define UTILS_HASH_ALGO_DJB2_H_ 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | /** 16 | * @file utils/hash_algo_djb2.h 17 | * @brief Hash function DJB2 18 | */ 19 | 20 | // source http://www.cse.yorku.ca/~oz/hash.html 21 | static inline uint32_t hash_algo_djb2(char const* str) { 22 | uint32_t hash = 5381; 23 | int c; 24 | 25 | while ((c = *str++)) { 26 | hash = ((hash << 5) + hash) + c; 27 | } 28 | 29 | return hash; 30 | } 31 | 32 | #ifdef __cplusplus 33 | } 34 | #endif 35 | 36 | #endif // UTILS_HASH_ALGO_DJB2_H_ 37 | -------------------------------------------------------------------------------- /utils/timer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "timer.h" 10 | #include "common/logger.h" 11 | 12 | #define TIMER_LOGGER "timer" 13 | 14 | static logger_id_t logger_id; 15 | static pthread_mutex_t timer_lock = PTHREAD_MUTEX_INITIALIZER; 16 | struct _ta_timer_t { 17 | pthread_t *thread_id; 18 | timer_t *timer_id; 19 | }; 20 | 21 | void timer_logger_init() { logger_id = logger_helper_enable(TIMER_LOGGER, LOGGER_DEBUG, true); } 22 | 23 | int timer_logger_release() { 24 | logger_helper_release(logger_id); 25 | return 0; 26 | } 27 | 28 | static void handler(union sigval v) { 29 | ta_timer_t *args = (ta_timer_t *)v.sival_ptr; 30 | ta_log_error("timer_id: %p expired\n", *(args->timer_id)); 31 | 32 | /* Cancel the thread */ 33 | pthread_mutex_lock(&timer_lock); 34 | pthread_cancel(*(args->thread_id)); 35 | pthread_mutex_unlock(&timer_lock); 36 | } 37 | 38 | ta_timer_t *ta_timer_start(const struct itimerspec *timer, void *callback, void *args) { 39 | pthread_t *thread_id; 40 | timer_t *timer_id; 41 | ta_timer_t *ta_timer; 42 | 43 | thread_id = (pthread_t *)malloc(sizeof(pthread_t)); 44 | timer_id = (timer_t *)malloc(sizeof(timer_t)); 45 | ta_timer = (ta_timer_t *)malloc(sizeof(ta_timer_t)); 46 | struct sigevent sev = {.sigev_notify = SIGEV_THREAD, 47 | .sigev_signo = SIGALRM, 48 | .sigev_value.sival_ptr = (void *)ta_timer, 49 | .sigev_notify_function = handler}; 50 | if (thread_id == NULL || timer_id == NULL || ta_timer == NULL) goto cleanup; 51 | ta_timer->thread_id = thread_id; 52 | ta_timer->timer_id = timer_id; 53 | 54 | if (timer_create(CLOCK_REALTIME, &sev, timer_id) == -1) { 55 | ta_log_error("%s\n", "timer_create_failed"); 56 | goto cleanup; 57 | } else { 58 | ta_log_debug("Create timer_id: %p\n", *timer_id); 59 | } 60 | 61 | timer_settime(*timer_id, 0, timer, NULL); 62 | pthread_create(thread_id, NULL, callback, args); 63 | 64 | return ta_timer; 65 | 66 | cleanup: 67 | free(thread_id); 68 | free(timer_id); 69 | free(ta_timer); 70 | return NULL; 71 | } 72 | 73 | status_t ta_timer_stop(ta_timer_t *ta_timer, void **rval) { 74 | int ret = 0; 75 | ret = pthread_join(*(ta_timer->thread_id), rval); 76 | 77 | if (ret) { 78 | ta_log_error("pthread_join failed: %d\n", ret); 79 | return SC_UTILS_TIMER_ERROR; 80 | } 81 | 82 | pthread_mutex_lock(&timer_lock); 83 | ret = timer_delete(*(ta_timer->timer_id)); 84 | free(ta_timer->timer_id); 85 | free(ta_timer->thread_id); 86 | free(ta_timer); 87 | pthread_mutex_unlock(&timer_lock); 88 | 89 | if (ret) { 90 | ta_log_error("timer_delete failed: %d\n", ret); 91 | return SC_UTILS_TIMER_ERROR; 92 | } 93 | 94 | if (*rval == PTHREAD_CANCELED) { 95 | return SC_UTILS_TIMER_EXPIRED; 96 | } 97 | 98 | return SC_OK; 99 | } 100 | -------------------------------------------------------------------------------- /utils/timer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_TIMER_H_ 10 | #define UTILS_TIMER_H_ 11 | 12 | #ifdef __cplusplus 13 | extern "C" { 14 | #endif 15 | 16 | /** 17 | * @file utils/timer.h 18 | * @brief Implementation of one-shot timer. 19 | * 20 | * The wrapper wraps and executes the callback, executes in a different thread, and cancels the thread after the given 21 | * timeout. 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "common/ta_errors.h" 30 | 31 | typedef struct _ta_timer_t ta_timer_t; 32 | 33 | /** 34 | * Create and initialize a ta_timer 35 | * @param[in] timer Timeout to wait until callback being halted 36 | * @param[in] callback The actual function being called 37 | * @param[in] args The arguments to pass to the callback function 38 | * 39 | * @return 40 | * - ta_timer pointer 41 | * - NULL on error 42 | */ 43 | ta_timer_t *ta_timer_start(const struct itimerspec *timer, void *callback, void *args); 44 | 45 | /** 46 | * Stop a timer and block the current thread until timeout or callback finishes. 47 | * @param[in] ta_timer timer obtained by ta_timer_start 48 | * @param[out] rval Return value of the callback 49 | * 50 | * @return 51 | * - SC_OK on success 52 | * - non zero on error 53 | */ 54 | status_t ta_timer_stop(ta_timer_t *ta_timer, void **rval); 55 | 56 | #ifdef __cplusplus 57 | } 58 | #endif 59 | 60 | #endif // UTILS_TIMER_H_ 61 | -------------------------------------------------------------------------------- /utils/tryte_byte_conv.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #include "tryte_byte_conv.h" 10 | #include 11 | #include 12 | 13 | void bytes_to_trytes(unsigned char const *const input, uint16_t input_len, char *output) { 14 | const char tryte_alphabet[] = "9ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 15 | uint8_t dec = 0, lower = 0, upper = 0; 16 | 17 | for (uint16_t i = 0; i < input_len; i++) { 18 | dec = input[i]; 19 | upper = (dec >> 4) & 15; 20 | lower = dec & 15; 21 | output[2 * i] = tryte_alphabet[upper]; 22 | output[2 * i + 1] = tryte_alphabet[lower]; 23 | } 24 | } 25 | 26 | void trytes_to_bytes(unsigned char const *const input, uint32_t input_len, char *const output) { 27 | uint8_t upper = 0, lower = 0; 28 | 29 | for (uint16_t i = 0; i < input_len; i += 2) { 30 | if (input[i] == '9') { 31 | upper = 0; 32 | } else { 33 | upper = input[i] - 64; 34 | } 35 | if (input[i + 1] == '9') { 36 | lower = 0; 37 | } else { 38 | lower = input[i + 1] - 64; 39 | } 40 | 41 | output[i / 2] = (upper << 4) | lower; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /utils/tryte_byte_conv.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors 3 | * All Rights Reserved. 4 | * This is free software; you can redistribute it and/or modify it under the 5 | * terms of the MIT license. A copy of the license can be found in the file 6 | * "LICENSE" at the root of this distribution. 7 | */ 8 | 9 | #ifndef UTILS_TRYTE_BYTE_CONV_H 10 | #define UTILS_TRYTE_BYTE_CONV_H 11 | 12 | #include 13 | 14 | #ifdef __cplusplus 15 | extern "C" { 16 | #endif 17 | 18 | /** 19 | * @file utils/tryte_byte_conv.h 20 | * @brief Conversion between trytes and bytes. 21 | */ 22 | 23 | /** 24 | * @brief Convert bytes to trytes 25 | * 26 | * @param[in] input The pointer to bytes array 27 | * @param[in] len Length of bytes array 28 | * @param[out] output The pointer to output array 29 | */ 30 | void bytes_to_trytes(unsigned char const *const input, uint16_t len, char *output); 31 | 32 | /** 33 | * @brief Convert trytes to bytes 34 | * 35 | * @param[in] input The pointer to trytes array 36 | * @param[in] input_len Length of trytes array 37 | * @param[out] output The pointer to output array 38 | */ 39 | void trytes_to_bytes(unsigned char const *const input, uint32_t input_len, char *const output); 40 | 41 | #ifdef __cplusplus 42 | } 43 | #endif 44 | 45 | #endif // UTILS_TRYTE_BYTE_CONV_H 46 | --------------------------------------------------------------------------------