diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..669754923b366865fe2a5a864b9cec3de15818d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.o +*.exe +bin/* +.vscode/* +.idea/* +build/* \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f006d22e00219d067cce78178cad68b1bcf2b66e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.5) +project(ql_csdk C) + +set(CMAKE_C_STANDARD 11) + +include_directories(include) +include_directories(include/base) +include_directories(include/proto) +include_directories(include/types) +include_directories(test) + +add_executable(ql_csdk + demo/main.c + include/base/ecc.h + include/base/hash.h + include/base/json.h + include/base/keccak256.h + include/base/log.h + include/base/x509.h + include/base/md5.h + include/proto/account.h + include/proto/largefile.h + include/types/ql_error_type.h + include/types/ql_type.h + src/base/ecc.c + src/base/hash.c + src/base/json.c + src/base/keccak256.c + src/base/log.c + src/base/md5.c + src/base/x509.c + src/proto/account.c + src/proto/largefile.c +) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bfdf9812ef79f93d10126b57b208de13954bc54b --- /dev/null +++ b/Makefile @@ -0,0 +1,86 @@ +CC = gcc +CFLAGS = -g -O -Wall +CFLAGS += -fprofile-arcs -ftest-coverage + +TOP_PATH = $(shell pwd) +HEAD_PATH = $(TOP_PATH)/include +SRC_PATH = $(TOP_PATH)/src +OUT_PATH = $(TOP_PATH)/bin +TEST_PATH = $(TOP_PATH)/test +DEMO_PATH = $(TOP_PATH)/demo + +TARGET_TEST = $(OUT_PATH)/AllTest +TARGET_MAIN = $(OUT_PATH)/main +OBJS = $(OUT_PATH)/log.o $(OUT_PATH)/keccak256.o $(OUT_PATH)/ecc.o $(OUT_PATH)/hash.o $(OUT_PATH)/account.o $(OUT_PATH)/largefile.o $(OUT_PATH)/x509.o $(OUT_PATH)/json.o $(OUT_PATH)/md5.o +OBJS_TEST = $(OBJS) $(OUT_PATH)/all_test.o $(OUT_PATH)/CuTest.o $(OUT_PATH)/x509_test.o $(OUT_PATH)/account_test.o $(OUT_PATH)/keccak256_test.o $(OUT_PATH)/ecc_test.o +OBJS_MAIN = $(OBJS) $(OUT_PATH)/main.o + +CFLAGS += -I$(HEAD_PATH)/types/ +CFLAGS += -I$(HEAD_PATH)/base/ +CFLAGS += -I$(HEAD_PATH)/proto/ + +$(TARGET_MAIN): $(OBJS_MAIN) + $(CC) $(CFLAGS) $^ -o $@ + +$(TARGET_TEST): $(OBJS_TEST) + $(CC) $(CFLAGS) $^ -o $@ + +# ------- demo ------- +$(OUT_PATH)/main.o: $(DEMO_PATH)/main.c + $(CC) $(CFLAGS) -c $^ -o $@ + +# ------- test------- +$(OUT_PATH)/all_test.o: $(TEST_PATH)/all_test.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/CuTest.o: $(TEST_PATH)/CuTest.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/x509_test.o: $(TEST_PATH)/x509_test.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/account_test.o: $(TEST_PATH)/account_test.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/keccak256_test.o: $(TEST_PATH)/keccak256_test.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/ecc_test.o: $(TEST_PATH)/ecc_test.c + $(CC) $(CFLAGS) -c $^ -o $@ + +# ------- base ------- +$(OUT_PATH)/log.o: $(SRC_PATH)/base/log.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/keccak256.o: $(SRC_PATH)/base/keccak256.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/ecc.o: $(SRC_PATH)/base/ecc.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/hash.o: $(SRC_PATH)/base/hash.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/x509.o: $(SRC_PATH)/base/x509.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/json.o: $(SRC_PATH)/base/json.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/md5.o: $(SRC_PATH)/base/md5.c + $(CC) $(CFLAGS) -c $^ -o $@ +# ------- proto ------- +$(OUT_PATH)/account.o: $(SRC_PATH)/proto/account.c + $(CC) $(CFLAGS) -c $^ -o $@ + +$(OUT_PATH)/largefile.o: $(SRC_PATH)/proto/largefile.c + $(CC) $(CFLAGS) -c $^ -o $@ + +all: prepare $(TARGET_MAIN) $(TARGET_TEST) + + +prepare: + mkdir -p $(OUT_PATH) + +clean: + rm -rf $(OUT_PATH) diff --git a/README.en.md b/README.en.md deleted file mode 100644 index cd6e641502fa0b87088bae427ba6c1864cf0878a..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# security_block_chain - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md index a3184234d20cf935008ab646e1f402286f41742d..df4f6c9a90255ef274195b5a3f17d50092b1a19b 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,365 @@ -# security_block_chain +# CSDK接口文档 +- [说明](#section10) + - [概述](#section11) + - [项目功能](#section12) + - [项目结构](#section13) + - [运行环境](#section14) +- [接口说明](#section20) + - [日志打印回调函数](#section21) + - [日志时间回调函数](#section22) + - [日志静默函数](#section23) + - [日志等级函数](#section24) + - [时间戳回调函数](#section25) + - [使用x509证书初始化账户函数](#section26) + - [使用json初始化账户函数](#section27) + - [创建交易函数](#section28) + - [交易格式化为字符串函数](#section29) + - [创建大文件对象函数](#section210) + - [计算大文件md5散列值函数](#section211) + - [获取大文件md5散列值函数](#section212) + - [格式化大文件信息为字符串函数](#section213) + - [释放大文件对象函数](#section214) -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +--- +### 说明 +#### 概述 +本文档是Openharmony上链软件包的接口文档,旨在描述该软件包的使用说明、使用方式,为用户基于该软件包的应用开发提供说明。 +CSDK软件包在iot场景下提供了数据格式化和处理的功能,为设备数据上链提供了可能。该软件包采用回调函数方式定义、设置外部接口,支持椭圆曲线密码学算法,编程风格符合《C语言编程规范》,具有便于移植、调试方便、代码轻量化等特点。 +#### 项目功能 + - 支持keccak256哈希运算。 + - 支持secp256k1签名、验签、共享密钥,支持公钥恢复算法,支持rfc6979确定性随机数算法。 + - 支持解析pem格式的X.509证书。 + - 支持趣链jsonrpc接口,实现iot需要的extra存证接口。 -#### 软件架构 -软件架构说明 +#### 项目结构 -#### 安装教程 -1. xxxx -2. xxxx -3. xxxx +项目主要包含以下内容: +- bin:为.o文件、可执行文件、.gcda文件、.gcno文件、代码覆盖率报告等的输出目录。 +- demo:项目的demo文件目录。 +- test:项目各模块单测的目录,其中CuTest为一个轻量级的测试框架,其余文件为各模块的测试用例。 +- include:头文件目录。 +- src:源文件目录。 +其中,在二级目录中: +- base:为基础模块的目录,ecc为计算secp256k1模块,hash为计算rfc6979的模块,keccak256为计算哈希的模块,log为日志模块,x509为解析pem证书的模块,该模块作为基础功能,通常仅会被proto文件夹下的模块调用,不会直接暴露给用户。 +- proto:为协议模块的目录,account为用户账户模块,该模块将直接暴露给用户调用,从而实现extra存证的功能。 +- types:为类型模块的目录,其中Oh_error_type定义了各模块的错误编码的定义,Oh_type定义了统一的数据类型格式,base目录和proto目录下的所有变量均采用该类型。types仅在include文件夹下存在。 +项目结构如下所示: +``` +. +├── CMakeLists.txt # CMake构建文件 +├── demo +│   └── main.c # 示例程序 +├── include +│   ├── base +│   │   ├── ecc.h # ecc签名相关头文件 +│   │   ├── hash.h # rfc6979 hash计算头文件 +│   │   ├── json.h # cjson相关调用头文件 +│   │   ├── keccak256.h # keccak256 hash算法相关头文件 +│   │   ├── log.h # 日志打印相关头文件 +│   │   ├── md5.h # md5计算相关头文件 +│   │   └── x509.h # x509证书相关头文件 +│   ├── proto +│   │   ├── account.h # 账户结构相关头文件 +│   │   └── largefile.h # 大文件传输相关头文件 +│   └── types +│   ├── ql_error_type.h # 自定义错误类型 +│   └── ql_type.h # 自定义数据类型 +├── Makefile # Make构建文件 +├── README.md # 说明文档 +├── src +│   ├── base +│   │   ├── ecc.c # ecc签名相关实现 +│   │   ├── hash.c # rfc6979 hash计算相关实现 +│   │   ├── json.c # cjson相关调用实现 +│   │   ├── keccak256.c # keccak256 hash算法相关实现 +│   │   ├── log.c # 日志打印相关实现 +│   │   ├── md5.c # md5计算相关实现 +│   │   └── x509.c # x509证书相关实现 +│   └── proto +│   ├── account.c # 账户操作相关实现 +│   └── largefile.c # 大文件传输相关实现 +└── test + ├── account_test.c # 账户操作相关测试 + ├── all_test.c # 集成测试 + ├── CuTest.c # CuTest基础测试实现 + ├── CuTest.h # CuTest基础实现头文件 + ├── ecc_test.c # ecc相关测试 + ├── keccak256_test.c # keccak256相关测试 + └── x509_test.c # x509相关测试 +``` -#### 使用说明 -1. xxxx -2. xxxx -3. xxxx +#### 运行环境 +编译环境:gcc 3.0+(支持C99标准)
+运行环境:32位单片机裸机、Linux系统、FreeRTOS系统 -#### 参与贡献 +--- +### 接口说明 +#### 日志打印回调函数 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +项目|内容 +:---:|:--: +函数名称|SetPrintLogCallback +功能描述|设置打印日志的回调函数 +参数|函数指针 +返回值|无 +备注|若不设置,则无法打印日志 -#### 特技 +示例: +``` +void print_log_func(char *content){ + printf("%s",content); +} -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +SetPrintLogCallback(print_log_func); +``` +#### 日志时间回调函数 + +项目|内容 +:---:|:--: +函数名称|SetGetTimeCallback +功能描述|设置日志打印时间的回调函数 +参数|函数指针 +返回值|无 +备注|若不设置,则日志时间无法正常显示 + + +示例: +``` +void print_log_time(char * time_buf, int size){ +#if (defined(__unix)) || (defined(_WIN32) || defined(_WIN64)) + time_t t = time(NULL); + struct tm* tp = localtime(&t); + time_buf[strftime(time_buf, size, "%H:%M:%S", tp)] = '\0'; +#else + time_buf[0] = '\0'; +#endif +} + +SetGetTimeCallback(print_log_time); +``` + +#### 日志静默函数 + +项目|内容 +:---:|:--: +函数名称|LogSetQuiet +功能描述|设置日志是否需要静默,即设置是否打印日志 +参数|LOG_QUIET_FALSE:不启用,即打印
LOG_QUIET_TRUE:启用,即不打印日志 +返回值|无 +备注|无 + + +示例: +``` +LogSetQuiet(LOG_QUIET_FALSE); +``` + +#### 日志等级函数 +项目|内容 +:---:|:--: +函数名称|LogSetLevel +功能描述|设置日志打印的等级 +参数|LOG_DEBUG:调试等级
LOG_INFO:信息等级
LOG_WARN:警告等级
LOG_ERROR:错误等级 +返回值|无 +备注|无 + + +示例: +``` +LogSetLevel(LOG_DEBUG); +``` +#### 时间戳回调函数 +项目|内容 +:---:|:--: +函数名称|AccountSetTimeFunc +功能描述|设置时间戳获取函数函数指针 +参数|函数指针 +返回值|无 +备注|单位为ns,若错误设置或不设置,将直接导致数据无法上链。 + + +示例: +``` +OhErrType native_get_time(OhInt64Type *dst) { + struct timeval t; + gettimeofday(&t,NULL); + *dst = (OhInt64Type)t.tv_sec * 1000000000 + (Oh_int64_t)t.tv_usec*1000; // ns + return ACCOUNT_SUCCESS; +} + +AccountSetTimeFunc(native_get_time); +``` +#### 使用x509证书初始化账户函数 +项目|内容 +:---:|:----------: +函数名称|AccountInitX509 +功能描述|使用x509证书初始化账户 +参数|acc:AccountType*类型的账户对象
str: OhByteType*类型的私钥证书 +返回值|参见account.h文件内的错误宏定义 +备注|需要先声明一个AccountType类型的账户,之后再使用私钥证书初始化该账户。 + + +示例: +``` +OhByteType priKey[] = "-----BEGIN EC PRIVATE KEY-----\n" +"MHQCAQEEIAICAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBoAcGBSuBBAAK\n" +"oUQDQgAExUK0Fv9I2BvhZR8lVIwG0ZHPowy4GvUZEYMM8uASzJ/3/Xbd0VlMYHFg\n" + "qXkEMxUZJABjkW2PNh3vU4lzCsLXRA==\n" + "-----END EC PRIVATE KEY-----"; +AccountTpye myAccount; +OhErrType res = AccountInitX509(&myAccount, priKey); +``` + +#### 使用json初始化账户函数 +项目|内容 +:---:|:-----: +函数名称|AccountInitJson +功能描述|使用json类型的账户数据初始化账户 +参数|acc:AccountType* 类型的账户对象
str: OhByteType* 类型的json账户数据 +返回值|参见account.h文件内的错误宏定义 +备注|需要先声明一个AccountType类型的账户,之后再初始化该账户。 + + +示例: +``` +OhByteType acc_json[] = +"{\"version\":\"4.0\",\"algo\":\"0x00\",\"privateKey\":\"0202020101010101010101010101010101010101010101010101010101010101\",\"publicKey\":\"04c542b416ff48d81be1651f25548c06d191cfa30cb81af51911830cf2e012cc9ff7fd76ddd1594c607160a97904331519240063916d8f361def5389730ac2d744\",\"address\":\"469339bdf3d3621bebea36c308de77939424e34e\"}"; +AccountType myAccount; +OhErrType res = AccountInitJson(&myAccount, acc_json); +``` + +#### 创建交易函数 +项目|内容 +:---:|:-----: +函数名称|TxSendNew +功能描述|创建交易 +参数|tx:TxType* 类型,指向交易对象
acc:AccountType* 类型,指向账户对象
to:OhByteType* 类型,为交易的目的地址
val:OhInt32Type类型,为交易的val值,存证则设置为0
ex:OhByteType* 类型,为存证的信息,通常为json格式
exid:OhByteType* 类型,为extraid的信息,需要为带[]的字符串格式,中括号内的字符串可以用逗号隔开 +返回值|参见account.h文件内的错误宏定义 +备注|返回值直接通过http post请求发送至区块链,即可完成数据上链 + + +示例: +``` +TxType tx; +OhByteType ex[] = "{\"id\":\"0F384\",\"name\":\"tom\",\"class\":\"0808\"}"; +res = TxSendNew(&tx, &myAccount, myAccount.addr, 0, ex, (OhByteType *)"[\"123\"]"); +``` + +#### 交易格式化为字符串函数 +项目|内容 +:---:|:-----: +函数名称|TxPrint +功能描述|将交易结构体格式化为字符串 +参数|tx:TxType* 类型,指向交易对象
fmtType:FORMAT_TYPE类型,为封装交易的类型,具体字段可参见宏定义
method: OhByteType* 类型,为交易的类型,具体字段可参见宏定义
outBuf:OhByteType* 类型,指向字符串的存储空间
outBufLen:字符串存储空间的长度 +返回值|参见account.h文件内的错误宏定义 +备注|若字符串存储空间的长度小于实际需要的长度,则格式化失败。 + + +示例: +``` +OhByteType out[700]; + res = TxPrint(&tx, ORIGIN_MSG, TX_TYPE_SENDTRANSACTION, out, 700); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + } + else{ + log_debug("ok"); + } +``` +#### 创建大文件对象函数 +项目|内容 +:---:|:-----: +函数名称|FileInfoNew +功能描述|新建大文件对象 +参数|f:LargefileType*类型,指向大文件对象
path:OhByteType*类型,文件路径
name:OhByteType*类型,上传大文件时使用的文件名
des:OhByteType*类型,上传大文件时使用的文件描述
node:OhByteType*类型,节点白名单,若为空,则为所有节点可见
user:OhByteType*类型,用户白名单,若为空,则为所有用户可见 +返回值|参见largefile.h文件内的错误宏定义 +备注| + + +示例: +``` +LargefileType f; + +OhByteType* file_name = (OhByteType*)"data.png"; + +res = FileInfoNew(&f, file_name, (OhByteType*)"pic_upload_name.png", (OhByteType*)"des: test largefile", (OhByteType*)"", (OhByteType*)""); + +if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + return res; +} +``` +#### 计算大文件md5散列值函数 +项目|内容 +:---:|:-----: +函数名称|FileCalMd5 +功能描述|计算大文件md5散列值 +参数|f:LargefileType*类型,指向大文件对象 +返回值|参见largefile.h文件内的错误宏定义 +备注|该方法将打开f对象下path指向的文件 + + +示例: +``` +res = FileCalMd5(&f); +if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + return res; +} +``` +#### 获取大文件md5散列值函数 +项目|内容 +:---:|:-----: +函数名称|FileGetHash +功能描述|将大文件md5散列值的结果导出到外部空间中 +参数|f:LargefileType*类型,指向大文件对象
buf:OhByteType*类型,指向存储空间
bufLen:存储空间的长度 +返回值|参见largefile.h文件内的错误宏定义 +备注| + + +示例: +``` +OhByteType hash[35]; +res = FileGetHash(&f, hash, 35); +if(res != FILE_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; +} +``` +#### 格式化大文件信息为字符串函数 +项目|内容 +:---:|:-----: +函数名称|FileInfoFormat +功能描述|将大文件信息格式化为extra json格式 +参数|f:LargefileType*类型,指向大文件对象
buf:OhByteType*类型,指向存储空间
bufLen:存储空间的长度 +返回值|参见largefile.h文件内的错误宏定义 +备注| + + +示例: +``` +OhByteType buf[400]; +res = FileInfoFormat(&f, buf, 400); +if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + return res; +} +``` +#### 释放大文件对象函数 +项目|内容 +:---:|:-----: +函数名称|FileInfoFree +功能描述|释放大文件对象 +参数|f:LargefileType*类型,指向大文件对象 +返回值|无 +备注|若不释放大文件对象,则可能会造成内存泄漏 + + +示例: +``` +FileInfoFree(&f); +``` \ No newline at end of file diff --git a/demo/main.c b/demo/main.c new file mode 100644 index 0000000000000000000000000000000000000000..2f2b5a8b9b81b010110cc0f41030b89d2fc3c67a --- /dev/null +++ b/demo/main.c @@ -0,0 +1,161 @@ +#include +#include "log.h" +#include "ql_type.h" +#include "account.h" +#include "largefile.h" +// ----------------------- +// unix system +// ----------------------- +#include +#include + +void print_log_func(char *content){ + printf("%s",content); +} + +void print_log_time(char * time_buf, int size){ +#if (defined(__unix)) || (defined(_WIN32) || defined(_WIN64)) + time_t t = time(NULL); + struct tm* tp = localtime(&t); + time_buf[strftime(time_buf, size, "%H:%M:%S", tp)] = '\0'; +#else + time_buf[0] = '\0'; +#endif +} + +OhErrType native_get_time(OhInt64Type *dst) { + struct timeval t; + gettimeofday(&t,NULL); + *dst = (OhInt64Type)t.tv_sec * 1000000000 + (OhInt64Type)t.tv_usec*1000; // ns + return ACCOUNT_SUCCESS; +} + +int test_sign(){ + struct timeval start, end; + +// OhByteType acc_json[] = "{\"version\":\"4.0\",\"algo\":\"0x03\",\"privateKey\":\"0202020101010101010101010101010101010101010101010101010101010101\",\"publicKey\":\"04c542b416ff48d81be1651f25548c06d191cfa30cb81af51911830cf2e012cc9ff7fd76ddd1594c607160a97904331519240063916d8f361def5389730ac2d744\",\"address\":\"469339bdf3d3621bebea36c308de77939424e34e\"}"; + OhByteType acc_json[] = "{\"address\":\"8399b2b7e104cebb8b8938a2c79e26cb4733b0b5\",\"algo\":\"0x03\",\"version\":\"4.0\",\"publicKey\":\"049c660da3c16fd0df820b747d82344916db69d7553d2456323c820f1b1f4f225986d1f16cde06d99d94aa8998f0a14b6aeca21d7cad7670516cc911e4b035f9e5\",\"privateKey\":\"8747be107feb7959f4e8c8936a31aac5ffd4ed4d62d0e9edee2854531e62ea5e\"}"; + log_debug("----account test----"); + //create account + AccountType my_account; + OhErrType res = AccountInitJson(&my_account, acc_json); + if(res != ACCOUNT_SUCCESS) { + log_error("account_new failed : %d", res); + return res; + } + // create tx + gettimeofday(&start,NULL); + TxType tx; + OhByteType ex[] = "{\"id\":\"0F384\",\"name\":\"tom\",\"class\":\"0808\"}"; + res = TxSendNew(&tx, &my_account, my_account.addr, 0, ex, (OhByteType *)"[\"12345\",\"54321\"]"); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; + } + log_debug("================================================================================="); + OhByteType out[1024]; + res = TxPrint(&tx, ADD_CURL_BODY,TX_TYPE_SENDTRANSACTION, out, 1024); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; + } + log_info("%s",out); + log_debug("=======COPY==THE==ABOVE==COMMAND==TO==THE==COMMAND==LINE==AND==EXECUTE==IT======="); + gettimeofday(&end,NULL); + log_debug("demo run time is %ldus",(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec)); + + return 0; +} + +int test_largefile(){ + // create account + OhByteType priKey[] = "-----BEGIN EC PRIVATE KEY-----\n" + "MHQCAQEEIAICAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBoAcGBSuBBAAK\n" + "oUQDQgAExUK0Fv9I2BvhZR8lVIwG0ZHPowy4GvUZEYMM8uASzJ/3/Xbd0VlMYHFg\n" + "qXkEMxUZJABjkW2PNh3vU4lzCsLXRA==\n" + "-----END EC PRIVATE KEY-----"; + AccountType my_account; + OhErrType res = AccountInitX509(&my_account, priKey); + if(res != ACCOUNT_SUCCESS) { + log_error("test_account_x509 failed : %d", res); + return res; + } + // create large file + LargefileType f; + OhByteType* file_name = (OhByteType*)"../data.png"; + res = FileInfoNew(&f, file_name, (OhByteType*)"pic_upload_name.png", (OhByteType*)"des: test largefile", (OhByteType*)"", (OhByteType*)""); + if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + FileInfoFree(&f); + return res; + } + res = FileCalMd5(&f); + if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + FileInfoFree(&f); + return res; + } + OhByteType buf[400]; + res = FileInfoFormat(&f, buf, 400); + if(res != FILE_SUCCESS){ + log_error("test_largefile failed : %d", res); + FileInfoFree(&f); + return res; + } + OhByteType hash[35]; + res = FileGetHash(&f, hash, 35); + if(res != FILE_SUCCESS) { + log_error("TxSendNew failed : %d", res); + FileInfoFree(&f); + return res; + } + FileInfoFree(&f); + // create extraid + OhByteType extraid[100]; + memset(extraid,0,sizeof(extraid)); + strcat((char*)extraid, "["); + strcat((char*)extraid, (char*)hash); // add hash + strcat((char*)extraid, ","); + strcat((char*)extraid, (char*)"\"13579\""); // add other extraid + strcat((char*)extraid, "]"); + // create tx + TxType tx; + res = TxSendNew(&tx, &my_account, my_account.addr, 0, buf, extraid); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; + } + OhByteType out[1100]; + log_debug("=============================== UPLOAD FILE ====================================="); + memset(out, 0, sizeof(out)); + res = TxPrint(&tx, ORIGIN_MSG,TX_TYPE_UPLOAD, out, 1100); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; + } + log_info("curl -H 'type: upload' -H 'params: %s' --data-binary @%s -H \"Content-Type: application/octet-stream\" -H \"Expect: \" 8.136.20.47:8081",out,file_name); + log_debug("============================== DOWNLOAD FILE ====================================="); + memset(out, 0, sizeof(out)); + res = TxPrint(&tx, ORIGIN_MSG,TX_TYPE_DOWNLOAD, out, 1100); + if(res != ACCOUNT_SUCCESS) { + log_error("TxSendNew failed : %d", res); + return res; + } + log_info("curl -H 'type: download' -H 'params: %s' 8.136.20.47:8081 -o download.png",out); + log_debug("================================================================================="); + return 0; +} + +int main(){ + + SetPrintLogCallback(print_log_func); + SetGetTimeCallback(print_log_time); + LogSetQuiet(LOG_QUIET_FALSE); + LogSetLevel(LOG_DEBUG); + AccountSetTimeFunc(native_get_time); + + test_sign(); + test_largefile(); + + return 0; +} \ No newline at end of file diff --git a/include/base/ecc.h b/include/base/ecc.h new file mode 100644 index 0000000000000000000000000000000000000000..ad4ffa6497d86d29d1eb27b8544b233073cca728 --- /dev/null +++ b/include/base/ecc.h @@ -0,0 +1,91 @@ +/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ + +#ifndef _MICRO_ECC_H_ +#define _MICRO_ECC_H_ + +#include "log.h" +#include "hash.h" +#include "ql_error_type.h" +#include "ql_type.h" + +// secp256k1 byte length, [DO NOT MODIFY!] +#define uECC_BYTES 32 +// ---------------------------------------------- +// Platform selection options. +// If uECC_PLATFORM is not defined, the code will try to guess it based on compiler macros. +// ---------------------------------------------- +#define uECC_arch_other 0 +#define uECC_x86 1 +#define uECC_x86_64 2 +#define uECC_arm 3 +#define uECC_arm_thumb 4 +#define uECC_avr 5 +#define uECC_arm_thumb2 6 + +// ---------------------------------------------- +// Inline assembly options. +// ---------------------------------------------- +#define uECC_asm_none 0 // Use standard C99 only +#define uECC_asm_small 1 // Use GCC inline assembly for the target platform (if available), optimized for minimum size +#define uECC_asm_fast 2 // Use GCC inline assembly optimized for maximum speed +#ifndef uECC_ASM +#define uECC_ASM uECC_asm_fast +#endif + +// ---------------------------------------------- +// If desired, you can define uECC_WORD_SIZE as appropriate for your platform (4, or 8 bytes). +// If desired, you can define uECC_SUPPORTS_INT128 to indicate whether to use 128-bit variables. +// If uECC_WORD_SIZE and uECC_SUPPORTS_INT128 is not explicitly defined then it will be automatically set based on your platform. +// ---------------------------------------------- +// #define uECC_WORD_SIZE 4 +// #define uECC_SUPPORTS_INT128 0 + +// ---------------------------------------------- +// Error type definition +// ---------------------------------------------- +#define ECC_SUCCESS (ERR_ECC_BASE + 0) // Success +#define ECC_ERR_PUB_EQUAL_ZERO -(ERR_ECC_BASE + 1) // Public key number is 0 +#define ECC_ERR_PRI_EQUAL_ZERO -(ERR_ECC_BASE + 2) // Private key number is 0 +#define ECC_ERR_RNG_UNSUITABLE -(ERR_ECC_BASE + 3) // Inappropriate random number +#define ECC_ERR_RNG_EQUAL_ZERO -(ERR_ECC_BASE + 4) // Random number is 0 +#define ECC_ERR_RNG_NOT_GENERATE -(ERR_ECC_BASE + 5) // Unable to generate random number +#define ECC_ERR_SIG_EQUAL_ZERO -(ERR_ECC_BASE + 6) // The signature contains 0 (r=0 or s=0) +#define ECC_ERR_SIG_BIGGER_N -(ERR_ECC_BASE + 7) // Inappropriate signature (r>n or s>n) +#define ECC_ERR_SHAREKEY_EQUAL_ZERO -(ERR_ECC_BASE + 8) // Shared key number is 0 + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* + The RNG function should fill p_size random bytes into p_dest. The filled-in values should be either truly random, or from a cryptographically-secure PRNG. + A correctly functioning RNG function must be set (using uECC_set_rng()) before calling uECC_make_key() or uECC_shared_secret(). + It should return value >= 0 if p_dest was filled with random data, + or value < 0 if the random data could not be generated. + */ +typedef OhErrType (*uECC_RNG_Function)(OhUint8Type *p_dest, OhInt32Type p_size); + +/* + Set the function that will be used to generate random bytes. + */ +OhVoidType uECC_set_rng(uECC_RNG_Function p_rng); + +/* +Generate an signature for a given hash value. +Inputs: + p_privateKey - Your private key. + p_hash - The message hash to sign. +Outputs: + p_signature - Will be filled in with the signature value. + Returns value >= 0 if the signature generated successfully, value < 0 if an error occurred. +*/ +OhErrType uECC_sign(const OhUint8Type p_privateKey[uECC_BYTES], const OhUint8Type p_hash[uECC_BYTES], OhUint8Type p_signature[uECC_BYTES*2+1]); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/base/hash.h b/include/base/hash.h new file mode 100644 index 0000000000000000000000000000000000000000..d9a74909a9794a7cb97e09e168c8b812d1915dc9 --- /dev/null +++ b/include/base/hash.h @@ -0,0 +1,52 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + + +#ifndef _SECP256K1_HASH_ +#define _SECP256K1_HASH_ + +#include +#include "ql_type.h" + +// ----------------------- +// sha256 definition +// ----------------------- +typedef struct { + OhUint32Type s[32]; + OhUint32Type buf[16]; /* In big endian */ + OhSizeType bytes; +} ql_sha256_t; + +OhVoidType sha256_init (ql_sha256_t* hash); +OhVoidType sha256_write(ql_sha256_t* hash, const OhByteType* data, OhSizeType len); +OhVoidType sha256_final(ql_sha256_t* hash, OhByteType* out32); + +// ----------------------- +// hmac definition +// ----------------------- +typedef struct { + ql_sha256_t inner, outer; +} ql_hmac_t; + +OhVoidType hmac_init (ql_hmac_t* hash, const OhByteType* key , OhSizeType keylen); +OhVoidType hmac_write(ql_hmac_t* hash, const OhByteType* data, OhSizeType size); +OhVoidType hmac_final(ql_hmac_t* hash, OhByteType* out32); + +// ----------------------- +// rfc6979 definition +// ----------------------- +typedef struct { + OhByteType v[32]; + OhByteType k[32]; + OhSizeType retry; +} ql_rfc6979_t; + +OhVoidType rfc6979_init (ql_rfc6979_t* rng, const OhByteType* key, OhSizeType keylen); +OhVoidType rfc6979_gen (ql_rfc6979_t* rng, OhByteType* out, OhSizeType outlen); +OhVoidType rfc6979_final(ql_rfc6979_t* rng); +OhVoidType rfc6979_nonce(OhByteType* nonce32, const OhByteType* msg32, const OhByteType* key32, const OhByteType* algo16, OhVoidType *data, OhSizeType counter); + +#endif diff --git a/include/base/json.h b/include/base/json.h new file mode 100644 index 0000000000000000000000000000000000000000..1861bf1d9a2bd6944fba6a266a8b24478dacd2a0 --- /dev/null +++ b/include/base/json.h @@ -0,0 +1,147 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef _C_JSON_H_ +#define _C_JSON_H_ + +#include +#ifdef __cplusplus +extern "C" +{ +#endif + +/* cJSON Types: */ +#define cJSON_False 0 +#define cJSON_True 1 +#define cJSON_NULL 2 +#define cJSON_Number 3 +#define cJSON_String 4 +#define cJSON_Array 5 +#define cJSON_Object 6 + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON { + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + int type; /* The type of the item, as above. */ + char *valueString; /* The item's string, if type==cJSON_String */ + int valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} cJSON; + +typedef struct cJSON_Hooks { + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +/* Supply malloc, realloc and free functions to cJSON */ +extern void cJSON_InitHooks(cJSON_Hooks* hooks); + + +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */ +extern cJSON *cJSON_Parse(const char *value); +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ +extern char *cJSON_Print(cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */ +extern char *cJSON_PrintUnformatted(cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt); +/* Delete a cJSON entity and all subentities. */ +extern void cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +extern int cJSON_GetArraySize(cJSON *array); +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); +/* Get item "string" from object. Case insensitive. */ +extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); + +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +extern const char *cJSON_GetErrorPtr(void); + +/* These calls create a cJSON item of the appropriate type. */ +extern cJSON *cJSON_CreateNull(void); +extern cJSON *cJSON_CreateTrue(void); +extern cJSON *cJSON_CreateFalse(void); +extern cJSON *cJSON_CreateBool(int b); +extern cJSON *cJSON_CreateNumber(double num); +extern cJSON *cJSON_CreateString(const char *string); +extern cJSON *cJSON_CreateArray(void); +extern cJSON *cJSON_CreateObject(void); + +/* These utilities create an Array of count items. */ +extern cJSON *cJSON_CreateIntArray(const int *numbers,int count); +extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count); +extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count); +extern cJSON *cJSON_CreateStringArray(const char **strings,int count); + +/* Append item to the specified array/object. */ +extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); +extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */ +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); + +/* Remove/Detatch items from Arrays/Objects. */ +extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which); +extern void cJSON_DeleteItemFromArray(cJSON *array,int which); +extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string); +extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string); + +/* Update array items. */ +extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */ +extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); +extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +extern cJSON *cJSON_Duplicate(cJSON *item,int recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will +need to be released. With recurse!=0, it will duplicate any children connected to the item. +The item->next and ->prev pointers are always zero on return from Duplicate. */ + +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated); + +extern void cJSON_Minify(char *json); + +/* Macros for creating things quickly. */ +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) +#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/base/keccak256.h b/include/base/keccak256.h new file mode 100644 index 0000000000000000000000000000000000000000..23d5b165c17d0a20cc920535f2b0332f314e836d --- /dev/null +++ b/include/base/keccak256.h @@ -0,0 +1,46 @@ +/* sha3 - an implementation of Secure Hash Algorithm 3 (Keccak). + * based on the + * The Keccak SHA-3 submission. Submission to NIST (Round 3), 2011 + * by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche + * + * Copyright: 2013 Aleksey Kravchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk! + */ + +#ifndef __KECCAK256_H_ +#define __KECCAK256_H_ + +#include +#include "ql_type.h" +#include "log.h" + +// Maximum parameters defined by SHA3, [DO NOT MODIFY!] +#define SHA3_MAX_PERMUTATION_SIZE 25 +#define SHA3_MAX_RATE_IN_QWORDS 24 + +/* +Method used to calculate keccak256. +inputs: + msg - Data used to calculate. + size - Data length. +output: + hashbuf - Calculation results. + */ +OhVoidType keccak256(const OhByteType *msg, OhUint32Type size, OhByteType **hashbuf); + +/* +Print the result of keccak. convert the hex data to string data. + */ +OhVoidType print_keccak_data(OhByteType *out); + +#endif diff --git a/include/base/log.h b/include/base/log.h new file mode 100644 index 0000000000000000000000000000000000000000..f8905c909152492dbec897623bc7cea6b4845fac --- /dev/null +++ b/include/base/log.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2016-2021, Hangzhou Qulian Technology Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LOG_H_ +#define _LOG_H_ + +#include +#include +#include +#include +#include "ql_type.h" + +// Maximum length of log content +#define LOG_MAX_SIZE 1024 + +// Enumerate log types +typedef enum { + LOG_DEBUG, + LOG_INFO, + LOG_WARN, + LOG_ERROR +} OhLongLevel; + +// Define log silent state +#define LOG_QUIET_TRUE 1 +#define LOG_QUIET_FALSE 0 + +// Callback function of and