新注册的用户请输入邮箱并保存,随后登录邮箱激活账号。后续可直接使用邮箱登录!

Commit a7d036bc authored by helangchen's avatar helangchen

初始化提交

parents
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "base64"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff"
[[package]]
name = "catalog_contract"
version = "2.1.0"
dependencies = [
"base64",
"chrono",
"serde",
"serde-json-wasm",
"serde_derive",
]
[[package]]
name = "chrono"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73"
dependencies = [
"libc",
"num-integer",
"num-traits",
"time",
"winapi",
]
[[package]]
name = "libc"
version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765"
[[package]]
name = "num-integer"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde-json-wasm"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "042ac496d97e5885149d34139bad1d617192770d7eb8f1866da2317ff4501853"
dependencies = [
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "time"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [
"libc",
"wasi",
"winapi",
]
[[package]]
name = "unicode-ident"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c"
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[package]
#name = "privacy_computing"
name = "catalog_contract"
#name = "mock"
version = "2.1.0"
authors = ["chainmaker"]
edition = "2018"
[dependencies]
base64 = "0.12.1"
chrono = "0.4.19"
serde-json-wasm = "0.3.2"
serde_derive = "*"
serde = { version = "1.0", features = ["derive"] }
[lib]
crate-type = ["cdylib"]
[profile.release]
lto = true
opt-level = 'z'
panic = 'abort'
[package.metadata.wasm-pack.profile.release]
wasm-opt = ['-Oz']
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.
\ No newline at end of file
build:
- cargo build --release --target=wasm32-unknown-unknown
\ No newline at end of file
长安链·ChainMaker
Copyright 2021 contributors to 长安链·ChainMaker
\ No newline at end of file
# Quick Start
- [长安链 · Rust SDK Build Docs](https://docs.chainmaker.org.cn/dev/%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.html#rust "长安链 · ChainMaker Docs")
# License
长安链·ChainMaker is made available under the Apache License, Version 2.0 (Apache-2.0), located in the [LICENSE](./LICENSE) file.
# Declaration
## 环境依赖
使用rust的sdk编译合约依赖rust编译器和cargo
## 安装rust cargo
> 官方地址: https://www.rust-lang.org/tools/install
**windows**
> To install Rust on Windows, download and run [rustup-init.exe](https://win.rustup.rs/), then follow the onscreen instructions.
>
> https://win.rustup.rs/
**Linux、Mac**
> curl https://sh.rustup.rs -sSf | sh
## 编译
```sh
make build
```
生成路径:target/wasm32-unknown-unknown/release/chainmaker_contract.wasm
This diff is collapsed.
use serde_json_wasm;
use crate::sim_context;
use sim_context::*;
use std::collections::HashMap;
use crate::easycodec::*;
// 安装合约时会执行此方法,必须
#[no_mangle]
pub extern "C" fn init_contract() {}
// 升级合约时会执行此方法,必须
#[no_mangle]
pub extern "C" fn upgrade() {}
const METADATE: &str = "METADATE_";
const DIGITAL_IDENTITY: &str = "DIGITAL_IDENTITY_";
const CALCULATION_MODEL: &str = "CALCULATION_MODEL_";
const INFRASTRUCTURE: &str = "INFRASTRUCTURE_";
const CATALOG: &str = "CATALOG_";
#[derive(Serialize, Deserialize)]
pub struct Detail
{
#[serde(rename = "companyDID")]
company_did: String,
name: String,
#[serde(rename = "ID")]
id: String,
}
#[derive(Serialize, Deserialize)]
pub struct Metadate
{
detail: String,
version: String,
#[serde(rename = "sourceServer")]
source_server: String,
#[serde(rename = "ownerDID")]
owner_did: String,
#[serde(rename = "ownerName")]
owner_name: String,
description: String,
#[serde(rename = "ID")]
id: String,
}
#[no_mangle]
pub extern "C" fn putMetadate() {
let ctx = &mut sim_context::get_sim_context();
let metadate = ctx.arg_as_utf8_str("metadate");
if metadate.len() == 0 {
ctx.log("putMetadate: metadate cannot be null");
ctx.error("putMetadate: metadate cannot be null");
return;
}
let r = serde_json_wasm::from_str(metadate.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm by metadate fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let metadate_get: Metadate = r.unwrap();
ctx.put_state_from_key(
(METADATE.to_owned() + metadate_get.id.as_str()).as_str(),
metadate.as_bytes(),
);
ctx.ok("success".as_bytes());
return;
}
#[no_mangle]
pub extern "C" fn getMetadate() {
let ctx = &mut sim_context::get_sim_context();
let metadate_id = ctx.arg_as_utf8_str("ID");
if metadate_id.len() == 0 {
ctx.log("getMetadate: ID cannot be null");
ctx.error("getMetadate: ID cannot be null");
return;
}
let r = ctx.get_state_from_key(
(METADATE.to_owned() + metadate_id.as_str()).as_str(),
);
if r.is_err() {
ctx.log("get_state by metadate_id fail");
ctx.error("get_state by metadate_id fail");
return;
}
let r = r.unwrap();
if r.len() == 0 {
ctx.log("ID not exists");
ctx.error("ID not exists");
return;
}
let s = String::from_utf8(r);
if s.is_err() {
ctx.log("Found invalid UTF-8");
ctx.error("Found invalid UTF-8");
return;
}
let s = s.unwrap();
let r = serde_json_wasm::from_str(s.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = format!("serde_json_wasm by metadate fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let metadate: Metadate = r.unwrap();
let r = serde_json_wasm::to_string(&metadate);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm resp to_string fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
// 返回查询结果
ctx.ok(resp_json.as_bytes());
}
#[derive(Serialize, Deserialize)]
pub struct DigitalIdentity
{
#[serde(rename = "detailParser")]
detail_parser: String,
version: String,
#[serde(rename = "isValid")]
is_valid: String,
expt: String,
#[serde(rename = "createTime")]
create_time: String,
vct: String,
m: String,
owner: String,
name: String,
#[serde(rename = "DID")]
did: String,
}
#[no_mangle]
pub extern "C" fn putDigitalIdentity() {
let ctx = &mut sim_context::get_sim_context();
let digital_identity = ctx.arg_as_utf8_str("digitalIdentity");
if digital_identity.len() == 0 {
ctx.log("putDigitalIdentity: digital_identity cannot be null");
ctx.error("putDigitalIdentity: digital_identity cannot be null");
return;
}
let r = serde_json_wasm::from_str(digital_identity.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm by digital_identity fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let digital_identity_get: DigitalIdentity = r.unwrap();
ctx.put_state_from_key(
(DIGITAL_IDENTITY.to_owned() + digital_identity_get.did.as_str()).as_str(),
digital_identity.as_bytes(),
);
ctx.ok("success".as_bytes());
return;
}
#[no_mangle]
pub extern "C" fn getDigitalIdentity() {
let ctx = &mut sim_context::get_sim_context();
let digital_identity_id = ctx.arg_as_utf8_str("ID");
if digital_identity_id.len() == 0 {
ctx.log("getDigitalIdentity: ID cannot be null");
ctx.error("getDigitalIdentity: ID cannot be null");
return;
}
let r = ctx.get_state_from_key(
(DIGITAL_IDENTITY.to_owned() + digital_identity_id.as_str()).as_str(),
);
if r.is_err() {
ctx.log("get_state by digital_identity_id fail");
ctx.error("get_state by digital_identity_id fail");
return;
}
let r = r.unwrap();
if r.len() == 0 {
ctx.log("ID not exists");
ctx.error("ID not exists");
return;
}
let s = String::from_utf8(r);
if s.is_err() {
ctx.log("Found invalid UTF-8");
ctx.error("Found invalid UTF-8");
return;
}
let s = s.unwrap();
let r = serde_json_wasm::from_str(s.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = format!("serde_json_wasm by digital_identity fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let digital_identity: DigitalIdentity = r.unwrap();
let r = serde_json_wasm::to_string(&digital_identity);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm resp to_string fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
// 返回查询结果
ctx.ok(resp_json.as_bytes());
}
#[derive(Serialize, Deserialize)]
pub struct CalculationModel
{
#[serde(rename = "ID")]
id: String,
name: String,
protocol: String,
version: String,
}
#[no_mangle]
pub extern "C" fn putCalculationModel() {
let ctx = &mut sim_context::get_sim_context();
let calculation_model = ctx.arg_as_utf8_str("calculationModel");
if calculation_model.len() == 0 {
ctx.log("putCalculationModel: calculation_model cannot be null");
ctx.error("putCalculationModel: calculation_model cannot be null");
return;
}
let r = serde_json_wasm::from_str(calculation_model.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm by calculation_model fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let calculation_model_get: CalculationModel = r.unwrap();
ctx.put_state_from_key(
(CALCULATION_MODEL.to_owned() + calculation_model_get.id.as_str()).as_str(),
calculation_model.as_bytes(),
);
ctx.ok("success".as_bytes());
return;
}
#[no_mangle]
pub extern "C" fn getCalculationModel() {
let ctx = &mut sim_context::get_sim_context();
let calculation_model_id = ctx.arg_as_utf8_str("ID");
if calculation_model_id.len() == 0 {
ctx.log("getCalculationModel: ID cannot be null");
ctx.error("getCalculationModel: ID cannot be null");
return;
}
let r = ctx.get_state_from_key(
(CALCULATION_MODEL.to_owned() + calculation_model_id.as_str()).as_str(),
);
if r.is_err() {
ctx.log("get_state by calculation_model_id fail");
ctx.error("get_state by calculation_model_id fail");
return;
}
let r = r.unwrap();
if r.len() == 0 {
ctx.log("ID not exists");
ctx.error("ID not exists");
return;
}
let s = String::from_utf8(r);
if s.is_err() {
ctx.log("Found invalid UTF-8");
ctx.error("Found invalid UTF-8");
return;
}
let s = s.unwrap();
let r = serde_json_wasm::from_str(s.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = format!("serde_json_wasm by calculation_model fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let calculation_model: CalculationModel = r.unwrap();
let r = serde_json_wasm::to_string(&calculation_model);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm resp to_string fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
// 返回查询结果
ctx.ok(resp_json.as_bytes());
}
#[derive(Serialize, Deserialize)]
pub struct Infrastructure
{
#[serde(rename = "ID")]
id: String,
#[serde(rename = "teeResource")]
tee_resource: String,
#[serde(rename = "networkResource")]
network_resource: String,
#[serde(rename = "storageResource")]
storage_resource: String,
#[serde(rename = "computingResource")]
computing_resource: String,
version: String,
}
#[no_mangle]
pub extern "C" fn putInfrastructure() {
let ctx = &mut sim_context::get_sim_context();
let infrastructure = ctx.arg_as_utf8_str("infrastructure");
if infrastructure.len() == 0 {
ctx.log("putInfrastructure: infrastructure cannot be null");
ctx.error("putInfrastructure: infrastructure cannot be null");
return;
}
let r = serde_json_wasm::from_str(infrastructure.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm by infrastructure fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let infrastructure_get: Infrastructure = r.unwrap();
//todo
ctx.put_state_from_key(
(INFRASTRUCTURE.to_owned() + infrastructure_get.computing_resource.as_str()).as_str(),
infrastructure.as_bytes(),
);
ctx.ok("success".as_bytes());
return;
}
#[no_mangle]
pub extern "C" fn getInfrastructure() {
let ctx = &mut sim_context::get_sim_context();
let infrastructure_id = ctx.arg_as_utf8_str("ID");
if infrastructure_id.len() == 0 {
ctx.log("getInfrastructure: ID cannot be null");
ctx.error("getInfrastructure: ID cannot be null");
return;
}
let r = ctx.get_state_from_key(
(INFRASTRUCTURE.to_owned() + infrastructure_id.as_str()).as_str(),
);
if r.is_err() {
ctx.log("get_state by infrastructure_id fail");
ctx.error("get_state by infrastructure_id fail");
return;
}
let r = r.unwrap();
if r.len() == 0 {
ctx.log("ID not exists");
ctx.error("ID not exists");
return;
}
let s = String::from_utf8(r);
if s.is_err() {
ctx.log("Found invalid UTF-8");
ctx.error("Found invalid UTF-8");
return;
}
let s = s.unwrap();
let r = serde_json_wasm::from_str(s.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = format!("serde_json_wasm by infrastructure fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let infrastructure: Infrastructure = r.unwrap();
let r = serde_json_wasm::to_string(&infrastructure);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm resp to_string fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
// 返回查询结果
ctx.ok(resp_json.as_bytes());
}
#[derive(Serialize, Deserialize)]
pub struct SubCatalog
{
infrastructure: Infrastructure,
#[serde(rename = "calculationModel")]
calculation_model: CalculationModel,
#[serde(rename = "digitalIdentity")]
digital_identity: DigitalIdentity,
metadate: Metadate,
}
#[derive(Serialize, Deserialize)]
pub struct Catalog
{
remark: String,
version: String,
#[serde(rename = "publishTime")]
publish_time: String,
#[serde(rename = "statusDesc")]
status_desc: String,
#[serde(rename = "updateOrgID")]
update_org_id: String,
#[serde(rename = "catalogName")]
catalog_name: String,
#[serde(rename = "catalogType")]
catalog_type: String,
}
#[no_mangle]
pub extern "C" fn putCatalog() {
let ctx = &mut sim_context::get_sim_context();
let catalog = ctx.arg_as_utf8_str("catalog");
if catalog.len() == 0 {
ctx.log("putCatalog: catalog cannot be null");
ctx.error("putCatalog: catalog cannot be null");
return;
}
let r = serde_json_wasm::from_str(catalog.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm by catalog fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let catalog_get: Catalog = r.unwrap();
ctx.put_state_from_key(
(CATALOG.to_owned() + catalog_get.catalog_type.as_str()).as_str(),
catalog.as_bytes(),
);
ctx.ok("success".as_bytes());
return;
}
#[no_mangle]
pub extern "C" fn getCatalog() {
let ctx = &mut sim_context::get_sim_context();
let catalog_type = ctx.arg_as_utf8_str("catalogType");
if catalog_type.len() == 0 {
ctx.log("getCatalog: catalogType cannot be null");
ctx.error("getCatalog: catalogType cannot be null");
return;
}
let r = ctx.get_state_from_key(
(CATALOG.to_owned() + catalog_type.as_str()).as_str(),
);
if r.is_err() {
ctx.log("get_state by catalog_id fail");
ctx.error("get_state by catalog_id fail");
return;
}
let r = r.unwrap();
if r.len() == 0 {
ctx.log("catalogType not exists");
ctx.error("catalogType not exists");
return;
}
let s = String::from_utf8(r);
if s.is_err() {
ctx.log("Found invalid UTF-8");
ctx.error("Found invalid UTF-8");
return;
}
let s = s.unwrap();
let r = serde_json_wasm::from_str(s.as_str());
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = format!("serde_json_wasm by catalog fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let catalog: Catalog = r.unwrap();
let r = serde_json_wasm::to_string(&catalog);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm resp to_string fail,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
// 返回查询结果
ctx.ok(resp_json.as_bytes());
}
\ No newline at end of file
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
use crate::easycodec::*;
use crate::sim_context;
use sim_context::*;
// 安装合约时会执行此方法,必须
#[no_mangle]
pub extern "C" fn init_contract() {
// 安装时的业务逻辑,内容可为空
sim_context::log("init_contract");
}
// 升级合约时会执行此方法,必须
#[no_mangle]
pub extern "C" fn upgrade() {
// 升级时的业务逻辑,内容可为空
sim_context::log("upgrade");
let ctx = &mut sim_context::get_sim_context();
ctx.ok("upgrade success".as_bytes());
}
struct Fact {
file_hash: String,
file_name: String,
time: i32,
ec: EasyCodec,
}
impl Fact {
fn new_fact(file_hash: String, file_name: String, time: i32) -> Fact {
let mut ec = EasyCodec::new();
ec.add_string("file_hash", file_hash.as_str());
ec.add_string("file_name", file_name.as_str());
ec.add_i32("time", time);
Fact {
file_hash,
file_name,
time,
ec,
}
}
fn get_emit_event_data(&self) -> Vec<String> {
let mut arr: Vec<String> = Vec::new();
arr.push(self.file_hash.clone());
arr.push(self.file_name.clone());
arr.push(self.time.to_string());
arr
}
fn to_json(&self) -> String {
self.ec.to_json()
}
fn marshal(&self) -> Vec<u8> {
self.ec.marshal()
}
fn unmarshal(data: &Vec<u8>) -> Fact {
let ec = EasyCodec::new_with_bytes(data);
Fact {
file_hash: ec.get_string("file_hash").unwrap(),
file_name: ec.get_string("file_name").unwrap(),
time: ec.get_i32("time").unwrap(),
ec,
}
}
}
// save 保存存证数据
#[no_mangle]
pub extern "C" fn save() {
// 获取上下文
let ctx = &mut sim_context::get_sim_context();
// 获取传入参数
let file_hash = ctx.arg_as_utf8_str("file_hash");
let file_name = ctx.arg_as_utf8_str("file_name");
let time_str = ctx.arg_as_utf8_str("time");
// 构造结构体 todo
let r_i32 = time_str.parse::<i32>();
if r_i32.is_err() {
let msg = format!("time is {:?} not int32 number.", time_str);
ctx.log(&msg);
ctx.error(&msg);
return;
}
let time: i32 = r_i32.unwrap();
let fact = Fact::new_fact(file_hash, file_name, time);
// 事件
ctx.emit_event("topic_vx", &fact.get_emit_event_data());
// 序列化后存储
ctx.put_state(
"fact_ec",
fact.file_hash.as_str(),
fact.marshal().as_slice(),
);
}
// find_by_file_hash 根据file_hash查询存证数据
#[no_mangle]
pub extern "C" fn find_by_file_hash() {
// 获取上下文
let ctx = &mut sim_context::get_sim_context();
// 获取传入参数
let file_hash = ctx.arg_as_utf8_str("file_hash");
// 校验参数
if file_hash.len() == 0 {
ctx.log("file_hash is null");
ctx.ok("".as_bytes());
return;
}
// 查询
let r = ctx.get_state("fact_ec", &file_hash);
// 校验返回结果
if r.is_err() {
ctx.log("get_state fail");
ctx.error("get_state fail");
return;
}
let fact_vec = r.unwrap();
if fact_vec.len() == 0 {
ctx.log("None");
ctx.ok("".as_bytes());
return;
}
// 查询
let r = ctx.get_state("fact_ec", &file_hash).unwrap();
let fact = Fact::unmarshal(&r);
let json_str = fact.to_json();
// 返回查询结果
ctx.ok(json_str.as_bytes());
ctx.log(&json_str);
}
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
use base64::encode;
use std::{io::BufWriter, io::Write, str, usize};
pub type EasyKeyType = i32;
pub type EasyValueType = i32;
pub const EASY_KEY_TYPE_SYSTEM: EasyKeyType = 0;
pub const EASY_KEY_TYPE_USER: EasyKeyType = 1;
pub const EASY_VALUE_TYPE_INT32: EasyValueType = 0;
pub const EASY_VALUE_TYPE_STRING: EasyValueType = 1;
pub const EASY_VALUE_TYPE_BYTES: EasyValueType = 2;
const EC_MAGIC_NUM: [u8; 4] = [99, 109, 101, 99]; // "cmec"
const EC_VERSION: [u8; 4] = [118, 49, 46, 48]; // "v1.0"
const EC_RESERVED: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255];
const PARAMETERS_KEY_MAX_COUNT: i32 = 128;
// const MAX_KEY_COUNT: usize = 128;
// const MAX_KEY_LEN: usize = 64;
// const MAX_VALUE_LEN: usize = 1024 * 1024;
const EC_MAGIC_NUM_LEN: usize = 4;
const EC_VERSION_LEN: usize = 4;
const EC_RESERVED_LEN: usize = 8;
const MIN_LEN: usize = 20;
/// serialize [kv_count, key_type, key_len, key, value_type, val_length, val]
/// EasyCodec serialize data
pub struct EasyCodec {
items: Vec<EasyCodecItem>,
}
#[allow(dead_code)]
impl EasyCodec {
///
/// # Example:
/// ```
/// fn main1(){
/// let mut ec = EasyCodec::new();
/// ec.add_i32("key1", 123);
/// ec.add_string("keyStr", "chainmaker长安链");
/// ec.add_bytes("bytes", "2".as_bytes().to_vec());
/// let bytes:Vec<u8> = ec.marshal();
/// let j: String = ec.to_json();
/// let ec = EasyCodec::unmarshal(&bytes);
/// }
///
/// fn main2() {
/// let a: i32 = 123;
/// let item1 = EasyCodecItem {
/// key_type: EASY_KEY_TYPE_USER,
/// key: "key1".to_string(),
/// value_type: EASY_VALUE_TYPE_INT32,
/// value: a.to_le_bytes().to_vec(),
/// };
///
/// let item2 = EasyCodecItem {
/// key_type: EASY_KEY_TYPE_USER,
/// key: "keyStr".to_string(),
/// value_type: EASY_VALUE_TYPE_STRING,
/// value: "chainmaker长安链",
/// };
///
/// let bytes = "chainmaker长安链".as_bytes().to_vec();
/// let item3 = EasyCodecItem {
/// key_type: EASY_KEY_TYPE_USER,
/// key: "bytes".to_string(),
/// value_type: EASY_VALUE_TYPE_BYTES,
/// value: bytes.as_bytes().to_vec(),
/// };
/// let items = vec![item1, item2, item3];
/// let ec = EasyCodec::new_with(items);
/// }
/// ```
pub fn new() -> EasyCodec {
EasyCodec { items: Vec::new() }
}
/// new with items, example see new() method
pub fn new_with(data: Vec<EasyCodecItem>) -> EasyCodec {
EasyCodec { items: data }
}
/// new_with_bytes unmarshal data
pub fn new_with_bytes(data: &Vec<u8>) -> EasyCodec {
EasyCodec::unmarshal(data)
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn get_items(&self) -> &Vec<EasyCodecItem> {
&self.items
}
pub fn put_item(&mut self, item: EasyCodecItem) {
self.items.push(item);
}
pub fn add_i32(&mut self, key: &str, val: i32) {
let v = val.to_le_bytes().to_vec();
self.add_val(EASY_KEY_TYPE_USER, key, EASY_VALUE_TYPE_INT32, v);
}
pub fn add_string(&mut self, key: &str, val: &str) {
let v = val.as_bytes().to_vec();
self.add_val(EASY_KEY_TYPE_USER, key, EASY_VALUE_TYPE_STRING, v);
}
pub fn add_bytes(&mut self, key: &str, val: Vec<u8>) {
self.add_val(EASY_KEY_TYPE_USER, key, EASY_VALUE_TYPE_BYTES, val);
}
pub fn add_val(
&mut self,
key_type: EasyKeyType,
key: &str,
value_type: EasyValueType,
value: Vec<u8>,
) {
let item = EasyCodecItem {
key_type,
key: key.to_string(),
value_type,
value,
};
self.items.push(item);
}
pub fn get_i32(&self, key: &str) -> Result<i32, String> {
let key = key.to_string();
for i in self.items.iter() {
if i.key == key {
return i.get_int();
}
}
Err("not found".to_string())
}
pub fn get_string(&self, key: &str) -> Result<String, String> {
let key = key.to_string();
for i in self.items.iter() {
if i.key == key {
return i.get_string();
}
}
Err("not found".to_string())
}
pub fn get_bytes(&self, key: &str) -> Result<Vec<u8>, String> {
let key = key.to_string();
for i in self.items.iter() {
if i.key == key {
return i.get_bytes();
}
}
Err("not found".to_string())
}
pub fn get_bytes_as_utf8_string(&self, key: &str) -> Result<String, String> {
let key = key.to_string();
for i in self.items.iter() {
if i.key == key {
let val = i.get_bytes();
if val.is_err() {
return Err("value type is not bytes".to_string());
}
let val_str = String::from_utf8(val.unwrap());
if val_str.is_err() {
return Err("not found utf-8 bytes".to_string());
}
return Ok(val_str.unwrap());
}
}
Err("not found".to_string())
}
/// remove key
pub fn remove(&mut self, key: &str) {
let key = key.to_string();
let mut index = 0 as usize;
for i in self.items.iter() {
if key == i.key {
self.items.remove(index);
break;
}
index += 1;
}
}
/// magic number + 预留8字节
/// kv count + [ key type + key len + key + value type + value len + value ]
/// marshal to bytes, example see new() method
pub fn marshal(&self) -> Vec<u8> {
let buf = Vec::new();
let mut stream = BufWriter::new(buf);
// header
let _ = stream.write(&EC_MAGIC_NUM);
let _ = stream.write(&EC_VERSION);
let _ = stream.write(&EC_RESERVED);
// kv count
let size = self.items.len() as i32;
let size_vec = size.to_le_bytes().to_vec();
let size_byte = size_vec.as_slice();
let _ = stream.write(size_byte);
for i in self.items.iter() {
// key type
let key_type_size_vec = i.key_type.to_le_bytes().to_vec();
let key_type_size_byte = key_type_size_vec.as_slice();
let _ = stream.write(key_type_size_byte).unwrap();
// key len
let key_val_size_vec = (i.key.len() as i32).to_le_bytes().to_vec();
let key_val_size_byte = key_val_size_vec.as_slice();
let _ = stream.write(key_val_size_byte).unwrap();
// key
let _ = stream.write(i.key.as_bytes()).unwrap();
// val type
let value_type_size_vec = i.value_type.to_le_bytes().to_vec();
let value_type_size_byte = value_type_size_vec.as_slice();
let _ = stream.write(value_type_size_byte).unwrap();
// val len
let val_size_vec = (i.value.len() as i32).to_le_bytes().to_vec();
let val_size_byte = val_size_vec.as_slice();
let _ = stream.write(val_size_byte).unwrap();
// val
let _ = stream.write(i.value.as_slice()).unwrap();
}
stream.flush().unwrap();
let r = stream.into_inner().unwrap();
r
}
/// unmarshal bytes to EasyCodec, example see new() method
pub fn unmarshal(data: &Vec<u8>) -> EasyCodec {
if data.len() <= MIN_LEN {
return EasyCodec::new();
}
let mut items: Vec<EasyCodecItem> = Vec::new();
let slice = data.as_slice();
let i32_len = 4;
let mut index: usize = 0;
// header
let magic_num = parse_le_i32(&slice, index);
let ec_magic_num = parse_le_i32(&EC_MAGIC_NUM, 0);
if magic_num == ec_magic_num {
index += EC_MAGIC_NUM_LEN;
let version = parse_le_i32(&slice, index);
index += EC_VERSION_LEN;
let reserved1 = parse_le_i32(&slice, index);
let reserved2 = parse_le_i32(&slice, index + 4);
index += EC_RESERVED_LEN;
let ec_magic_num = parse_le_i32(&EC_MAGIC_NUM, 0);
let ec_version = parse_le_i32(&EC_VERSION, 0);
let ec_reserved1 = parse_le_i32(&EC_RESERVED, 0);
let ec_reserved2 = parse_le_i32(&EC_RESERVED, 4);
if !(magic_num == ec_magic_num
&& version == ec_version
&& reserved1 == ec_reserved1
&& reserved2 == ec_reserved2)
{
return EasyCodec::new();
}
}
// kv count
let kv_count = parse_le_i32(slice, index);
if kv_count > PARAMETERS_KEY_MAX_COUNT {
return EasyCodec::new();
}
index += i32_len;
for _ in 0..kv_count {
// read key type
let key_type = parse_le_i32(slice, index);
index += i32_len;
if key_type != EASY_KEY_TYPE_SYSTEM && key_type != EASY_KEY_TYPE_USER {
continue;
}
// read key len
let key_len = parse_le_i32(slice, index) as usize;
index += i32_len;
// read key
let key = String::from_utf8(slice[index..(index + key_len)].to_vec()).unwrap();
index += key_len;
// read val type
let value_type = parse_le_i32(slice, index);
index += i32_len;
// read val len
let val_len = parse_le_i32(slice, index) as usize;
index += i32_len;
let value = slice[index..(index + val_len)].to_vec();
index += val_len;
let item = EasyCodecItem {
key_type,
key,
value_type,
value,
};
items.push(item);
}
EasyCodec::new_with(items)
}
/// to simple json, bytes is null
pub fn to_json(&self) -> String {
let mut str_json = "{".to_string();
for i in self.items.iter() {
str_json.push_str("\"");
str_json.push_str(i.key.as_str());
str_json.push_str("\":");
if i.value_type == EASY_VALUE_TYPE_STRING {
let val = String::from_utf8(i.value.clone()).unwrap();
let result = val.replace("\"", "\\\"");
str_json.push_str("\"");
str_json.push_str(result.as_str());
str_json.push_str("\"");
} else if i.value_type == EASY_VALUE_TYPE_INT32 {
let val = parse_le_i32(i.value.as_slice(), 0);
str_json.push_str(val.to_string().as_str());
} else if i.value_type == EASY_VALUE_TYPE_BYTES {
let val = encode(i.value.as_slice());
str_json.push_str("\"");
str_json.push_str(&val);
str_json.push_str("\"");
}
str_json.push_str(",");
}
if str_json.len() > 1 {
str_json.remove(str_json.len() - 1);
}
str_json.push_str("}");
str_json
}
}
pub struct EasyCodecItem {
pub key_type: EasyKeyType,
pub key: String,
pub value_type: EasyValueType,
pub value: Vec<u8>,
}
impl EasyCodecItem {
pub fn get_int(&self) -> Result<i32, String> {
if self.value_type == EASY_VALUE_TYPE_INT32 {
return Ok(i32::from_le_bytes([
self.value[0],
self.value[1],
self.value[2],
self.value[3],
]));
}
Err("value type not i32".to_string())
}
pub fn get_string(&self) -> Result<String, String> {
if self.value_type == EASY_VALUE_TYPE_STRING {
return Ok(std::str::from_utf8(&self.value).unwrap().to_string());
}
Err("value type not string".to_string())
}
pub fn get_bytes(&self) -> Result<Vec<u8>, String> {
if self.value_type == EASY_VALUE_TYPE_BYTES {
return Ok(self.value.clone());
}
Err("value type not bytes".to_string())
}
}
fn parse_le_i32(slice: &[u8], index: usize) -> i32 {
i32::from_le_bytes([
slice[index + 0],
slice[index + 1],
slice[index + 2],
slice[index + 3],
])
}
/// cargo test --package chainmaker-contract
#[cfg(test)]
mod tests {
use crate::easycodec::*;
#[test]
fn base_test() {
let val: i32 = 12345678;
let b = val.to_le_bytes();
let v = b.to_vec();
let slice = v.as_slice();
println!("slice {:?}", slice);
let kv_count = parse_le_i32(slice, 0);
let index = 4;
let slice = &slice[index..slice.len()];
println!("slice {:?}", slice);
println!("kv_count {:?}", kv_count);
let iiii = parse_le_i32("1cmec2312".as_bytes(), 1);
println!("iiii {:?}", iiii);
}
/// how to test, execute the following command
/// cargo test -- --nocapture easy_codec_test
#[test]
fn easy_codec_test() {
let a: i32 = 123;
let item1 = EasyCodecItem {
key_type: EASY_KEY_TYPE_USER,
key: "key1".to_string(),
value_type: EASY_VALUE_TYPE_INT32,
value: a.to_le_bytes().to_vec(),
};
let bytes = "chainmaker长安链".as_bytes().to_vec();
let item2 = EasyCodecItem {
key_type: EASY_KEY_TYPE_USER,
key: "keyStr".to_string(),
value_type: EASY_VALUE_TYPE_STRING,
value: bytes,
};
let item3 = EasyCodecItem {
key_type: EASY_KEY_TYPE_USER,
key: "bytes".to_string(),
value_type: EASY_VALUE_TYPE_BYTES,
value: "222222222222".as_bytes().to_vec(),
};
println!("===================marshal start==================");
let items = vec![item1, item2, item3];
let ec = EasyCodec::new_with(items);
let bytes = ec.marshal();
println!("bytes {:?}", bytes);
let j = ec.to_json();
println!("to_json {:?}", j);
println!("===================marshal end==================");
println!("===================unmarshal start==================");
let ec_new = EasyCodec::unmarshal(&bytes);
let j = ec_new.to_json();
println!("to_json {:?}", j);
let bytes = ec_new.marshal();
println!("bytes {:?}", bytes);
println!("===================unmarshal end==================");
println!("===================other use start==================");
let mut ec = EasyCodec::new();
ec.add_i32("key1", 123);
ec.add_string("keyStr", "chainmaker长安链");
ec.add_bytes("bytes", "2".as_bytes().to_vec());
let bytes = ec.marshal();
println!("bytes {:?}", bytes);
let mut ec = EasyCodec::unmarshal(&bytes);
let bytes = ec.get_bytes("bytes").unwrap();
let key1 = ec.get_i32("key1").unwrap();
let key_str = ec.get_string("keyStr").unwrap();
println!("bytes {:?}", bytes);
println!("key1 {:?}", key1);
println!("key_str {:?}", key_str);
println!("before 【remove】 len {:?}", ec.len());
println!("remove key keyStr");
ec.remove("keyStr");
let key_str = ec.get_string("keyStr");
println!("key_str {:?}", key_str);
println!("after 【remove】 len {:?}", ec.len());
println!("===================other use end==================");
tojson_test();
}
fn tojson_test() {
println!("========json test start=========");
let mut ec = EasyCodec::new();
ec.add_i32("key1", 123);
ec.add_string("keyStr", "chainmaker长安链{\"name\":\"abcd\"}");
ec.add_bytes("bytes", "2".as_bytes().to_vec());
let j = ec.to_json();
println!("json: \n{:?}", j);
println!("========json test end==========");
}
/// how to test, execute the following command
/// cargo test -- --nocapture easy_codec_field_test
#[test]
fn easy_codec_field_test() {
let origin1: [u8; 174] = [
99, 109, 101, 99, 118, 49, 46, 48, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, 0,
1, 0, 0, 0, 8, 0, 0, 0, 107, 101, 121, 66, 121, 116, 101, 115, 2, 0, 0, 0, 40, 0, 0, 0,
99, 104, 97, 105, 110, 109, 97, 107, 101, 114, 233, 149, 191, 229, 174, 137, 233, 147,
190, 33, 64, 35, 36, 37, 94, 38, 42, 40, 41, 95, 43, 45, 61, 123, 125, 124, 58, 63, 62,
60, 1, 0, 0, 0, 8, 0, 0, 0, 107, 101, 121, 73, 110, 116, 51, 50, 0, 0, 0, 0, 4, 0, 0,
0, 21, 205, 91, 7, 1, 0, 0, 0, 6, 0, 0, 0, 107, 101, 121, 83, 116, 114, 1, 0, 0, 0, 40,
0, 0, 0, 99, 104, 97, 105, 110, 109, 97, 107, 101, 114, 233, 149, 191, 229, 174, 137,
233, 147, 190, 33, 64, 35, 36, 37, 94, 38, 42, 40, 41, 95, 43, 45, 61, 123, 125, 124,
58, 63, 62, 60,
];
let origin2: [u8; 158] = [
3, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 107, 101, 121, 66, 121, 116, 101, 115, 2, 0, 0, 0,
40, 0, 0, 0, 99, 104, 97, 105, 110, 109, 97, 107, 101, 114, 233, 149, 191, 229, 174,
137, 233, 147, 190, 33, 64, 35, 36, 37, 94, 38, 42, 40, 41, 95, 43, 45, 61, 123, 125,
124, 58, 63, 62, 60, 1, 0, 0, 0, 8, 0, 0, 0, 107, 101, 121, 73, 110, 116, 51, 50, 0, 0,
0, 0, 4, 0, 0, 0, 21, 205, 91, 7, 1, 0, 0, 0, 6, 0, 0, 0, 107, 101, 121, 83, 116, 114,
1, 0, 0, 0, 40, 0, 0, 0, 99, 104, 97, 105, 110, 109, 97, 107, 101, 114, 233, 149, 191,
229, 174, 137, 233, 147, 190, 33, 64, 35, 36, 37, 94, 38, 42, 40, 41, 95, 43, 45, 61,
123, 125, 124, 58, 63, 62, 60,
];
let str_val = "chainmaker长安链!@#$%^&*()_+-={}|:?><";
let mut ec = EasyCodec::new();
ec.add_bytes("keyBytes", str_val.as_bytes().to_vec());
ec.add_i32("keyInt32", 123456789);
ec.add_string("keyStr", str_val);
println!("{:?}", ec.to_json());
let data = ec.marshal();
let ec1 = EasyCodec::new_with_bytes(&origin1.to_vec());
assert_equal_byte(data.as_slice(), ec1.marshal().as_slice());
let ec2 = EasyCodec::new_with_bytes(&origin2.to_vec());
assert_equal_byte(data.as_slice(), ec2.marshal().as_slice());
}
fn assert_equal_byte(a: &[u8], b: &[u8]) {
if a.len() != b.len() {
println!("a \t {:?}", a);
println!("b \t {:?}", b);
panic!("not equal")
}
for i in 0..a.len() {
if a[i] != b[i] {
println!("a \t {:?}", a);
println!("b \t {:?}", b);
println!("i {:?} a val={:?} b val={:?}", i, a[i], b[i]);
panic!("not equal")
}
}
}
}
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
#[macro_use]
extern crate serde_derive;
// SDK
pub mod sim_context;
pub mod sim_context_bulletproofs;
pub mod sim_context_paillier;
pub mod sim_context_rs;
pub mod easycodec;
pub mod vec_box;
// fact
//pub mod contract_fact;
//pub mod catalog_0;
pub mod catalog;
//pub mod mock;
//pub mod privacy_computing;
\ No newline at end of file
use serde_json_wasm;
use crate::sim_context;
use sim_context::*;
use std::collections::HashMap;
use crate::easycodec::*;
#[no_mangle]
pub extern "C" fn init_contract() {
sim_context::log("init_contract");
}
#[no_mangle]
pub extern "C" fn upgrade() {
sim_context::log("upgrade");
let ctx = &mut sim_context::get_sim_context();
ctx.ok("upgrade success".as_bytes());
}
#[no_mangle]
pub extern "C" fn version() {
sim_context::log("version");
let ctx = &mut sim_context::get_sim_context();
ctx.ok("v3.2".as_bytes());
ctx.log("v3.2");
}
#[derive(Serialize, Deserialize)]
struct CallResp {
message: String,
project_status: String,
project_status_code: i32,
}
const APPROVAL_COMPLETED: &str = "APPROVAL_COMPLETED";
#[no_mangle]
pub extern "C" fn get_status_by_project_id() {
sim_context::log("init start.");
let ctx = &mut sim_context::get_sim_context();
let project_id = ctx.arg_as_utf8_str("project_id");
if project_id.len() == 0 {
ctx.log("get_status_by_project_id: project_id cannot be null");
ctx.error("get_status_by_project_id: project_id cannot be null");
return;
}
let ret = CallResp {
message: "MOCK".to_string(),
project_status: APPROVAL_COMPLETED.to_string(),
project_status_code: 0,
};
let r = serde_json_wasm::to_string(&ret);
if r.is_err() {
let a = r.err().unwrap().to_string();
let err = &format!("serde_json_wasm jobs to string failed,msg:[{:?}] ", a);
ctx.log(err.as_str());
ctx.error(err.as_str());
return;
}
let resp_json = r.unwrap();
ctx.ok(resp_json.as_bytes());
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
use crate::easycodec::*;
use crate::sim_context::*;
const CONTRACT_METHOD_GET_BULLETPROOFS_RESULT: &str = "GetBulletproofsResult";
const CONTRACT_METHOD_GET_BULLETPROOFS_RESULT_LEN: &str = "GetBulletproofsResultLen";
const BULLETPROOFS_OPERATION_TYPE_PEDERSEN_ADD_NUM: &str = "PedersenAddNum";
const BULLETPROOFS_OPERATION_TYPE_PEDERSEN_ADD_COMMITMENT: &str = "PedersenAddCommitment";
const BULLETPROOFS_OPERATION_TYPE_PEDERSEN_SUB_NUM: &str = "PedersenSubNum";
const BULLETPROOFS_OPERATION_TYPE_PEDERSEN_SUB_COMMITMENT: &str = "PedersenSubCommitment";
const BULLETPROOFS_OPERATION_TYPE_PEDERSEN_MUL_NUM: &str = "PedersenMulNum";
const BULLETPROOFS_VERIFY: &str = "BulletproofsVerify";
/// BulletproofsSimContext is the trait that wrap the bulletproofs method
pub trait BulletproofsSimContext {
/// Compute a commitment to x + y from a commitment to x without revealing the value x, where y is a scalar
///
/// # Arguments
///
/// * `commitment` - C = xB + rB'
/// * `num` - the value y
///
/// # return
///
/// * `return1` - the new commitment to x + y: C' = (x + y)B + rB'
///
fn pedersen_add_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code>;
/// Compute a commitment to x + y from commitments to x and y, without revealing the value x and y
///
/// # Arguments
///
/// * `commitment1` - commitment to x: Cx = xB + rB'
/// * `commitment2` - commitment to y: Cy = yB + sB'
///
/// # return
///
/// * `return1` - commitment to x + y: C = (x + y)B + (r + s)B'
///
fn pedersen_add_commitment(
&self,
commitment1: Vec<u8>,
commitment2: Vec<u8>,
) -> Result<Vec<u8>, result_code>;
/// Compute a commitment to x - y from a commitment to x without revealing the value x, where y is a scalar
///
/// # Arguments
///
/// * `commitment1` - C = xB + rB'
/// * `num` - the value y
///
/// # return
///
/// * `return1` - the new commitment to x - y: C' = (x - y)B + rB'
fn pedersen_sub_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code>;
/// Compute a commitment to x - y from commitments to x and y, without revealing the value x and y
///
/// # Arguments
///
/// * `commitment1` - commitment to x: Cx = xB + rB'
/// * `commitment2` - commitment to y: Cy = yB + sB'
///
/// # return
///
/// * `return1` - commitment to x - y: C = (x - y)B + (r - s)B'
fn pedersen_sub_commitment(
&self,
commitment1: Vec<u8>,
commitment2: Vec<u8>,
) -> Result<Vec<u8>, result_code>;
/// Compute a commitment to x * y from a commitment to x and an integer y, without revealing the value x and y
///
/// # Arguments
///
/// * `commitment1` - commitment to x: Cx = xB + rB'
/// * `num` - integer value y
///
/// # return
///
/// * `return1` - commitment to x * y: C = (x * y)B + (r * y)B'
fn pedersen_mul_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code>;
/// Verify the validity of a proof
///
/// # Arguments
///
/// * `proof` - the zero-knowledge proof proving the number committed in commitment is in the range [0, 2^64)
/// * `commitment` - commitment bindingly hiding the number x
///
/// # return
///
/// * `return1` - true on valid proof, false otherwise
fn verify(&self, proof: Vec<u8>, commitment: Vec<u8>) -> Result<Vec<u8>, result_code>;
}
pub struct BulletproofsSimContextImpl {
pub common: CommonUtils,
}
impl BulletproofsSimContextImpl {
pub fn new(ctx_ptr: result_code) -> BulletproofsSimContextImpl {
BulletproofsSimContextImpl {
common: CommonUtils { ctx_ptr },
}
}
}
impl BulletproofsSimContext for BulletproofsSimContextImpl {
fn pedersen_add_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(
self,
commitment,
num.to_string().into_bytes(),
BULLETPROOFS_OPERATION_TYPE_PEDERSEN_ADD_NUM,
)
}
fn pedersen_add_commitment(
&self,
commitment1: Vec<u8>,
commitment2: Vec<u8>,
) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(
self,
commitment1,
commitment2,
BULLETPROOFS_OPERATION_TYPE_PEDERSEN_ADD_COMMITMENT,
)
}
fn pedersen_sub_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(
self,
commitment,
num.to_string().into_bytes(),
BULLETPROOFS_OPERATION_TYPE_PEDERSEN_SUB_NUM,
)
}
fn pedersen_sub_commitment(
&self,
commitment1: Vec<u8>,
commitment2: Vec<u8>,
) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(
self,
commitment1,
commitment2,
BULLETPROOFS_OPERATION_TYPE_PEDERSEN_SUB_COMMITMENT,
)
}
fn pedersen_mul_num(&self, commitment: Vec<u8>, num: &str) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(
self,
commitment,
num.to_string().into_bytes(),
BULLETPROOFS_OPERATION_TYPE_PEDERSEN_MUL_NUM,
)
}
fn verify(&self, proof: Vec<u8>, commitment: Vec<u8>) -> Result<Vec<u8>, result_code> {
bulletproofs_operation(self, proof, commitment, BULLETPROOFS_VERIFY)
}
}
fn bulletproofs_operation(
bulletproofs_sim_context: &BulletproofsSimContextImpl,
param1: Vec<u8>,
param2: Vec<u8>,
bulletproofs_func_name: &str,
) -> Result<Vec<u8>, result_code> {
let ec = &mut EasyCodec::new();
ec.add_bytes("param1", param1);
ec.add_bytes("param2", param2);
ec.add_string("bulletproofsFuncName", bulletproofs_func_name);
bulletproofs_sim_context.common.get_bytes_from_chain(
ec,
CONTRACT_METHOD_GET_BULLETPROOFS_RESULT_LEN,
CONTRACT_METHOD_GET_BULLETPROOFS_RESULT,
)
}
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
use crate::easycodec::*;
use crate::sim_context::*;
const CONTRACT_METHOD_GET_PAILLIER_OPERATION_RESULT: &str = "GetPaillierOperationResult";
const CONTRACT_METHOD_GET_PAILLIER_OPERATION_RESULT_LEN: &str = "GetPaillierOperationResultLen";
const PAILLIER_OPERATION_TYPE_ADD_CIPHERTEXT: &str = "AddCiphertext";
const PAILLIER_OPERATION_TYPE_ADD_PLAINTEXT: &str = "AddPlaintext";
const PAILLIER_OPERATION_TYPE_SUB_CIPHERTEXT: &str = "SubCiphertext";
const PAILLIER_OPERATION_TYPE_SUB_PLAINTEXT: &str = "SubPlaintext";
const PAILLIER_OPERATION_TYPE_NUM_MUL: &str = "NumMul";
pub trait PaillierSimContext {
// Paillier method
fn add_ciphertext(
&self,
pubkey: Vec<u8>,
ciphertext1: Vec<u8>,
ciphertext2: Vec<u8>,
) -> Result<Vec<u8>, result_code>;
fn add_plaintext(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code>;
fn sub_ciphertext(
&self,
pubkey: Vec<u8>,
ciphertext1: Vec<u8>,
ciphertext2: Vec<u8>,
) -> Result<Vec<u8>, result_code>;
fn sub_plaintext(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code>;
fn num_mul(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code>;
}
pub struct PaillierSimContextImpl {
pub common: CommonUtils,
}
impl PaillierSimContextImpl {
pub fn new(ctx_ptr: i32) -> PaillierSimContextImpl {
PaillierSimContextImpl {
common: CommonUtils { ctx_ptr },
}
}
}
impl PaillierSimContext for PaillierSimContextImpl {
fn add_ciphertext(
&self,
pubkey: Vec<u8>,
ciphertext1: Vec<u8>,
ciphertext2: Vec<u8>,
) -> Result<Vec<u8>, result_code> {
paillier_operation(
self,
pubkey,
ciphertext1,
ciphertext2,
PAILLIER_OPERATION_TYPE_ADD_CIPHERTEXT,
)
}
fn add_plaintext(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code> {
paillier_operation(
self,
pubkey,
ciphertext,
plaintext.to_string().into_bytes(),
PAILLIER_OPERATION_TYPE_ADD_PLAINTEXT,
)
}
fn sub_ciphertext(
&self,
pubkey: Vec<u8>,
ciphertext1: Vec<u8>,
ciphertext2: Vec<u8>,
) -> Result<Vec<u8>, result_code> {
paillier_operation(
self,
pubkey,
ciphertext1,
ciphertext2,
PAILLIER_OPERATION_TYPE_SUB_CIPHERTEXT,
)
}
fn sub_plaintext(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code> {
paillier_operation(
self,
pubkey,
ciphertext,
plaintext.to_string().into_bytes(),
PAILLIER_OPERATION_TYPE_SUB_PLAINTEXT,
)
}
fn num_mul(
&self,
pubkey: Vec<u8>,
ciphertext: Vec<u8>,
plaintext: &str,
) -> Result<Vec<u8>, result_code> {
paillier_operation(
self,
pubkey,
ciphertext,
plaintext.to_string().into_bytes(),
PAILLIER_OPERATION_TYPE_NUM_MUL,
)
}
}
fn paillier_operation(
crypto_sim_context: &PaillierSimContextImpl,
pubkey: Vec<u8>,
operate_one: Vec<u8>,
operate_two: Vec<u8>,
operation_type: &str,
) -> Result<Vec<u8>, result_code> {
let ec = &mut EasyCodec::new();
ec.add_bytes("pubKey", pubkey);
ec.add_bytes("operandOne", operate_one);
ec.add_bytes("operandTwo", operate_two);
ec.add_string("opType", operation_type);
crypto_sim_context.common.get_bytes_from_chain(
ec,
CONTRACT_METHOD_GET_PAILLIER_OPERATION_RESULT_LEN,
CONTRACT_METHOD_GET_PAILLIER_OPERATION_RESULT,
)
}
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
use crate::easycodec::*;
use crate::sim_context::*;
const CONTRACT_METHOD_EXECUTE_QUERY_SQL: &str = "ExecuteQuery"; // 执行sql
const CONTRACT_METHOD_EXECUTE_QUERY_ONE: &str = "ExecuteQueryOne"; // 执行sql
const CONTRACT_METHOD_EXECUTE_QUERY_ONE_LEN: &str = "ExecuteQueryOneLen"; // 执行sql
const CONTRACT_METHOD_ITERATOR_NEXT: &str = "RSNext"; // 迭代获取下一个数据
const CONTRACT_METHOD_ITERATOR_NEXT_LEN: &str = "RSNextLen"; // 迭代获取下一个数据的长度
const CONTRACT_METHOD_ITERATOR_HAS_NEXT: &str = "RSHasNext"; // 迭代获取是否有下一个数据
const CONTRACT_METHOD_ITERATOR_CLOSE: &str = "RSClose"; // 迭代结束
const CONTRACT_METHOD_EXECUTE_UPDATE_SQL: &str = "ExecuteUpdate"; // 执行sql更新语句
const CONTRACT_METHOD_EXECUTE_DDL_SQL: &str = "ExecuteDDL"; // 执行sql DDL语句
pub trait ResultSet {
fn next_row(&self) -> Result<EasyCodec, result_code>;
fn has_next(&self) -> bool;
fn close(&self) -> bool;
}
// 查询迭代
pub struct ResultSetSqlImpl {
pub common: CommonUtils,
pub index: i32,
}
pub struct SqlSimContextImpl {
pub common: CommonUtils,
}
pub trait SqlSimContext {
fn execute_query_one(&self, sql: &str) -> Result<EasyCodec, result_code>;
fn execute_query(&self, sql: &str) -> Result<Box<dyn ResultSet>, result_code>;
/// #### ExecuteUpdateSql execute update/insert/delete sql
/// ##### It is best to update with primary key
///
/// as:
///
/// - update table set name = 'Tom' where uniqueKey='xxx'
/// - delete from table where uniqueKey='xxx'
/// - insert into table(id, xxx,xxx) values(xxx,xxx,xxx)
///
/// ### not allow:
/// - random methods: NOW() RAND() and so on
fn execute_update(&self, sql: &str) -> Result<i32, result_code>;
/// ExecuteDDLSql execute DDL sql, for init_contract or upgrade method. allow table create/alter/drop/truncate
///
/// ## You must have a primary key to create a table
/// ### allow:
/// - CREATE TABLE tableName
/// - ALTER TABLE tableName
/// - DROP TABLE tableName
/// - TRUNCATE TABLE tableName
///
/// ### not allow:
/// - CREATE DATABASE dbName
/// - CREATE TABLE dbName.tableName
/// - ALTER TABLE dbName.tableName
/// - DROP DATABASE dbName
/// - DROP TABLE dbName.tableName
/// - TRUNCATE TABLE dbName.tableName
/// not allow:
/// - random methods: NOW() RAND() and so on
///
fn execute_ddl(&self, sql: &str) -> Result<i32, result_code>;
}
impl SqlSimContext for SqlSimContextImpl {
/// 查询多行数据
fn execute_query(&self, sql: &str) -> Result<Box<dyn ResultSet>, result_code> {
let ec = &mut EasyCodec::new();
ec.add_string("sql", sql);
let r = self
.common
.get_i32_from_chain(ec, CONTRACT_METHOD_EXECUTE_QUERY_SQL);
let index = match r {
Ok(index) => index,
Err(code) => {
return Err(code);
}
};
let rs = ResultSetSqlImpl::new(self.common.ctx_ptr, index);
Ok(Box::new(rs))
}
/// 查询单行数据
fn execute_query_one(&self, sql: &str) -> Result<EasyCodec, result_code> {
let ec = &mut EasyCodec::new();
ec.add_string("sql", sql);
let r = self.common.get_bytes_from_chain(
ec,
CONTRACT_METHOD_EXECUTE_QUERY_ONE_LEN,
CONTRACT_METHOD_EXECUTE_QUERY_ONE,
);
match r {
Ok(bytes) => return Ok(EasyCodec::new_with_bytes(&bytes)),
Err(code) => return Err(code),
}
}
/// 执行更新语句,返回被影响的条数
fn execute_update(&self, sql: &str) -> Result<i32, result_code> {
let ec = &mut EasyCodec::new();
ec.add_string("sql", sql);
self.common
.get_i32_from_chain(ec, CONTRACT_METHOD_EXECUTE_UPDATE_SQL)
}
/// 执行一条DDL语句,返回被影响的条数。只有安装合约和更新合约允许执行
fn execute_ddl(&self, sql: &str) -> Result<i32, result_code> {
let ec = &mut EasyCodec::new();
ec.add_string("sql", sql);
self.common
.get_i32_from_chain(ec, CONTRACT_METHOD_EXECUTE_DDL_SQL)
}
}
impl SqlSimContextImpl {
pub fn new(ctx_ptr: i32) -> SqlSimContextImpl {
SqlSimContextImpl {
common: CommonUtils { ctx_ptr },
}
}
}
// 结构体生命周期不能超过属性的生命周期
impl ResultSetSqlImpl {
pub fn new(ctx_ptr: i32, index: i32) -> ResultSetSqlImpl {
ResultSetSqlImpl {
common: CommonUtils { ctx_ptr },
index,
}
}
}
impl ResultSet for ResultSetSqlImpl {
/// get the next row of data
fn next_row(&self) -> Result<EasyCodec, result_code> {
let ec = &mut EasyCodec::new();
ec.add_i32("rs_index", self.index);
let r = self.common.get_bytes_from_chain(
ec,
CONTRACT_METHOD_ITERATOR_NEXT_LEN,
CONTRACT_METHOD_ITERATOR_NEXT,
);
match r {
Ok(data) => return Ok(EasyCodec::unmarshal(&data)),
Err(code) => return Err(code),
}
}
/// return whether there is a next line
fn has_next(&self) -> bool {
let ec = &mut EasyCodec::new();
ec.add_i32("rs_index", self.index);
let r = self
.common
.get_i32_from_chain(ec, CONTRACT_METHOD_ITERATOR_HAS_NEXT);
match r {
Ok(state) => {
if state == 0 {
return false;
} else {
return true;
}
}
_ => false,
}
}
/// close the query statement
fn close(&self) -> bool {
let ec = &mut EasyCodec::new();
ec.add_i32("rs_index", self.index);
let r = self
.common
.get_i32_from_chain(ec, CONTRACT_METHOD_ITERATOR_CLOSE);
match r {
Ok(_) => true,
_ => false,
}
}
}
///
/// Copyright (C) BABEC. All rights reserved.
///
/// SPDX-License-Identifier: Apache-2.0
///
// use crate::sim_context;
use std::mem::ManuallyDrop;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Debug)]
pub struct VecBox<T> {
data: ManuallyDrop<Box<Vec<T>>>,
}
impl<T: Copy> VecBox<T> {
/// get_instance 全局静态实例,每个instance实例一次。用于chan执行智能合约方法时,往智能合约传输数据
pub fn get_instance(capacity: usize) -> Arc<Mutex<VecBox<u8>>> {
static mut VECBOX: Option<Arc<Mutex<VecBox<u8>>>> = None;
unsafe {
// Rust中使用可变静态变量都是unsafe的
let v = VECBOX
.get_or_insert_with(|| {
// 初始化单例对象的代码
// sim_context::log(&format!("new instance size={}", capacity));
let instance: VecBox<u8> = VecBox::new(capacity);
Arc::new(Mutex::new(instance))
})
.clone();
v
}
}
/// new 根据size 申请对应大小的数据内存
pub fn new(capacity: usize) -> VecBox<T> {
let v: Vec<T> = Vec::with_capacity(capacity);
let b = Box::new(v);
Self {
data: ManuallyDrop::new(b),
}
}
pub fn reset_data_size(&mut self, capacity: usize) {
self.deallocated();
// sim_context::log(&format!("new data allocate size={}", capacity));
let v: Vec<T> = Vec::with_capacity(capacity);
let b = Box::new(v);
self.data = ManuallyDrop::new(b);
}
pub fn deallocated(&mut self) {
unsafe {
let _ = ManuallyDrop::drop(&mut self.data);
}
}
pub fn drop(&mut self) {
unsafe {
let _ = ManuallyDrop::drop(&mut self.data);
}
}
pub fn data_as_mut(&mut self) -> &Vec<T> {
self.data.as_mut()
}
pub fn copy<'a>(&'a mut self, vec: &Vec<T>) -> Result<usize, &str> {
let size = vec.len() as usize;
// Write get_state parameters into memory, then vm host could obtain the parameters.
let buffer = self.data.as_mut();
if buffer.capacity() >= size {
for b in vec {
buffer.push(*b);
}
Ok(size)
} else {
Err("Vec size overflow")
}
}
pub fn len(&mut self) -> usize {
return self.data.capacity();
}
pub fn as_mut_ptr(&mut self) -> *mut T {
return self.data.as_mut_ptr();
}
pub fn as_ptr(&mut self) -> *const T {
return self.data.as_ptr();
}
pub fn as_ptr_i32(&mut self) -> i32 {
return self.data.as_ptr() as i32;
}
pub fn as_ptr_str(&mut self) -> String {
(self.data.as_ptr() as i32).to_string()
}
pub fn data_ptr(&mut self) -> *const T {
let s = &mut self.data.as_ref();
(*s).as_ptr()
}
pub fn value(&mut self) -> &Vec<T> {
let s = self.data.as_ref();
s
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment