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

Commit 1978190b authored by edric wei's avatar edric wei

Merge remote-tracking branch 'origin/v2.2.0_alpha_qc' into develop_guanghong

parents 6e471a38 30ccae1f
...@@ -2,4 +2,5 @@ ...@@ -2,4 +2,5 @@
bin bin
*.log *.log
*.log.* *.log.*
cover.out cover.out
\ No newline at end of file test
\ No newline at end of file
run:
timeout: 10m
tests: true
# default is true. Enables skipping of directories:
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
skip-dirs-use-default: true
# skip-files:
skip-dirs:
- p2p #from libp2p
- mock #from gomock
- protogo #from pb generate
- sqldbprovider #will remove
- eventsqldb
- evm-go
- gasm-go
- wasmer-go
linters:
disable-all: true
enable:
- deadcode
- goconst
- gocyclo
- gofmt
- ineffassign
- staticcheck
- structcheck # 当非导出结构嵌入另一个结构, 前一个结构被使用就不会监测到, 这个需要每个业务自己屏蔽
- typecheck
- goimports
- revive
- gosimple
- govet
- lll
- rowserrcheck
- errcheck
- misspell
- unused
- varcheck
- sqlclosecheck
- gosec
linters-settings:
goconst:
min-len: 2
min-occurrences: 2
gocyclo:
min-complexity: 20
goimports:
#local-prefixes: git.code.oa.com
golint:
#min-confidence: 0
govet:
check-shadowing: true
gosimple:
go: "1.15"
lll:
line-length: 120
errcheck:
check-type-assertions: true
gocritic:
enabled-checks:
- nestingReduce
settings:
nestingReduce:
bodyWidth: 5
revive:
# see https://github.com/mgechev/revive#available-rules for details.
rules:
# - name: blank-imports
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: error-return
- name: error-strings
- name: error-naming
- name: exported
- name: if-return
- name: increment-decrement
# - name: var-naming
- name: var-declaration
- name: package-comments
- name: range
# - name: receiver-naming
- name: time-naming
- name: unexported-return
- name: indent-error-flow
- name: errorf
- name: empty-block
- name: superfluous-else
- name: unexported-naming
- name: unexported-return
- name: unreachable-code
- name: redefines-builtin-id
- name: function-length
arguments: [ 80,0 ]
issues:
exclude-use-default: true
include:
- EXC0002 # golint (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form)
- EXC0003 # golint func name will be used as test\\.Test.* by other packages, and that stutters; consider calling this
#- EXC0004 # govet (possible misuse of unsafe.Pointer|should have signature)
- EXC0005 # staticcheck ineffective break statement. Did you mean to break out of the outer loop
- EXC0011 # stylecheck (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form)
exclude-rules:
- path: .*_test.go
linters:
- unused
- deadcode
- ineffassign
- staticcheck
- forbidigo
- dupl
- errcheck
- lll
- funlen
- linters:
- revive
text: "stutters"
- linters:
- errcheck
text: "json.Unmarshal"
- linters:
- gosec
text: "G108|G204|G501|G401"
max-same-issues: 0
new: false
max-issues-per-linter: 0
output:
sort-results: true
\ No newline at end of file
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
VERSION=v2.2.0_alpha_qc
VERSION_DEVELOP=develop
gomod:
go get chainmaker.org/chainmaker/pb-go/v2@$(VERSION)
go get chainmaker.org/chainmaker/common/v2@$(VERSION_DEVELOP)
go get chainmaker.org/chainmaker/protocol/v2@$(VERSION)
go get chainmaker.org/chainmaker/logger/v2@$(VERSION_DEVELOP)
go get chainmaker.org/chainmaker/utils/v2@$(VERSION)
go get chainmaker.org/chainmaker/localconf/v2@$(VERSION)
go get chainmaker.org/chainmaker/chainconf/v2@$(VERSION)
go mod tidy
lint:
golangci-lint run ./...
ut:
mkdir -p ../ut-vm-native
go test -v -coverprofile=../ut-vm-native/cover.out ./...
go tool cover -html=../ut-vm-native/cover.out -o ../ut-vm-native/coverage.html
\ No newline at end of file
长安链·ChainMaker
Copyright 2021 contributors to 长安链·ChainMaker
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
package accountmgr
import "chainmaker.org/chainmaker/protocol/v2"
type AccountMgr interface {
/**
* @Description: 设置gas管理员
* @param publicKey
* @return bool
* @return error
*/
SetAdmin(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 查询gas管理员
* @param publicKey
* @return []byte
* @return error
*/
GetAdmin(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 充值gas
* @param publicKey
* @param gas
* @return bool
* @return error
*/
RechargeGas(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 扣款for vm
* @param publicKey
* @param gas
* @return bool
* @return error
*/
ChargeGasVm(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 退还多扣的gas for vm
* @param: publicKey 发起交易的账户公钥
* @param: gas 退还gas数量
* @return bool 是否退还成功
* @return error
*/
RefundGasVm(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 查询gas余额
* @param publicKey
* @return uint64
* @return error
*/
GetBalance(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 退款for sdk
* @param publicKey
* @param gasUsed
* @return bool
* @return error
*/
RefundGas(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 冻结指定账户
* @param publicKey
* @return bool
* @return error
*/
FrozenAccount(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 解冻指定账号
* @param txSimContext
* @param params
* @return []byte
* @return error
*/
UnFrozenAccount(txSimContext protocol.TxSimContext, params map[string][]byte) ([]byte, error)
/**
* @Description: 获取账户冻结状态
* @param publicKey
* @return bool
* @return error
*/
GetAccountStatus(context protocol.TxSimContext, params map[string][]byte) ([]byte, error)
}
...@@ -17,7 +17,9 @@ import ( ...@@ -17,7 +17,9 @@ import (
"strconv" "strconv"
"strings" "strings"
"chainmaker.org/chainmaker/vm-native/common" "chainmaker.org/chainmaker/utils/v2"
"chainmaker.org/chainmaker/vm-native/v2/common"
"chainmaker.org/chainmaker/common/v2/crypto/hash" "chainmaker.org/chainmaker/common/v2/crypto/hash"
"chainmaker.org/chainmaker/localconf/v2" "chainmaker.org/chainmaker/localconf/v2"
...@@ -26,7 +28,6 @@ import ( ...@@ -26,7 +28,6 @@ import (
storage "chainmaker.org/chainmaker/pb-go/v2/store" storage "chainmaker.org/chainmaker/pb-go/v2/store"
"chainmaker.org/chainmaker/pb-go/v2/syscontract" "chainmaker.org/chainmaker/pb-go/v2/syscontract"
"chainmaker.org/chainmaker/protocol/v2" "chainmaker.org/chainmaker/protocol/v2"
"chainmaker.org/chainmaker/utils/v2"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
) )
...@@ -35,14 +36,17 @@ const ( ...@@ -35,14 +36,17 @@ const (
paramNameWithRWSet = "withRWSet" paramNameWithRWSet = "withRWSet"
paramNameBlockHash = "blockHash" paramNameBlockHash = "blockHash"
paramNameTxId = "txId" paramNameTxId = "txId"
TRUE = "true" // TRUE string const
TRUE = "true"
) )
var ( var (
logTemplateMarshalBlockInfoFailed = "marshal block info failed, %s" logTemplateMarshalBlockInfoFailed = "marshal block info failed, %s"
errStoreIsNil = fmt.Errorf("store is nil") errStoreIsNil = fmt.Errorf("store is nil")
//errDataNotFound = fmt.Errorf("data not found")
) )
type BlockHeight int64
type BlockContract struct { type BlockContract struct {
methods map[string]common.ContractFunc methods map[string]common.ContractFunc
log protocol.Logger log protocol.Logger
...@@ -63,22 +67,26 @@ func registerBlockContractMethods(log protocol.Logger) map[string]common.Contrac ...@@ -63,22 +67,26 @@ func registerBlockContractMethods(log protocol.Logger) map[string]common.Contrac
q := make(map[string]common.ContractFunc, 64) q := make(map[string]common.ContractFunc, 64)
b := &BlockRuntime{log: log} b := &BlockRuntime{log: log}
q[syscontract.ChainQueryFunction_GET_BLOCK_BY_HEIGHT.String()] = b.GetBlockByHeight q[syscontract.ChainQueryFunction_GET_BLOCK_BY_HEIGHT.String()] = common.WrapResultFunc(b.GetBlockByHeight)
q[syscontract.ChainQueryFunction_GET_BLOCK_WITH_TXRWSETS_BY_HEIGHT.String()] = b.GetBlockWithTxRWSetsByHeight q[syscontract.ChainQueryFunction_GET_BLOCK_WITH_TXRWSETS_BY_HEIGHT.String()] = common.WrapResultFunc(
q[syscontract.ChainQueryFunction_GET_BLOCK_BY_HASH.String()] = b.GetBlockByHash b.GetBlockWithTxRWSetsByHeight)
q[syscontract.ChainQueryFunction_GET_BLOCK_WITH_TXRWSETS_BY_HASH.String()] = b.GetBlockWithTxRWSetsByHash q[syscontract.ChainQueryFunction_GET_BLOCK_BY_HASH.String()] = common.WrapResultFunc(b.GetBlockByHash)
q[syscontract.ChainQueryFunction_GET_BLOCK_BY_TX_ID.String()] = b.GetBlockByTxId q[syscontract.ChainQueryFunction_GET_BLOCK_WITH_TXRWSETS_BY_HASH.String()] = common.WrapResultFunc(
q[syscontract.ChainQueryFunction_GET_TX_BY_TX_ID.String()] = b.GetTxByTxId b.GetBlockWithTxRWSetsByHash)
q[syscontract.ChainQueryFunction_GET_LAST_CONFIG_BLOCK.String()] = b.GetLastConfigBlock q[syscontract.ChainQueryFunction_GET_BLOCK_BY_TX_ID.String()] = common.WrapResultFunc(b.GetBlockByTxId)
q[syscontract.ChainQueryFunction_GET_LAST_BLOCK.String()] = b.GetLastBlock q[syscontract.ChainQueryFunction_GET_TX_BY_TX_ID.String()] = common.WrapResultFunc(b.GetTxByTxId)
q[syscontract.ChainQueryFunction_GET_CHAIN_INFO.String()] = b.GetChainInfo q[syscontract.ChainQueryFunction_GET_LAST_CONFIG_BLOCK.String()] = common.WrapResultFunc(b.GetLastConfigBlock)
q[syscontract.ChainQueryFunction_GET_NODE_CHAIN_LIST.String()] = b.GetNodeChainList q[syscontract.ChainQueryFunction_GET_LAST_BLOCK.String()] = common.WrapResultFunc(b.GetLastBlock)
q[syscontract.ChainQueryFunction_GET_FULL_BLOCK_BY_HEIGHT.String()] = b.GetFullBlockByHeight q[syscontract.ChainQueryFunction_GET_CHAIN_INFO.String()] = common.WrapResultFunc(b.GetChainInfo)
q[syscontract.ChainQueryFunction_GET_BLOCK_HEIGHT_BY_TX_ID.String()] = b.GetBlockHeightByTxId q[syscontract.ChainQueryFunction_GET_NODE_CHAIN_LIST.String()] = common.WrapResultFunc(b.GetNodeChainList)
q[syscontract.ChainQueryFunction_GET_BLOCK_HEIGHT_BY_HASH.String()] = b.GetBlockHeightByHash q[syscontract.ChainQueryFunction_GET_FULL_BLOCK_BY_HEIGHT.String()] = common.WrapResultFunc(b.GetFullBlockByHeight)
q[syscontract.ChainQueryFunction_GET_BLOCK_HEADER_BY_HEIGHT.String()] = b.GetBlockHeaderByHeight q[syscontract.ChainQueryFunction_GET_BLOCK_HEIGHT_BY_TX_ID.String()] = common.WrapResultFunc(b.GetBlockHeightByTxId)
q[syscontract.ChainQueryFunction_GET_ARCHIVED_BLOCK_HEIGHT.String()] = b.GetArchiveBlockHeight q[syscontract.ChainQueryFunction_GET_BLOCK_HEIGHT_BY_HASH.String()] = common.WrapResultFunc(b.GetBlockHeightByHash)
q[syscontract.ChainQueryFunction_GET_MERKLE_PATH_BY_TX_ID.String()] = b.GetMerklePathByTxId q[syscontract.ChainQueryFunction_GET_BLOCK_HEADER_BY_HEIGHT.String()] = common.WrapResultFunc(
b.GetBlockHeaderByHeight)
q[syscontract.ChainQueryFunction_GET_ARCHIVED_BLOCK_HEIGHT.String()] = common.WrapResultFunc(
b.GetArchiveBlockHeight)
q[syscontract.ChainQueryFunction_GET_MERKLE_PATH_BY_TX_ID.String()] = common.WrapResultFunc(b.GetMerklePathByTxId)
return q return q
} }
...@@ -139,11 +147,6 @@ func (r *BlockRuntime) GetChainInfo(txSimContext protocol.TxSimContext, paramete ...@@ -139,11 +147,6 @@ func (r *BlockRuntime) GetChainInfo(txSimContext protocol.TxSimContext, paramete
return nil, errStoreIsNil return nil, errStoreIsNil
} }
provider, err := txSimContext.GetChainNodesInfoProvider()
if err != nil {
return nil, fmt.Errorf("get ChainNodesInfoProvider error: %s", err)
}
var block *commonPb.Block var block *commonPb.Block
var nodes []*discoveryPb.Node var nodes []*discoveryPb.Node
...@@ -151,8 +154,13 @@ func (r *BlockRuntime) GetChainInfo(txSimContext protocol.TxSimContext, paramete ...@@ -151,8 +154,13 @@ func (r *BlockRuntime) GetChainInfo(txSimContext protocol.TxSimContext, paramete
return nil, err return nil, err
} }
if nodes, err = r.getChainNodeInfo(provider, chainId); err != nil { var provider protocol.ChainNodesInfoProvider
return nil, err if provider, err = txSimContext.GetChainNodesInfoProvider(); err != nil {
r.log.Warn(err)
} else {
if nodes, err = r.getChainNodeInfo(provider, chainId); err != nil {
return nil, err
}
} }
chainInfo := &discoveryPb.ChainInfo{ chainInfo := &discoveryPb.ChainInfo{
...@@ -571,16 +579,18 @@ func (r *BlockRuntime) GetLastBlock(txSimContext protocol.TxSimContext, paramete ...@@ -571,16 +579,18 @@ func (r *BlockRuntime) GetLastBlock(txSimContext protocol.TxSimContext, paramete
} }
func (r *BlockRuntime) GetTxByTxId(txSimContext protocol.TxSimContext, parameters map[string][]byte) ([]byte, error) { func (r *BlockRuntime) GetTxByTxId(txSimContext protocol.TxSimContext, parameters map[string][]byte) ([]byte, error) {
var errMsg string //var errMsg string
var err error var err error
var transactionInfoBytes []byte //var transactionInfoBytes []byte
// check params // check params
var param *BlockRuntimeParam var param *BlockRuntimeParam
if param, err = r.validateParams(parameters, paramNameTxId); err != nil { if param, err = r.validateParamsAndLen(parameters, false, paramNameTxId); err != nil {
return nil, err return nil, err
} }
if withRWSet, ok := parameters[paramNameWithRWSet]; ok {
param.withRWSet = string(withRWSet)
}
chainId := txSimContext.GetTx().Payload.ChainId chainId := txSimContext.GetTx().Payload.ChainId
store := txSimContext.GetBlockchainStore() store := txSimContext.GetBlockchainStore()
...@@ -588,33 +598,47 @@ func (r *BlockRuntime) GetTxByTxId(txSimContext protocol.TxSimContext, parameter ...@@ -588,33 +598,47 @@ func (r *BlockRuntime) GetTxByTxId(txSimContext protocol.TxSimContext, parameter
return nil, errStoreIsNil return nil, errStoreIsNil
} }
var tx *commonPb.Transaction if strings.ToLower(param.withRWSet) == "true" {
var block *commonPb.Block txInfoWithRWSet, err1 := r.getTxInfoWithRWSetByTxId(store, chainId, param.txId)
if err1 != nil {
if tx, err = r.getTxByTxId(store, chainId, param.txId); err != nil { return nil, err1
return nil, err }
} return txInfoWithRWSet.Marshal()
if block, err = r.getBlockByTxId(store, chainId, param.txId); err != nil {
return nil, err
}
transactionInfo := &commonPb.TransactionInfo{
Transaction: tx,
BlockHeight: uint64(block.Header.BlockHeight),
}
if transactionInfo, err = checkRoleAndGenerateTransactionInfo(txSimContext, transactionInfo); err != nil {
return nil, err
} }
txInfo, err := r.getTxWithInfoByTxId(store, chainId, param.txId)
transactionInfoBytes, err = proto.Marshal(transactionInfo)
if err != nil { if err != nil {
errMsg = fmt.Sprintf("marshal tx failed, %s", err.Error()) return nil, err
r.log.Errorf(errMsg)
return nil, fmt.Errorf(errMsg)
} }
return transactionInfoBytes, nil return txInfo.Marshal()
//var tx *commonPb.Transaction
//var block *commonPb.Block
//
//if tx, err = r.getTxByTxId(store, chainId, param.txId); err != nil {
// return nil, err
//}
//
//if block, err = r.getBlockByTxId(store, chainId, param.txId); err != nil {
// return nil, err
//}
//
//transactionInfo := &commonPb.TransactionInfo{
// Transaction: tx,
// BlockHeight: uint64(block.Header.BlockHeight),
//}
//
//TODO:Devin 什么情况下要检查权限,从而决定只返回区块高度还是包含其他信息呢?
//if transactionInfo, err = checkRoleAndGenerateTransactionInfo(txSimContext, transactionInfo); err != nil {
// return nil, err
//}
//
//transactionInfoBytes, err = proto.Marshal(transactionInfo)
//if err != nil {
// errMsg = fmt.Sprintf("marshal tx failed, %s", err.Error())
// r.log.Errorf(errMsg)
// return nil, fmt.Errorf(errMsg)
//}
//return transactionInfoBytes, nil
} }
...@@ -831,11 +855,10 @@ func (r *BlockRuntime) getBlockHeaderByHeight(store protocol.BlockchainStore, ch ...@@ -831,11 +855,10 @@ func (r *BlockRuntime) getBlockHeaderByHeight(store protocol.BlockchainStore, ch
err = r.handleError(blockHeader, err, chainId) err = r.handleError(blockHeader, err, chainId)
return blockHeader, err return blockHeader, err
} }
func (r *BlockRuntime) getBlockHeightByTxId(store protocol.BlockchainStore, chainId string, txId string) ( func (r *BlockRuntime) getBlockHeightByTxId(store protocol.BlockchainStore, chainId string, txId string) (
uint64, error) { uint64, error) {
height, err := store.GetTxHeight(txId) height, err := store.GetTxHeight(txId)
err = r.handleError(height, err, chainId) err = r.handleError(BlockHeight(height), err, chainId)
return height, err return height, err
} }
...@@ -847,7 +870,7 @@ func (r *BlockRuntime) getBlockHeightByHash(store protocol.BlockchainStore, chai ...@@ -847,7 +870,7 @@ func (r *BlockRuntime) getBlockHeightByHash(store protocol.BlockchainStore, chai
return 0, fmt.Errorf("decode hash failed, %s", err) return 0, fmt.Errorf("decode hash failed, %s", err)
} }
height, err := store.GetHeightByHash(hashBytes) height, err := store.GetHeightByHash(hashBytes)
err = r.handleError(height, err, chainId) err = r.handleError(BlockHeight(height), err, chainId)
return height, err return height, err
} }
...@@ -877,13 +900,18 @@ func (r *BlockRuntime) getLastConfigBlock(store protocol.BlockchainStore, chainI ...@@ -877,13 +900,18 @@ func (r *BlockRuntime) getLastConfigBlock(store protocol.BlockchainStore, chainI
return block, err return block, err
} }
func (r *BlockRuntime) getTxByTxId(store protocol.BlockchainStore, chainId string, txId string) ( func (r *BlockRuntime) getTxWithInfoByTxId(store protocol.BlockchainStore, chainId string, txId string) (
*commonPb.Transaction, error) { *commonPb.TransactionInfo, error) {
tx, err := store.GetTx(txId) tx, err := store.GetTxWithInfo(txId)
err = r.handleError(tx, err, chainId) err = r.handleErrorSpecTypeName(tx, err, "transaction", chainId)
return tx, err
}
func (r *BlockRuntime) getTxInfoWithRWSetByTxId(store protocol.BlockchainStore, chainId string, txId string) (
*commonPb.TransactionInfoWithRWSet, error) {
tx, err := store.GetTxInfoWithRWSet(txId)
err = r.handleErrorSpecTypeName(tx, err, "transaction", chainId)
return tx, err return tx, err
} }
func (r *BlockRuntime) getTxRWSetsByBlock(store protocol.BlockchainStore, chainId string, block *commonPb.Block) ( func (r *BlockRuntime) getTxRWSetsByBlock(store protocol.BlockchainStore, chainId string, block *commonPb.Block) (
[]*commonPb.TxRWSet, error) { []*commonPb.TxRWSet, error) {
var txRWSets []*commonPb.TxRWSet var txRWSets []*commonPb.TxRWSet
...@@ -911,7 +939,12 @@ func (r *BlockRuntime) GetArchiveBlockHeight(context protocol.TxSimContext, para ...@@ -911,7 +939,12 @@ func (r *BlockRuntime) GetArchiveBlockHeight(context protocol.TxSimContext, para
} }
func (r *BlockRuntime) handleError(value interface{}, err error, chainId string) error { func (r *BlockRuntime) handleError(value interface{}, err error, chainId string) error {
typeName := strings.ToLower(strings.Split(fmt.Sprintf("%T", value), ".")[1]) tn := strings.Split(fmt.Sprintf("%T", value), ".")
typeName := strings.ToLower(tn[len(tn)-1])
return r.handleErrorSpecTypeName(value, err, typeName, chainId)
}
func (r *BlockRuntime) handleErrorSpecTypeName(value interface{}, err error, typeName, chainId string) error {
if err != nil { if err != nil {
r.log.Errorf("get %s from store failed, [chainId:%s], %s", typeName, chainId, err.Error()) r.log.Errorf("get %s from store failed, [chainId:%s], %s", typeName, chainId, err.Error())
return fmt.Errorf("get %s failed, %s", typeName, err) return fmt.Errorf("get %s failed, %s", typeName, err)
...@@ -926,11 +959,15 @@ func (r *BlockRuntime) handleError(value interface{}, err error, chainId string) ...@@ -926,11 +959,15 @@ func (r *BlockRuntime) handleError(value interface{}, err error, chainId string)
} }
func (r *BlockRuntime) validateParams(parameters map[string][]byte, keyNames ...string) (*BlockRuntimeParam, error) { func (r *BlockRuntime) validateParams(parameters map[string][]byte, keyNames ...string) (*BlockRuntimeParam, error) {
return r.validateParamsAndLen(parameters, true, keyNames...)
}
func (r *BlockRuntime) validateParamsAndLen(parameters map[string][]byte, checkParamLen bool, keyNames ...string) (
*BlockRuntimeParam, error) {
var ( var (
errMsg string errMsg string
err error err error
) )
if len(parameters) != len(keyNames) { if checkParamLen && len(parameters) != len(keyNames) {
errMsg = fmt.Sprintf("invalid params len, need [%s]", strings.Join(keyNames, "|")) errMsg = fmt.Sprintf("invalid params len, need [%s]", strings.Join(keyNames, "|"))
r.log.Error(errMsg) r.log.Error(errMsg)
return nil, errors.New(errMsg) return nil, errors.New(errMsg)
...@@ -995,33 +1032,33 @@ func checkRoleAndFilterBlockTxs(block *commonPb.Block, txSimContext protocol.TxS ...@@ -995,33 +1032,33 @@ func checkRoleAndFilterBlockTxs(block *commonPb.Block, txSimContext protocol.TxS
return block, nil return block, nil
} }
func checkRoleAndGenerateTransactionInfo(txSimContext protocol.TxSimContext, //func checkRoleAndGenerateTransactionInfo(txSimContext protocol.TxSimContext,
transactionInfo *commonPb.TransactionInfo) (*commonPb.TransactionInfo, error) { // transactionInfo *commonPb.TransactionInfo) (*commonPb.TransactionInfo, error) {
var ( // var (
reqSender protocol.Role // reqSender protocol.Role
err error // err error
ac protocol.AccessControlProvider // ac protocol.AccessControlProvider
) // )
tx := transactionInfo.Transaction // tx := transactionInfo.Transaction
//
if ac, err = txSimContext.GetAccessControl(); err != nil { // if ac, err = txSimContext.GetAccessControl(); err != nil {
return nil, err // return nil, err
} // }
//
if reqSender, err = utils.GetRoleFromTx(txSimContext.GetTx(), ac); err != nil { // if reqSender, err = utils.GetRoleFromTx(txSimContext.GetTx(), ac); err != nil {
return nil, err // return nil, err
} // }
//
if reqSender == protocol.RoleLight { // if reqSender == protocol.RoleLight {
if tx.Sender.Signer.OrgId != txSimContext.GetTx().Sender.Signer.OrgId { // if tx.Sender.Signer.OrgId != txSimContext.GetTx().Sender.Signer.OrgId {
newTransactionInfo := &commonPb.TransactionInfo{ // newTransactionInfo := &commonPb.TransactionInfo{
Transaction: nil, // Transaction: nil,
BlockHeight: transactionInfo.BlockHeight, // BlockHeight: transactionInfo.BlockHeight,
BlockHash: transactionInfo.BlockHash, // BlockHash: transactionInfo.BlockHash,
TxIndex: transactionInfo.TxIndex, // TxIndex: transactionInfo.TxIndex,
} // }
return newTransactionInfo, nil // return newTransactionInfo, nil
} // }
} // }
return transactionInfo, nil // return transactionInfo, nil
} //}
/*
* Copyright (C) BABEC. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package blockcontract
import (
"fmt"
"testing"
"chainmaker.org/chainmaker/protocol/v2/test"
"github.com/stretchr/testify/require"
)
func Test_handleError(t *testing.T) {
br := BlockRuntime{
log: &test.GoLogger{},
}
err := br.handleError(BlockHeight(0), fmt.Errorf("not found"), "chain1")
require.NotNil(t, err)
err = br.handleError(BlockHeight(0), nil, "chain1")
require.Nil(t, err)
}
...@@ -18,10 +18,6 @@ import ( ...@@ -18,10 +18,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"time"
"chainmaker.org/chainmaker/vm-native/chainconfigmgr"
"chainmaker.org/chainmaker/vm-native/common"
bcx509 "chainmaker.org/chainmaker/common/v2/crypto/x509" bcx509 "chainmaker.org/chainmaker/common/v2/crypto/x509"
pbac "chainmaker.org/chainmaker/pb-go/v2/accesscontrol" pbac "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
...@@ -30,6 +26,8 @@ import ( ...@@ -30,6 +26,8 @@ import (
"chainmaker.org/chainmaker/pb-go/v2/syscontract" "chainmaker.org/chainmaker/pb-go/v2/syscontract"
"chainmaker.org/chainmaker/protocol/v2" "chainmaker.org/chainmaker/protocol/v2"
"chainmaker.org/chainmaker/utils/v2" "chainmaker.org/chainmaker/utils/v2"
"chainmaker.org/chainmaker/vm-native/v2/chainconfigmgr"
"chainmaker.org/chainmaker/vm-native/v2/common"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
) )
...@@ -60,13 +58,13 @@ func registerCertManageContractMethods(log protocol.Logger) map[string]common.Co ...@@ -60,13 +58,13 @@ func registerCertManageContractMethods(log protocol.Logger) map[string]common.Co
// cert manager // cert manager
certManageRuntime := &CertManageRuntime{log: log} certManageRuntime := &CertManageRuntime{log: log}
methodMap[syscontract.CertManageFunction_CERT_ADD.String()] = certManageRuntime.Add methodMap[syscontract.CertManageFunction_CERT_ADD.String()] = common.WrapResultFunc(certManageRuntime.Add)
methodMap[syscontract.CertManageFunction_CERTS_DELETE.String()] = certManageRuntime.Delete methodMap[syscontract.CertManageFunction_CERTS_DELETE.String()] = common.WrapResultFunc(certManageRuntime.Delete)
methodMap[syscontract.CertManageFunction_CERTS_FREEZE.String()] = certManageRuntime.Freeze methodMap[syscontract.CertManageFunction_CERTS_FREEZE.String()] = common.WrapResultFunc(certManageRuntime.Freeze)
methodMap[syscontract.CertManageFunction_CERTS_UNFREEZE.String()] = certManageRuntime.Unfreeze methodMap[syscontract.CertManageFunction_CERTS_UNFREEZE.String()] = common.WrapResultFunc(certManageRuntime.Unfreeze)
methodMap[syscontract.CertManageFunction_CERTS_REVOKE.String()] = certManageRuntime.Revoke methodMap[syscontract.CertManageFunction_CERTS_REVOKE.String()] = common.WrapResultFunc(certManageRuntime.Revoke)
// query // query
methodMap[syscontract.CertManageFunction_CERTS_QUERY.String()] = certManageRuntime.Query methodMap[syscontract.CertManageFunction_CERTS_QUERY.String()] = common.WrapResultFunc(certManageRuntime.Query)
return methodMap return methodMap
} }
...@@ -78,30 +76,29 @@ type CertManageRuntime struct { ...@@ -78,30 +76,29 @@ type CertManageRuntime struct {
func (r *CertManageRuntime) Add(txSimContext protocol.TxSimContext, _ map[string][]byte) ( func (r *CertManageRuntime) Add(txSimContext protocol.TxSimContext, _ map[string][]byte) (
result []byte, err error) { result []byte, err error) {
tx := txSimContext.GetTx() memberInfo := txSimContext.GetTx().Sender.Signer.GetMemberInfo()
sender := tx.Sender
memberInfo := sender.Signer.GetMemberInfo()
ac, err := txSimContext.GetAccessControl() ac, err := txSimContext.GetAccessControl()
if err != nil { if err != nil {
r.log.Errorf("txSimContext.GetAccessControl failed, err: %s", err.Error()) r.log.Warnf("txSimContext.GetAccessControl failed, err: %s", err.Error())
return nil, err return nil, err
} }
hashType := ac.GetHashAlg() hashType := ac.GetHashAlg()
certHash, err := utils.GetCertificateIdHex(memberInfo, hashType) certHash, err := utils.GetCertificateIdHex(memberInfo, hashType)
if err != nil { if err != nil {
r.log.Errorf("get certHash failed, err: %s", err.Error()) r.log.Warnf("get certHash failed, err: %s", err.Error())
return nil, err return nil, err
} }
err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash), memberInfo) err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash), memberInfo)
if err != nil { if err != nil {
r.log.Errorf("certManage add cert failed, err: %s", err.Error()) r.log.Warnf("certManage add cert failed, err: %s", err.Error())
return nil, err return nil, err
} }
r.log.Infof("certManage add cert success certHash[%s] memberInfo[%s]", certHash, string(memberInfo)) r.log.Infof("certManage add cert success."+
" certHash[%s] memberInfo[%s] hashType[%s]", certHash, string(memberInfo), hashType)
return []byte(certHash), nil return []byte(certHash), nil
} }
...@@ -114,7 +111,7 @@ func (r *CertManageRuntime) Delete(txSimContext protocol.TxSimContext, params ma ...@@ -114,7 +111,7 @@ func (r *CertManageRuntime) Delete(txSimContext protocol.TxSimContext, params ma
if utils.IsAnyBlank(certHashesStr) { if utils.IsAnyBlank(certHashesStr) {
err = fmt.Errorf("%s, delete cert require param [%s] not found", common.ErrParams.Error(), paramNameCertHashes) err = fmt.Errorf("%s, delete cert require param [%s] not found", common.ErrParams.Error(), paramNameCertHashes)
r.log.Error(err) r.log.Warn(err)
return nil, err return nil, err
} }
...@@ -122,20 +119,20 @@ func (r *CertManageRuntime) Delete(txSimContext protocol.TxSimContext, params ma ...@@ -122,20 +119,20 @@ func (r *CertManageRuntime) Delete(txSimContext protocol.TxSimContext, params ma
for _, certHash := range certHashes { for _, certHash := range certHashes {
bytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash)) bytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash))
if err != nil { if err != nil {
r.log.Errorf("certManage delete the certHash failed, certHash[%s], err: %s", certHash, err.Error()) r.log.Warnf("certManage delete the certHash failed, certHash[%s], err: %s", certHash, err.Error())
return nil, err return nil, err
} }
if len(bytes) == 0 { if len(bytes) == 0 {
msg := fmt.Sprintf( msg := fmt.Sprintf(
"certManage delete the certHash failed, certHash[%s], err: certHash is not exist", certHash) "certManage delete the certHash failed, certHash[%s], err: certHash is not exist", certHash)
r.log.Error(msg) r.log.Warnf(msg)
return nil, errors.New(msg) return nil, errors.New(msg)
} }
err = txSimContext.Del(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash)) err = txSimContext.Del(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash))
if err != nil { if err != nil {
r.log.Errorf("certManage txSimContext.Del failed, certHash[%s] err: %s", certHash, err.Error()) r.log.Warnf("certManage txSimContext.Del failed, certHash[%s] err: %s", certHash, err.Error())
return nil, err return nil, err
} }
} }
...@@ -152,7 +149,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map ...@@ -152,7 +149,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map
if utils.IsAnyBlank(certHashesStr) { if utils.IsAnyBlank(certHashesStr) {
err := fmt.Errorf("%s, query cert require param [%s] not found", common.ErrParams.Error(), paramNameCertHashes) err := fmt.Errorf("%s, query cert require param [%s] not found", common.ErrParams.Error(), paramNameCertHashes)
r.log.Error(err) r.log.Warn(err)
return nil, err return nil, err
} }
...@@ -161,7 +158,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map ...@@ -161,7 +158,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map
for i, certHash := range certHashes { for i, certHash := range certHashes {
certBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash)) certBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(certHash))
if err != nil { if err != nil {
r.log.Errorf("certManage delete the certHash failed, certHash[%s] err: %s", certHash, err.Error()) r.log.Warnf("certManage delete the certHash failed, certHash[%s] err: %s", certHash, err.Error())
return nil, err return nil, err
} }
...@@ -175,7 +172,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map ...@@ -175,7 +172,7 @@ func (r *CertManageRuntime) Query(txSimContext protocol.TxSimContext, params map
c.CertInfos = certInfos c.CertInfos = certInfos
certBytes, err := proto.Marshal(c) certBytes, err := proto.Marshal(c)
if err != nil { if err != nil {
r.log.Errorf("certManage query proto.Marshal(c) err certHash[%s] err", certHashesStr, err) r.log.Warnf("certManage query proto.Marshal(c) err certHash[%s] err", certHashesStr, err)
return nil, err return nil, err
} }
...@@ -199,7 +196,7 @@ func (r *CertManageRuntime) Freeze(txSimContext protocol.TxSimContext, params ma ...@@ -199,7 +196,7 @@ func (r *CertManageRuntime) Freeze(txSimContext protocol.TxSimContext, params ma
if utils.IsAnyBlank(certsStr) { if utils.IsAnyBlank(certsStr) {
err = fmt.Errorf("%s, freeze cert require param [%s] not found", common.ErrParams.Error(), paramNameCerts) err = fmt.Errorf("%s, freeze cert require param [%s] not found", common.ErrParams.Error(), paramNameCerts)
r.log.Error(err) r.log.Warn(err)
return nil, err return nil, err
} }
...@@ -245,18 +242,18 @@ func (r *CertManageRuntime) Freeze(txSimContext protocol.TxSimContext, params ma ...@@ -245,18 +242,18 @@ func (r *CertManageRuntime) Freeze(txSimContext protocol.TxSimContext, params ma
} }
if !changed { if !changed {
r.log.Error(common.ErrParams) r.log.Warn(common.ErrParams)
return nil, common.ErrParams return nil, common.ErrParams
} }
marshal, err := json.Marshal(freezeKeyArray) marshal, err := json.Marshal(freezeKeyArray)
if err != nil { if err != nil {
r.log.Errorf("freezeKeyArray err: ", err.Error()) r.log.Warnf("freezeKeyArray err: ", err.Error())
return nil, err return nil, err
} }
err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertFreezeKey), marshal) err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertFreezeKey), marshal)
if err != nil { if err != nil {
r.log.Errorf("txSimContext put CERT_FREEZE_KEY err ", err.Error()) r.log.Warnf("txSimContext put CERT_FREEZE_KEY err ", err.Error())
return nil, err return nil, err
} }
...@@ -278,7 +275,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params ...@@ -278,7 +275,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params
} }
if len(freezeKeyArray) == 0 { if len(freezeKeyArray) == 0 {
r.log.Errorf("no cert need to unfreeze") r.log.Warnf("no cert need to unfreeze")
return nil, errors.New("no cert need to unfreeze") return nil, errors.New("no cert need to unfreeze")
} }
...@@ -290,7 +287,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params ...@@ -290,7 +287,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params
if utils.IsAllBlank(certsStr, certHashesStr) { if utils.IsAllBlank(certsStr, certHashesStr) {
err = fmt.Errorf("%s, unfreeze cert require param [%s or %s] not found", err = fmt.Errorf("%s, unfreeze cert require param [%s or %s] not found",
common.ErrParams.Error(), paramNameCerts, paramNameCertHashes) common.ErrParams.Error(), paramNameCerts, paramNameCertHashes)
r.log.Error(err) r.log.Warn(err)
return nil, err return nil, err
} }
...@@ -305,7 +302,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params ...@@ -305,7 +302,7 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params
} }
certHash, err1 := utils.GetCertificateIdHex([]byte(cert), hashType) certHash, err1 := utils.GetCertificateIdHex([]byte(cert), hashType)
if err1 != nil { if err1 != nil {
r.log.Errorf("GetCertificateIdHex failed, err: ", err1.Error()) r.log.Warnf("GetCertificateIdHex failed, err: ", err1.Error())
continue continue
} }
freezeKeyArray, changed = r.recoverFrozenCert(txSimContext, certHash, freezeKeyArray, certFullHashes, changed) freezeKeyArray, changed = r.recoverFrozenCert(txSimContext, certHash, freezeKeyArray, certFullHashes, changed)
...@@ -320,18 +317,18 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params ...@@ -320,18 +317,18 @@ func (r *CertManageRuntime) Unfreeze(txSimContext protocol.TxSimContext, params
} }
if !changed { if !changed {
r.log.Error(common.ErrParams) r.log.Warn(common.ErrParams)
return nil, common.ErrParams return nil, common.ErrParams
} }
marshal, err := json.Marshal(freezeKeyArray) marshal, err := json.Marshal(freezeKeyArray)
if err != nil { if err != nil {
r.log.Errorf("freezeKeyArray err: ", err.Error()) r.log.Warnf("freezeKeyArray err: ", err.Error())
return nil, err return nil, err
} }
err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertFreezeKey), marshal) err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertFreezeKey), marshal)
if err != nil { if err != nil {
r.log.Errorf("txSimContext put CERT_FREEZE_KEY err: ", err.Error()) r.log.Warnf("txSimContext put CERT_FREEZE_KEY err: ", err.Error())
return nil, err return nil, err
} }
...@@ -350,17 +347,17 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -350,17 +347,17 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
crlStr, ok := params[paramNameCertCrl] crlStr, ok := params[paramNameCertCrl]
if !ok { if !ok {
err := fmt.Errorf("certManage cert revocation params err,cert_cerl is empty") err := fmt.Errorf("certManage cert revocation params err,cert_cerl is empty")
r.log.Error(err.Error()) r.log.Warn(err.Error())
return nil, err return nil, err
} }
ac, err := txSimContext.GetAccessControl() ac, err := txSimContext.GetAccessControl()
if err != nil { if err != nil {
r.log.Errorf("certManage txSimContext.GetOrganization failed, err: ", err.Error()) r.log.Warnf("certManage txSimContext.GetOrganization failed, err: ", err.Error())
return nil, err return nil, err
} }
_, err = ac.VerifyRelatedMaterial(pbac.VerifyType_CRL, crlStr) _, err = ac.VerifyRelatedMaterial(pbac.VerifyType_CRL, crlStr)
if err != nil { if err != nil {
r.log.Errorf("certManage validate crl failed err: ", err.Error()) r.log.Warnf("certManage validate crl failed err: ", err.Error())
return nil, err return nil, err
} }
...@@ -370,16 +367,17 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -370,16 +367,17 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
for crlPEM != nil { for crlPEM != nil {
crl, err1 := x509.ParseCRL(crlPEM.Bytes) crl, err1 := x509.ParseCRL(crlPEM.Bytes)
if err1 != nil { if err1 != nil {
r.log.Errorf("certManage parse crl failed err: ", err1.Error()) r.log.Warnf("certManage parse crl failed err: ", err1.Error())
return nil, err1 return nil, err1
} }
crlPEM, rest = pem.Decode(rest) crlPEM, rest = pem.Decode(rest)
crls = append(crls, crl) crls = append(crls, crl)
} }
crlBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertRevokeKey)) crlBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertRevokeKey))
if err != nil { if err != nil {
r.log.Errorf("get certManage crlList fail err: ", err.Error()) r.log.Warnf("get certManage crlList fail err: ", err.Error())
return nil, fmt.Errorf("get certManage crlList failed, err: %s", err) return nil, fmt.Errorf("get certManage crlList failed, err: %s", err)
} }
...@@ -387,7 +385,7 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -387,7 +385,7 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
if len(crlBytes) > 0 { if len(crlBytes) > 0 {
err = json.Unmarshal(crlBytes, &crlKeyList) err = json.Unmarshal(crlBytes, &crlKeyList)
if err != nil { if err != nil {
r.log.Errorf("certManage unmarshal crl list err: ", err.Error()) r.log.Warnf("certManage unmarshal crl list err: ", err.Error())
return nil, errors.New("unmarshal crl list err") return nil, errors.New("unmarshal crl list err")
} }
} }
...@@ -396,14 +394,14 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -396,14 +394,14 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
for _, crtList := range crls { for _, crtList := range crls {
aki, err1 := getAKI(crtList) aki, err1 := getAKI(crtList)
if err1 != nil { if err1 != nil {
r.log.Errorf("certManage getAKI err: ", err1.Error()) r.log.Warnf("certManage getAKI err: ", err1.Error())
continue continue
} }
key := fmt.Sprintf("%s%s", protocol.CertRevokeKeyPrefix, hex.EncodeToString(aki)) key := fmt.Sprintf("%s%s", protocol.CertRevokeKeyPrefix, hex.EncodeToString(aki))
crtListBytes, err1 := asn1.Marshal(*crtList) crtListBytes, err1 := asn1.Marshal(*crtList)
if err1 != nil { if err1 != nil {
r.log.Errorf("certManage marshal crt list err: ", err1.Error()) r.log.Warnf("certManage marshal crt list err: ", err1.Error())
continue continue
} }
...@@ -427,7 +425,7 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -427,7 +425,7 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(key), toMemory) err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(key), toMemory)
if err != nil { if err != nil {
r.log.Errorf("certManage save crl certs err: ", err.Error()) r.log.Warnf("certManage save crl certs err: ", err.Error())
return nil, err return nil, err
} }
...@@ -441,18 +439,18 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma ...@@ -441,18 +439,18 @@ func (r *CertManageRuntime) Revoke(txSimContext protocol.TxSimContext, params ma
} }
if !changed { if !changed {
r.log.Error(common.ErrParams) r.log.Warn(common.ErrParams)
return nil, common.ErrParams return nil, common.ErrParams
} }
crlBytesResult, err := json.Marshal(crlKeyList) crlBytesResult, err := json.Marshal(crlKeyList)
if err != nil { if err != nil {
r.log.Errorf("certManage marshal crlKeyList err: ", err.Error()) r.log.Warnf("certManage marshal crlKeyList err: ", err.Error())
return nil, err return nil, err
} }
err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertRevokeKey), crlBytesResult) err = txSimContext.Put(syscontract.SystemContract_CERT_MANAGE.String(), []byte(protocol.CertRevokeKey), crlBytesResult)
if err != nil { if err != nil {
r.log.Errorf("certManage txSimContext put CertRevokeKey err: ", err.Error()) r.log.Warnf("certManage txSimContext put CertRevokeKey err: ", err.Error())
return nil, err return nil, err
} }
crlResultStr := strings.TrimRight(crlResult.String(), ",") crlResultStr := strings.TrimRight(crlResult.String(), ",")
...@@ -471,7 +469,7 @@ func getAKI(crl *pkix.CertificateList) (aki []byte, err error) { ...@@ -471,7 +469,7 @@ func getAKI(crl *pkix.CertificateList) (aki []byte, err error) {
func (r *CertManageRuntime) getFreezeKeyArray(txSimContext protocol.TxSimContext) (string, []string, error) { func (r *CertManageRuntime) getFreezeKeyArray(txSimContext protocol.TxSimContext) (string, []string, error) {
ac, err := txSimContext.GetAccessControl() ac, err := txSimContext.GetAccessControl()
if err != nil { if err != nil {
r.log.Errorf("txSimContext.GetAccessControl failed, err: ", err.Error()) r.log.Warnf("txSimContext.GetAccessControl failed, err: ", err.Error())
return "", nil, err return "", nil, err
} }
hashType := ac.GetHashAlg() hashType := ac.GetHashAlg()
...@@ -481,14 +479,14 @@ func (r *CertManageRuntime) getFreezeKeyArray(txSimContext protocol.TxSimContext ...@@ -481,14 +479,14 @@ func (r *CertManageRuntime) getFreezeKeyArray(txSimContext protocol.TxSimContext
freezeKeyArrayBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(), freezeKeyArrayBytes, err := txSimContext.Get(syscontract.SystemContract_CERT_MANAGE.String(),
[]byte(protocol.CertFreezeKey)) []byte(protocol.CertFreezeKey))
if err != nil { if err != nil {
r.log.Errorf("txSimContext get CERT_FREEZE_KEY err: ", err.Error()) r.log.Warnf("txSimContext get CERT_FREEZE_KEY err: ", err.Error())
return "", nil, err return "", nil, err
} }
if len(freezeKeyArrayBytes) > 0 { if len(freezeKeyArrayBytes) > 0 {
err := json.Unmarshal(freezeKeyArrayBytes, &freezeKeyArray) err := json.Unmarshal(freezeKeyArrayBytes, &freezeKeyArray)
if err != nil { if err != nil {
r.log.Errorf("unmarshal freeze key array err: ", err.Error()) r.log.Warnf("unmarshal freeze key array err: ", err.Error())
return "", nil, err return "", nil, err
} }
} }
...@@ -537,31 +535,11 @@ func (r *CertManageRuntime) checkCert(cert string, trustRoots []*configPb.TrustR ...@@ -537,31 +535,11 @@ func (r *CertManageRuntime) checkCert(cert string, trustRoots []*configPb.TrustR
return errors.New("can not freeze/unfreeze root certificate") return errors.New("can not freeze/unfreeze root certificate")
} }
// 判断是否是该ca签发的证书 caCerts := make([][]byte, 0)
caPool := bcx509.NewCertPool()
for _, root := range trustRoots { for _, root := range trustRoots {
for _, s := range root.Root { for _, certTmp := range root.Root {
pemBlock, rest := pem.Decode([]byte(s)) caCerts = append(caCerts, []byte(certTmp))
for pemBlock != nil {
cert, _ := bcx509.ParseCertificate(pemBlock.Bytes)
caPool.AddCert(cert)
pemBlock, rest = pem.Decode(rest)
}
} }
} }
certChain, err := c.Verify(bcx509.VerifyOptions{ return utils.VerifyCertIssue(caCerts, nil, []byte(cert))
Intermediates: caPool,
Roots: caPool,
CurrentTime: time.Time{},
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
MaxConstraintComparisions: 0,
})
if err != nil {
r.log.Warn(err)
return err
}
if len(certChain) > 0 && len(certChain[0]) > 0 {
return nil
}
return errors.New("the cert is not in trust root")
} }
/*
* Copyright (C) BABEC. All rights reserved.
* Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package certmgr
import (
"fmt"
"testing"
"chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
commonPb "chainmaker.org/chainmaker/pb-go/v2/common"
"chainmaker.org/chainmaker/protocol/v2/test"
"github.com/stretchr/testify/assert"
"chainmaker.org/chainmaker/protocol/v2/mock"
"github.com/golang/mock/gomock"
"chainmaker.org/chainmaker/protocol/v2"
)
var (
errCert = false
)
func Test_AddCert(t *testing.T) {
mgrRuntime, txSimContext, fn := initEnv(t)
defer fn()
result, err := mgrRuntime.Add(txSimContext, nil)
assert.Nil(t, err)
assert.Equal(t, "e77c9238c51e3446d942f94bd8803cc4f351254f8771f972146d7bfc6e0be7f4", string(result))
fmt.Printf("add cert success. cert hash: %s \n", result)
errCert = true
_, err = mgrRuntime.Add(txSimContext, nil)
assert.NotNil(t, err)
errCert = false
}
func Test_DeleteCert(t *testing.T) {
mgrRuntime, txSimContext, fn := initEnv(t)
defer fn()
result, err := mgrRuntime.Add(txSimContext, nil)
assert.Equal(t, "e77c9238c51e3446d942f94bd8803cc4f351254f8771f972146d7bfc6e0be7f4", string(result))
params := make(map[string][]byte)
params[paramNameCertHashes] = []byte("e77c9238c51e3446d942f94bd8803cc4f351254f8771f972146d7bfc6e0be7f4")
result, err = mgrRuntime.Delete(txSimContext, params)
assert.Nil(t, err)
result, err = mgrRuntime.Delete(txSimContext, params)
assert.NotNil(t, err)
_, err = mgrRuntime.Delete(txSimContext, nil)
assert.NotNil(t, err)
}
var _ protocol.TxSimContext = (*mock.MockTxSimContext)(nil)
func initEnv(t *testing.T) (*CertManageRuntime, *mock.MockTxSimContext, func()) {
certMgrRuntime := &CertManageRuntime{NewLogger()}
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
acTest := mock.NewMockAccessControlProvider(ctrl)
acTest.EXPECT().GetHashAlg().Return("SHA256").AnyTimes()
txSimContext.EXPECT().GetAccessControl().Return(acTest, nil).AnyTimes()
cache := NewCacheMock()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(name string, key []byte, value []byte) error {
cache.Put(name, string(key), value)
return nil
}).AnyTimes()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).DoAndReturn(
func(name string, key []byte) ([]byte, error) {
return cache.Get(name, string(key)), nil
}).AnyTimes()
txSimContext.EXPECT().Del(gomock.Any(), gomock.Any()).DoAndReturn(
func(name string, key []byte) error {
return cache.Del(name, string(key))
}).AnyTimes()
txSimContext.EXPECT().GetTx().DoAndReturn(
func() *commonPb.Transaction {
return &commonPb.Transaction{
Sender: &commonPb.EndorsementEntry{
Signer: getOrg1Client1Signer(),
},
}
}).AnyTimes()
return certMgrRuntime, txSimContext, func() { ctrl.Finish() }
}
func getOrg1Client1Signer() *accesscontrol.Member {
certStr := "-----BEGIN CERTIFICATE-----\nMIICijCCAi+gAwIBAgIDBS9vMAoGCCqGSM49BAMCMIGKMQswCQYDVQQGEwJDTjEQ\nMA4GA1UECBMHQmVpamluZzEQMA4GA1UEBxMHQmVpamluZzEfMB0GA1UEChMWd3gt\nb3JnMS5jaGFpbm1ha2VyLm9yZzESMBAGA1UECxMJcm9vdC1jZXJ0MSIwIAYDVQQD\nExljYS53eC1vcmcxLmNoYWlubWFrZXIub3JnMB4XDTIwMTIwODA2NTM0M1oXDTI1\nMTIwNzA2NTM0M1owgZExCzAJBgNVBAYTAkNOMRAwDgYDVQQIEwdCZWlqaW5nMRAw\nDgYDVQQHEwdCZWlqaW5nMR8wHQYDVQQKExZ3eC1vcmcxLmNoYWlubWFrZXIub3Jn\nMQ8wDQYDVQQLEwZjbGllbnQxLDAqBgNVBAMTI2NsaWVudDEuc2lnbi53eC1vcmcx\nLmNoYWlubWFrZXIub3JnMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE56xayRx0\n/a8KEXPxRfiSzYgJ/sE4tVeI/ZbjpiUX9m0TCJX7W/VHdm6WeJLOdCDuLLNvjGTy\nt8LLyqyubJI5AKN7MHkwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw\nKQYDVR0OBCIEIMjAiM2eMzlQ9HzV9ePW69rfUiRZVT2pDBOMqM4WVJSAMCsGA1Ud\nIwQkMCKAIDUkP3EcubfENS6TH3DFczH5dAnC2eD73+wcUF/bEIlnMAoGCCqGSM49\nBAMCA0kAMEYCIQCWUHL0xisjQoW+o6VV12pBXIRJgdeUeAu2EIjptSg2GAIhAIxK\nLXpHIBFxIkmWlxUaanCojPSZhzEbd+8LRrmhEO8n\n-----END CERTIFICATE-----"
if errCert {
certStr = "-----BEGIN CERTIFICATE-----\nMIICijCCAi+gAwIBAgIDBS9vMAoCqGSM49BAMCMIGKMQswCQYDVQQGEwJDTjEQ\nMA4GA1UECBMHQmVpamluZzEQMA4GA1UEmVpamluZzEfMB0GA1UEChMWd3gt\nb3JnMS5jaGFpbm1ha2VyLm9yZzESMBAGA1UECxMJcm9vdC1jZXJ0MSIwIAYDVQQD\nExljYS53eC1vcmcxLmNoYWlubWFrZXIub3JnMB4XDTIwMTIwODA2NTM0M1oXDTI1\nMTIwNzA2NTM0M1owgZExCzAJBgNVBAYTAkNOMRAwDgYDVQQIEwdCZWlqaW5nMRAw\nDgYDVQQHEwdCZWlqaW5nMR8wHQYDVQQKExZ3eC1vcmcxLmNoYWlubWFrZXIub3Jn\nMQ8wDQYDVQQLEwZjbGllbnQxLDAqBgNVBAMTI2NsaWVudDEuc2lnbi53eC1vcmcx\nLmNoYWlubWFrZXIub3JnMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE56xayRx0/a8KEXPxRfiSzYgJ/sE4tVeI/ZbjpiUX9m0TCJX7W/VHdm6WeJLOdCDuLLNvjGTy\nt8LLyqyubJI5AKN7MHkwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw\nKQYDVR0OBCIEIMjAiM2eMzlQ9HzV9ePW69rfUiRZVT2pDBOMqM4WVJSAMCsGA1Ud\nIwQkMCKAIDUkP3EcubfENS6TH3DFczH5dAnC2eD73+wcUF/bEIlnMAoGCCqGSM49\nBAMCA0kAMEYCIQCWUHisjQoW+o6VV12pBXIRJgdeUeAu2EIjptSg2GAIhAIxK\nLXpHIBFxIkmWlxUaanCojPSEbd+8LRrmhEO8n\n-----END CERTIFICATE-----"
}
return &accesscontrol.Member{
OrgId: "wx-org1.chainmaker.org",
MemberType: accesscontrol.MemberType_CERT,
MemberInfo: []byte(certStr),
}
}
func NewLogger() protocol.Logger {
cmLogger := &test.GoLogger{}
return cmLogger
}
const KeyFormat = "%s/%s"
func realKey(name, key string) string {
return fmt.Sprintf(KeyFormat, name, key)
}
type CacheMock struct {
content map[string][]byte
}
func NewCacheMock() *CacheMock {
return &CacheMock{
content: make(map[string][]byte, 64),
}
}
func (c *CacheMock) Put(name, key string, value []byte) {
c.content[realKey(name, key)] = value
}
func (c *CacheMock) Get(name, key string) []byte {
return c.content[realKey(name, key)]
}
func (c *CacheMock) Del(name, key string) error {
delete(c.content, realKey(name, key))
return nil
}
func (c *CacheMock) GetByKey(key string) []byte {
return c.content[key]
}
func (c *CacheMock) Keys() []string {
sc := make([]string, 0)
for k := range c.content {
sc = append(sc, k)
}
return sc
}
This diff is collapsed.
...@@ -10,14 +10,24 @@ package common ...@@ -10,14 +10,24 @@ package common
import "errors" import "errors"
var ( var (
ErrContractIdIsNil = errors.New("the contractId is empty") // ErrContractIdIsNil err msg
ErrContractIdIsNil = errors.New("the contractId is empty")
// ErrContractNotFound err msg
ErrContractNotFound = errors.New("the contractName is not exist") ErrContractNotFound = errors.New("the contractName is not exist")
// ErrTxTypeNotSupport err msg
ErrTxTypeNotSupport = errors.New("the txType does not support") ErrTxTypeNotSupport = errors.New("the txType does not support")
ErrMethodNotFound = errors.New("the method does not found") // ErrMethodNotFound err msg
ErrParamsEmpty = errors.New("the params is empty") ErrMethodNotFound = errors.New("the method does not found")
ErrContractName = errors.New("the contractName is error") // ErrParamsEmpty err msg
ErrOutOfRange = errors.New("out of range") ErrParamsEmpty = errors.New("the params is empty")
ErrParams = errors.New("params is error") // ErrContractName err msg
ErrSequence = errors.New("sequence is error") ErrContractName = errors.New("the contractName is error")
ErrUnmarshalFailed = errors.New("unmarshal is error") // ErrOutOfRange err msg
ErrOutOfRange = errors.New("out of range")
// ErrParams err msg
ErrParams = errors.New("params is error")
// ErrSequence err msg
ErrSequence = errors.New("sequence is error")
// ErrUnmarshalFailed err msg
ErrUnmarshalFailed = errors.New("unmarshal is error")
) )
package common
import "chainmaker.org/chainmaker/pb-go/v2/syscontract"
const DefaultGas = uint64(100000)
// contractName: [functionName:gas]
var gasTable = map[string]map[string]uint64{
syscontract.SystemContract_CHAIN_QUERY.String(): {"": DefaultGas}, //key: ""表示默认方法
syscontract.SystemContract_CONTRACT_MANAGE.String(): {
syscontract.ContractManageFunction_INIT_CONTRACT.String(): 1000000,
syscontract.ContractManageFunction_UPGRADE_CONTRACT.String(): 1000000,
"": DefaultGas,
},
}
func GetGas(contractName, method string, defaultGas uint64) uint64 {
methodGasMap, ok := gasTable[contractName]
if !ok { //找不到合约的Gas设置
return defaultGas
}
gas, ok2 := methodGasMap[method]
if !ok2 { //找不到匹配的,就找key为空的
contractGas, ok3 := methodGasMap[""]
if !ok3 {
return defaultGas
}
return contractGas
}
return gas
}
...@@ -7,9 +7,12 @@ ...@@ -7,9 +7,12 @@
package common package common
import "chainmaker.org/chainmaker/protocol/v2" import (
"chainmaker.org/chainmaker/pb-go/v2/common"
"chainmaker.org/chainmaker/protocol/v2"
)
type ContractFunc func(context protocol.TxSimContext, params map[string][]byte) ([]byte, error) type ContractFunc func(context protocol.TxSimContext, params map[string][]byte) *common.ContractResult
// Contract define native Contract interface // Contract define native Contract interface
type Contract interface { type Contract interface {
......
package common
import (
"encoding/json"
"chainmaker.org/chainmaker/pb-go/v2/common"
"chainmaker.org/chainmaker/protocol/v2"
)
func ResultSuccess(result []byte, gas uint64) *common.ContractResult {
return &common.ContractResult{
Code: 0,
Result: result,
Message: "OK",
GasUsed: gas,
ContractEvent: nil,
}
}
func ResultError(err error) *common.ContractResult {
return &common.ContractResult{
Code: 1,
Result: nil,
Message: err.Error(),
GasUsed: 0,
ContractEvent: nil,
}
}
func ResultBytesAndError(returnResult []byte, err error) *common.ContractResult {
if err != nil {
return &common.ContractResult{
Code: 1,
Result: returnResult,
Message: err.Error(),
GasUsed: 0,
ContractEvent: nil,
}
}
//if len(returnResult) == 0 {
// returnResult = []byte("ok")
//}
return &common.ContractResult{
Code: 0,
Result: returnResult,
Message: "OK",
GasUsed: 0,
ContractEvent: nil,
}
}
func ResultErrorWithGasUsed(err error, gas uint64) *common.ContractResult {
return &common.ContractResult{
Code: 1,
Result: nil,
Message: err.Error(),
GasUsed: 0,
ContractEvent: nil,
}
}
func ResultJson(obj interface{}) (*common.ContractResult, error) {
data, err := json.Marshal(obj)
if err != nil {
return nil, err
}
return &common.ContractResult{
Code: 0,
Result: data,
Message: "OK",
GasUsed: 0,
ContractEvent: nil,
}, nil
}
//WrapResultFunc 包装原有的返回[]byte的函数,改为返回ContractResult的函数
func WrapResultFunc(f func(txSimContext protocol.TxSimContext, parameters map[string][]byte) ([]byte, error)) func(
txSimContext protocol.TxSimContext, parameters map[string][]byte) *common.ContractResult {
f2 := func(txSimContext protocol.TxSimContext, parameters map[string][]byte) *common.ContractResult {
result, err := f(txSimContext, parameters)
return ResultBytesAndError(result, err)
}
return f2
}
This diff is collapsed.
...@@ -6,3 +6,267 @@ ...@@ -6,3 +6,267 @@
*/ */
package contractmgr package contractmgr
import (
"testing"
pbac "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
commonPb "chainmaker.org/chainmaker/pb-go/v2/common"
"chainmaker.org/chainmaker/pb-go/v2/store"
"chainmaker.org/chainmaker/pb-go/v2/syscontract"
"chainmaker.org/chainmaker/protocol/v2"
"chainmaker.org/chainmaker/protocol/v2/mock"
"chainmaker.org/chainmaker/protocol/v2/test"
"chainmaker.org/chainmaker/utils/v2"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
)
func TestContractManagerRuntime_InstallContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
acTest := mock.NewMockAccessControlProvider(ctrl)
acTest.EXPECT().GetHashAlg().Return("SHA256").AnyTimes()
acTest.EXPECT().NewMember(gomock.Any()).Return(&Mb{}, nil).AnyTimes()
txSimContext.EXPECT().GetAccessControl().Return(acTest, nil).AnyTimes()
txSimContext.EXPECT().GetBlockVersion().Return(uint32(220)).AnyTimes()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]byte{}, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),
gomock.Any()).Return(&commonPb.ContractResult{Code: 0}, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS)
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, gas, err := runtime.InstallContract(txSimContext, "testContractName", "v1", []byte("bytes"),
commonPb.RuntimeType_WASMER, map[string][]byte{})
assert.Nil(t, err)
t.Log(result)
t.Log(gas)
}
func TestContractManagerRuntime_UpgradeContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_NORMAL}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),
gomock.Any()).Return(&commonPb.ContractResult{Code: 0}, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS)
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, gas, err := runtime.UpgradeContract(txSimContext, "testContractName", "v1", []byte("bytes"),
commonPb.RuntimeType_WASMER, map[string][]byte{})
assert.NotNil(t, err) //version重复
result, gas, err = runtime.UpgradeContract(txSimContext, "testContractName", "v2", []byte("bytes"),
commonPb.RuntimeType_WASMER, map[string][]byte{})
t.Log(result)
t.Log(gas)
}
func TestContractManagerRuntime_FreezeContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_NORMAL}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, err := runtime.FreezeContract(txSimContext, "")
assert.NotNil(t, err)
t.Log(result)
result, err = runtime.FreezeContract(txSimContext, "testContractName")
assert.Nil(t, err)
assert.True(t, result.Status == commonPb.ContractStatus_FROZEN)
t.Log(result)
}
func TestContractManagerRuntime_FreezeContractFail(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, err := runtime.FreezeContract(txSimContext, "")
assert.NotNil(t, err)
t.Log(result)
result, err = runtime.FreezeContract(txSimContext, "testContractName")
assert.NotNil(t, err)
t.Log(result)
}
func TestContractManagerRuntime_UnfreezeContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, err := runtime.UnfreezeContract(txSimContext, "testContractName")
assert.Nil(t, err)
assert.True(t, result.Status == commonPb.ContractStatus_NORMAL)
t.Log(result)
}
func TestContractManagerRuntime_RevokeContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, err := runtime.RevokeContract(txSimContext, "testContractName")
assert.Nil(t, err)
assert.True(t, result.Status == commonPb.ContractStatus_REVOKED)
t.Log(result)
}
func TestContractManagerRuntime_GetContractInfo(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
c, err := runtime.GetContractInfo(txSimContext, "testContractName")
assert.Nil(t, err)
t.Log(c)
}
func TestContractManagerRuntime_GetAllContracts(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract1 := &commonPb.Contract{Name: "testContractName1", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
contract2 := &commonPb.Contract{Name: "testContractName2", Version: "v1", Status: commonPb.ContractStatus_NORMAL}
contract3 := &commonPb.Contract{Name: "testContractName3", Version: "v1", Status: commonPb.ContractStatus_FROZEN}
list := &ListIter{list: []*commonPb.Contract{contract1, contract2, contract3}}
txSimContext.EXPECT().Select(gomock.Any(), gomock.Any(), gomock.Any()).Return(list, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
clist, err := runtime.GetAllContracts(txSimContext)
assert.Nil(t, err)
t.Log(clist)
assert.EqualValues(t, 3, len(clist))
}
type ListIter struct {
list []*commonPb.Contract
idx int
}
func (i *ListIter) Next() bool {
i.idx++
return i.idx < len(i.list)+1
}
func (i *ListIter) Value() (*store.KV, error) {
c := i.list[i.idx-1]
cdata, _ := c.Marshal()
return &store.KV{
ContractName: "",
Key: utils.GetContractDbKey(c.Name),
Value: cdata,
}, nil
}
func (i *ListIter) Release() {
i.list = make([]*commonPb.Contract, 0)
i.idx = 0
}
func initParameters() map[string][]byte {
parameters := make(map[string][]byte)
parameters[syscontract.InitContract_CONTRACT_NAME.String()] = []byte("testContractName")
parameters[syscontract.InitContract_CONTRACT_VERSION.String()] = []byte("v1")
parameters[syscontract.InitContract_CONTRACT_BYTECODE.String()] = []byte("byte code!!!")
parameters[syscontract.InitContract_CONTRACT_RUNTIME_TYPE.String()] = []byte("WASMER")
return parameters
}
func TestContractManagerRuntime_InstallContract2(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
acTest := mock.NewMockAccessControlProvider(ctrl)
acTest.EXPECT().GetHashAlg().Return("SHA256").AnyTimes()
acTest.EXPECT().NewMember(gomock.Any()).Return(&Mb{}, nil).AnyTimes()
txSimContext.EXPECT().GetAccessControl().Return(acTest, nil).AnyTimes()
txSimContext.EXPECT().GetBlockVersion().Return(uint32(220)).AnyTimes()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]byte{}, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),
gomock.Any()).Return(&commonPb.ContractResult{Code: 0}, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS)
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result := runtime.installContract(txSimContext, initParameters())
t.Log(result)
assert.EqualValues(t, "OK", result.Message)
assert.EqualValues(t, 0, result.Code)
}
func TestContractManagerRuntime_UpgradeContract2(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "testContractName", Version: "v0", Status: commonPb.ContractStatus_NORMAL}
cdata, _ := contract.Marshal()
txSimContext.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cdata, nil).AnyTimes()
txSimContext.EXPECT().GetSender().Return(&pbac.Member{MemberInfo: []byte("user1")}).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),
gomock.Any()).Return(&commonPb.ContractResult{Code: 0}, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS)
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result := runtime.upgradeContract(txSimContext, initParameters())
assert.EqualValues(t, 0, result.Code)
}
type Mb struct {
}
func (m Mb) GetMemberId() string {
return "memberId"
}
func (m Mb) GetOrgId() string {
return "orgId"
}
func (m Mb) GetRole() protocol.Role {
return "role"
}
func (m Mb) GetUid() string {
return "uid"
}
func (m Mb) Verify(hashType string, msg []byte, sig []byte) error {
panic("implement me")
}
func (m Mb) GetMember() (*pbac.Member, error) {
panic("implement me")
}
func TestContractManagerRuntime_InitNewNativeContract(t *testing.T) {
ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl)
defer ctrl.Finish()
contract := &commonPb.Contract{Name: "CHAIN_CONFIG", Version: "v1", RuntimeType: commonPb.RuntimeType_NATIVE, Status: commonPb.ContractStatus_NORMAL}
list := &ListIter{list: []*commonPb.Contract{contract}}
txSimContext.EXPECT().Select(gomock.Any(), gomock.Any(), gomock.Any()).Return(list, nil).AnyTimes()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
runtime := &ContractManagerRuntime{log: &test.GoLogger{}}
result, err := runtime.InitNewNativeContract(txSimContext, initParameters())
assert.Nil(t, err)
t.Log(string(result))
assert.NotContains(t, string(result), "CHAIN_CONFIG")
}
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"chainmaker.org/chainmaker/vm-native/common" "chainmaker.org/chainmaker/vm-native/v2/common"
"chainmaker.org/chainmaker/utils/v2" "chainmaker.org/chainmaker/utils/v2"
...@@ -87,13 +87,20 @@ func registerPrivateComputeContractMethods(log protocol.Logger) map[string]commo ...@@ -87,13 +87,20 @@ func registerPrivateComputeContractMethods(log protocol.Logger) map[string]commo
}, },
} }
queryMethodMap[syscontract.CrossTransactionFunction_EXECUTE.String()] = crossTransactionRuntime.Execute queryMethodMap[syscontract.CrossTransactionFunction_EXECUTE.String()] = common.WrapResultFunc(
queryMethodMap[syscontract.CrossTransactionFunction_COMMIT.String()] = crossTransactionRuntime.Commit crossTransactionRuntime.Execute)
queryMethodMap[syscontract.CrossTransactionFunction_ROLLBACK.String()] = crossTransactionRuntime.Rollback queryMethodMap[syscontract.CrossTransactionFunction_COMMIT.String()] = common.WrapResultFunc(
queryMethodMap[syscontract.CrossTransactionFunction_READ_STATE.String()] = crossTransactionRuntime.ReadState crossTransactionRuntime.Commit)
queryMethodMap[syscontract.CrossTransactionFunction_SAVE_PROOF.String()] = crossTransactionRuntime.SaveProof queryMethodMap[syscontract.CrossTransactionFunction_ROLLBACK.String()] = common.WrapResultFunc(
queryMethodMap[syscontract.CrossTransactionFunction_READ_PROOF.String()] = crossTransactionRuntime.ReadProof crossTransactionRuntime.Rollback)
queryMethodMap[syscontract.CrossTransactionFunction_ARBITRATE.String()] = crossTransactionRuntime.Arbitrate queryMethodMap[syscontract.CrossTransactionFunction_READ_STATE.String()] = common.WrapResultFunc(
crossTransactionRuntime.ReadState)
queryMethodMap[syscontract.CrossTransactionFunction_SAVE_PROOF.String()] = common.WrapResultFunc(
crossTransactionRuntime.SaveProof)
queryMethodMap[syscontract.CrossTransactionFunction_READ_PROOF.String()] = common.WrapResultFunc(
crossTransactionRuntime.ReadProof)
queryMethodMap[syscontract.CrossTransactionFunction_ARBITRATE.String()] = common.WrapResultFunc(
crossTransactionRuntime.Arbitrate)
return queryMethodMap return queryMethodMap
} }
...@@ -567,7 +574,7 @@ func callBusinessContract(ctx protocol.TxSimContext, crossID, params []byte) (*c ...@@ -567,7 +574,7 @@ func callBusinessContract(ctx protocol.TxSimContext, crossID, params []byte) (*c
func callContract(ctx protocol.TxSimContext, contract *Contract) (*commonPb.ContractResult, error) { func callContract(ctx protocol.TxSimContext, contract *Contract) (*commonPb.ContractResult, error) {
c := &commonPb.Contract{Name: contract.Name} c := &commonPb.Contract{Name: contract.Name}
result, code := ctx.CallContract(c, contract.Method, nil, contract.Params, 0, commonPb.TxType_INVOKE_CONTRACT) result, _, code := ctx.CallContract(c, contract.Method, nil, contract.Params, 0, commonPb.TxType_INVOKE_CONTRACT)
if code != commonPb.TxStatusCode_SUCCESS { if code != commonPb.TxStatusCode_SUCCESS {
if result != nil { if result != nil {
......
...@@ -9,22 +9,19 @@ import ( ...@@ -9,22 +9,19 @@ import (
"fmt" "fmt"
"testing" "testing"
"chainmaker.org/chainmaker/common/v2/serialize"
"chainmaker.org/chainmaker/pb-go/v2/accesscontrol" "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
pbac "chainmaker.org/chainmaker/pb-go/v2/accesscontrol" pbac "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
configPb "chainmaker.org/chainmaker/pb-go/v2/config"
"github.com/gogo/protobuf/proto"
"chainmaker.org/chainmaker/logger/v2"
"chainmaker.org/chainmaker/common/v2/serialize"
commonPb "chainmaker.org/chainmaker/pb-go/v2/common" commonPb "chainmaker.org/chainmaker/pb-go/v2/common"
configPb "chainmaker.org/chainmaker/pb-go/v2/config"
"chainmaker.org/chainmaker/pb-go/v2/syscontract" "chainmaker.org/chainmaker/pb-go/v2/syscontract"
"chainmaker.org/chainmaker/protocol/v2"
"chainmaker.org/chainmaker/protocol/v2/mock" "chainmaker.org/chainmaker/protocol/v2/mock"
"chainmaker.org/chainmaker/protocol/v2/test"
"github.com/gogo/protobuf/proto"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/require"
) )
var ( var (
...@@ -34,7 +31,7 @@ var ( ...@@ -34,7 +31,7 @@ var (
StateKey: cacheKey("state"), StateKey: cacheKey("state"),
ProofPreKey: cacheKey("proof"), ProofPreKey: cacheKey("proof"),
} }
crossContract = NewCrossTransactionContract(logger.GetLogger("CrossTx")) crossContract = NewCrossTransactionContract(&test.GoLogger{})
gCache = NewCacheMock() gCache = NewCacheMock()
crossID = []byte(uuid.New().String()) crossID = []byte(uuid.New().String())
gProofKey = []byte("1233211234567") gProofKey = []byte("1233211234567")
...@@ -61,21 +58,20 @@ func Test_Execute(t *testing.T) { ...@@ -61,21 +58,20 @@ func Test_Execute(t *testing.T) {
}, },
).AnyTimes() ).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Eq("exec"), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn( txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Eq("exec"), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn(
func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, commonPb.TxStatusCode) { func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, protocol.ExecOrderTxType, commonPb.TxStatusCode) {
if contract.Name == contractName { if contract.Name == contractName {
return &commonPb.ContractResult{ return &commonPb.ContractResult{
Code: 0, Code: 0,
Result: []byte("hello world"), Result: []byte("hello world"),
}, commonPb.TxStatusCode_SUCCESS }, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS
} }
return nil, commonPb.TxStatusCode_CONTRACT_FAIL return nil, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_CONTRACT_FAIL
}, },
) )
exec := crossContract.GetMethod(syscontract.CrossTransactionFunction_EXECUTE.String()) exec := crossContract.GetMethod(syscontract.CrossTransactionFunction_EXECUTE.String())
params := genExecParams(crossID) params := genExecParams(crossID)
ret, err := exec(txSimContext, params) ret := exec(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func genExecParams(crossID []byte) map[string][]byte { func genExecParams(crossID []byte) map[string][]byte {
eParams := map[string][]byte{ eParams := map[string][]byte{
...@@ -116,9 +112,8 @@ func Test_Commit(t *testing.T) { ...@@ -116,9 +112,8 @@ func Test_Commit(t *testing.T) {
commit := crossContract.GetMethod(syscontract.CrossTransactionFunction_COMMIT.String()) commit := crossContract.GetMethod(syscontract.CrossTransactionFunction_COMMIT.String())
params := map[string][]byte{paramCrossID: crossID} params := map[string][]byte{paramCrossID: crossID}
ret, err := commit(txSimContext, params) ret := commit(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func Test_Rollback(t *testing.T) { func Test_Rollback(t *testing.T) {
...@@ -139,23 +134,22 @@ func Test_Rollback(t *testing.T) { ...@@ -139,23 +134,22 @@ func Test_Rollback(t *testing.T) {
).AnyTimes() ).AnyTimes()
//if state == syscontract.CrossTxState_ExecOK || state == syscontract.CrossTxState_RollbackFail { //if state == syscontract.CrossTxState_ExecOK || state == syscontract.CrossTxState_RollbackFail {
txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Eq("rollback"), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn( txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Eq("rollback"), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn(
func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, commonPb.TxStatusCode) { func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, protocol.ExecOrderTxType, commonPb.TxStatusCode) {
if contract.Name == contractName && method == rollbackMethod { if contract.Name == contractName && method == rollbackMethod {
return &commonPb.ContractResult{ return &commonPb.ContractResult{
Code: 0, Code: 0,
Result: []byte("hello world"), Result: []byte("hello world"),
}, commonPb.TxStatusCode_SUCCESS }, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS
} }
return nil, commonPb.TxStatusCode_CONTRACT_FAIL return nil, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_CONTRACT_FAIL
}, },
) )
//} //}
call := crossContract.GetMethod(syscontract.CrossTransactionFunction_ROLLBACK.String()) call := crossContract.GetMethod(syscontract.CrossTransactionFunction_ROLLBACK.String())
params := map[string][]byte{paramCrossID: crossID} params := map[string][]byte{paramCrossID: crossID}
ret, err := call(txSimContext, params) ret := call(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func Test_ReadState(t *testing.T) { func Test_ReadState(t *testing.T) {
...@@ -170,11 +164,8 @@ func Test_ReadState(t *testing.T) { ...@@ -170,11 +164,8 @@ func Test_ReadState(t *testing.T) {
call := crossContract.GetMethod(syscontract.CrossTransactionFunction_READ_STATE.String()) call := crossContract.GetMethod(syscontract.CrossTransactionFunction_READ_STATE.String())
params := map[string][]byte{paramCrossID: crossID} params := map[string][]byte{paramCrossID: crossID}
ret, err := call(txSimContext, params) ret := call(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
result := syscontract.CrossState{}
result.Unmarshal(ret)
t.Log(result)
} }
func Test_SaveProof(t *testing.T) { func Test_SaveProof(t *testing.T) {
...@@ -197,9 +188,8 @@ func Test_SaveProof(t *testing.T) { ...@@ -197,9 +188,8 @@ func Test_SaveProof(t *testing.T) {
call := crossContract.GetMethod(syscontract.CrossTransactionFunction_SAVE_PROOF.String()) call := crossContract.GetMethod(syscontract.CrossTransactionFunction_SAVE_PROOF.String())
params := map[string][]byte{paramCrossID: crossID, paramProofKey: proofKey, paramTxProof: []byte("中国奥运健儿加油")} params := map[string][]byte{paramCrossID: crossID, paramProofKey: proofKey, paramTxProof: []byte("中国奥运健儿加油")}
ret, err := call(txSimContext, params) ret := call(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func Test_ReadProof(t *testing.T) { func Test_ReadProof(t *testing.T) {
...@@ -215,9 +205,8 @@ func Test_ReadProof(t *testing.T) { ...@@ -215,9 +205,8 @@ func Test_ReadProof(t *testing.T) {
call := crossContract.GetMethod(syscontract.CrossTransactionFunction_READ_PROOF.String()) call := crossContract.GetMethod(syscontract.CrossTransactionFunction_READ_PROOF.String())
params := map[string][]byte{paramCrossID: crossID, paramProofKey: proofKey} params := map[string][]byte{paramCrossID: crossID, paramProofKey: proofKey}
ret, err := call(txSimContext, params) ret := call(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func Test_Arbitrate(t *testing.T) { func Test_Arbitrate(t *testing.T) {
...@@ -274,22 +263,21 @@ MmUZz2wJML7wFsZw+IZ1MH28g3IRc67NcHiV7TX97kqwcTrfD10aV8UZn/+8aDQ5 ...@@ -274,22 +263,21 @@ MmUZz2wJML7wFsZw+IZ1MH28g3IRc67NcHiV7TX97kqwcTrfD10aV8UZn/+8aDQ5
).AnyTimes() ).AnyTimes()
txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Not(nil), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn( txSimContext.EXPECT().CallContract(gomock.Not(nil), gomock.Not(nil), gomock.Nil(), gomock.Any(), gomock.Eq(uint64(0)), gomock.Eq(commonPb.TxType_INVOKE_CONTRACT)).DoAndReturn(
func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, commonPb.TxStatusCode) { func(contract *commonPb.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType commonPb.TxType) (*commonPb.ContractResult, protocol.ExecOrderTxType, commonPb.TxStatusCode) {
if contract.Name == "tx" { if contract.Name == "tx" {
return &commonPb.ContractResult{ return &commonPb.ContractResult{
Code: 0, Code: 0,
Result: []byte("hello world"), Result: []byte("hello world"),
}, commonPb.TxStatusCode_SUCCESS }, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_SUCCESS
} }
return nil, commonPb.TxStatusCode_CONTRACT_FAIL return nil, protocol.ExecOrderTxTypeNormal, commonPb.TxStatusCode_CONTRACT_FAIL
}, },
).AnyTimes() ).AnyTimes()
call := crossContract.GetMethod(syscontract.CrossTransactionFunction_ARBITRATE.String()) call := crossContract.GetMethod(syscontract.CrossTransactionFunction_ARBITRATE.String())
params := map[string][]byte{paramCrossID: crossID, paramArbitrateCmd: []byte(syscontract.CrossArbitrateCmd_ROLLBACK_CMD.String())} params := map[string][]byte{paramCrossID: crossID, paramArbitrateCmd: []byte(syscontract.CrossArbitrateCmd_ROLLBACK_CMD.String())}
ret, err := call(txSimContext, params) ret := call(txSimContext, params)
require.Nil(t, err) t.Logf("%#v", ret)
t.Log(string(ret))
} }
func realKey(name string, key []byte) string { func realKey(name string, key []byte) string {
......
...@@ -8,13 +8,14 @@ ...@@ -8,13 +8,14 @@
package dposmgr package dposmgr
import ( import (
"crypto/sha256"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"strings" "strings"
"chainmaker.org/chainmaker/vm-native/common" "chainmaker.org/chainmaker/common/v2/crypto"
"chainmaker.org/chainmaker/common/v2/crypto/hash"
"chainmaker.org/chainmaker/vm-native/v2/common"
"chainmaker.org/chainmaker/pb-go/v2/accesscontrol" "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
"chainmaker.org/chainmaker/pb-go/v2/syscontract" "chainmaker.org/chainmaker/pb-go/v2/syscontract"
...@@ -69,17 +70,18 @@ func registerDPoSERC20ContractMethods(log protocol.Logger) map[string]common.Con ...@@ -69,17 +70,18 @@ func registerDPoSERC20ContractMethods(log protocol.Logger) map[string]common.Con
methodMap := make(map[string]common.ContractFunc, 64) methodMap := make(map[string]common.ContractFunc, 64)
// [DPoS] // [DPoS]
dposRuntime := NewDPoSRuntime(log) dposRuntime := NewDPoSRuntime(log)
methodMap[syscontract.DPoSERC20Function_GET_BALANCEOF.String()] = dposRuntime.BalanceOf methodMap[syscontract.DPoSERC20Function_GET_BALANCEOF.String()] = common.WrapResultFunc(dposRuntime.BalanceOf)
methodMap[syscontract.DPoSERC20Function_TRANSFER.String()] = dposRuntime.Transfer methodMap[syscontract.DPoSERC20Function_TRANSFER.String()] = common.WrapResultFunc(dposRuntime.Transfer)
//methodMap[syscontract.DPoSERC20Function_TRANSFER_FROM.String()] = dposRuntime.TransferFrom //methodMap[syscontract.DPoSERC20Function_TRANSFER_FROM.String()] = common.WrapResultFunc( dposRuntime.TransferFrom)
//methodMap[syscontract.DPoSERC20Function_GET_ALLOWANCE.String()] = dposRuntime.Allowance //methodMap[syscontract.DPoSERC20Function_GET_ALLOWANCE.String()] = common.WrapResultFunc( dposRuntime.Allowance)
//methodMap[syscontract.DPoSERC20Function_APPROVE.String()] = dposRuntime.Approve //methodMap[syscontract.DPoSERC20Function_APPROVE.String()] = common.WrapResultFunc( dposRuntime.Approve)
methodMap[syscontract.DPoSERC20Function_MINT.String()] = dposRuntime.Mint methodMap[syscontract.DPoSERC20Function_MINT.String()] = common.WrapResultFunc(dposRuntime.Mint)
//methodMap[syscontract.DPoSERC20Function_BURN.String()] = dposRuntime.Burn //methodMap[syscontract.DPoSERC20Function_BURN.String()] = common.WrapResultFunc( dposRuntime.Burn)
//methodMap[syscontract.DPoSERC20Function_TRANSFER_OWNERSHIP.String()] = dposRuntime.TransferOwnership //methodMap[syscontract.DPoSERC20Function_TRANSFER_OWNERSHIP.String()] = common.WrapResultFunc(
methodMap[syscontract.DPoSERC20Function_GET_OWNER.String()] = dposRuntime.Owner //dposRuntime.TransferOwnership)
methodMap[syscontract.DPoSERC20Function_GET_DECIMALS.String()] = dposRuntime.Decimals methodMap[syscontract.DPoSERC20Function_GET_OWNER.String()] = common.WrapResultFunc(dposRuntime.Owner)
methodMap[syscontract.DPoSERC20Function_GET_TOTAL_SUPPLY.String()] = dposRuntime.Total methodMap[syscontract.DPoSERC20Function_GET_DECIMALS.String()] = common.WrapResultFunc(dposRuntime.Decimals)
methodMap[syscontract.DPoSERC20Function_GET_TOTAL_SUPPLY.String()] = common.WrapResultFunc(dposRuntime.Total)
return methodMap return methodMap
} }
...@@ -542,45 +544,72 @@ func setApproveValue(txSimContext protocol.TxSimContext, from, to string, val *u ...@@ -542,45 +544,72 @@ func setApproveValue(txSimContext protocol.TxSimContext, from, to string, val *u
func loadSenderAddress(txSimContext protocol.TxSimContext) (string, error) { func loadSenderAddress(txSimContext protocol.TxSimContext) (string, error) {
sender := txSimContext.GetSender() sender := txSimContext.GetSender()
if sender != nil { if sender == nil {
// 将sender转换为用户地址 return "", fmt.Errorf("can not find sender from tx, contract[%s]", dposErc20ContractName)
var member []byte }
if sender.MemberType == accesscontrol.MemberType_CERT { // 将sender转换为用户地址
// 长证书 var (
member = sender.MemberInfo err error
} else if sender.MemberType == accesscontrol.MemberType_CERT_HASH { pubkey []byte
// 短证书 )
memberInfoHex := hex.EncodeToString(sender.MemberInfo) switch sender.MemberType {
certInfo, err := getWholeCertInfo(txSimContext, memberInfoHex) case accesscontrol.MemberType_CERT:
if err != nil { // 长证书
return "", fmt.Errorf( if pubkey, err = getPubkeyFromCert(sender.MemberInfo); err != nil {
"can not load whole cert info , contract[%s] member[%s]", return "", err
dposErc20ContractName, memberInfoHex) }
} case accesscontrol.MemberType_CERT_HASH:
member = certInfo.Cert var certInfo *commonPb.CertInfo
} else { // 短证书
return "", errors.New("invalid member type") memberInfoHex := hex.EncodeToString(sender.MemberInfo)
certInfo, err = getWholeCertInfo(txSimContext, memberInfoHex)
if err != nil {
return "", fmt.Errorf(
"can not load whole cert info , contract[%s] member[%s], reason: %s",
dposErc20ContractName, memberInfoHex, err)
} }
return parseUserAddress(member) if pubkey, err = getPubkeyFromCert(certInfo.Cert); err != nil {
return "", err
}
case accesscontrol.MemberType_PUBLIC_KEY:
pubkey = sender.MemberInfo
default:
return "", fmt.Errorf("invalid member type: %s", sender.MemberType)
}
ac, err := txSimContext.GetAccessControl()
if err != nil {
return "", err
} }
return "", fmt.Errorf("can not find sender from tx, contract[%s]", dposErc20ContractName) return calUserAddr(pubkey, ac.GetHashAlg())
} }
// parseUserAddress // parseUserAddress
func parseUserAddress(member []byte) (string, error) { func getPubkeyFromCert(member []byte) ([]byte, error) {
certificate, err := utils.ParseCert(member) certificate, err := utils.ParseCert(member)
if err != nil { if err != nil {
msg := fmt.Errorf("parse cert failed, name[%s] err: %+v", dposErc20ContractName, err) return nil, fmt.Errorf("parse cert failed, name[%s] err: %+v", dposErc20ContractName, err)
return "", msg
} }
pubKeyBytes, err := certificate.PublicKey.Bytes() pubKeyBytes, err := certificate.PublicKey.Bytes()
if err != nil { if err != nil {
msg := fmt.Errorf("load public key from cert failed, name[%s] err: %+v", dposErc20ContractName, err) return nil, fmt.Errorf("load public key from cert failed, name[%s] err: %+v", dposErc20ContractName, err)
return "", msg }
return pubKeyBytes, nil
}
func calUserAddr(pubkey []byte, hashType string) (string, error) {
var (
err error
hashBz []byte
)
if hashType == crypto.CRYPTO_ALGO_SM3 || hashType == crypto.CRYPTO_ALGO_SHA256 {
if hashBz, err = hash.GetByStrType(hashType, pubkey); err != nil {
return "", err
}
} else {
return "", fmt.Errorf("not support hashAlgo: %s", hashType)
} }
// 转换为SHA-256 addr := base58.Encode(hashBz[:])
addressBytes := sha256.Sum256(pubKeyBytes) return addr, nil
return base58.Encode(addressBytes[:]), nil
} }
func getWholeCertInfo(txSimContext protocol.TxSimContext, certHash string) (*commonPb.CertInfo, error) { func getWholeCertInfo(txSimContext protocol.TxSimContext, certHash string) (*commonPb.CertInfo, error) {
......
...@@ -12,9 +12,9 @@ import ( ...@@ -12,9 +12,9 @@ import (
"testing" "testing"
"chainmaker.org/chainmaker/protocol/v2/mock" "chainmaker.org/chainmaker/protocol/v2/mock"
"chainmaker.org/chainmaker/protocol/v2/test"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"chainmaker.org/chainmaker/logger/v2"
acPb "chainmaker.org/chainmaker/pb-go/v2/accesscontrol" acPb "chainmaker.org/chainmaker/pb-go/v2/accesscontrol"
"chainmaker.org/chainmaker/protocol/v2" "chainmaker.org/chainmaker/protocol/v2"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
...@@ -180,7 +180,11 @@ func TestDPoSRuntime_TransferFrom(t *testing.T) { ...@@ -180,7 +180,11 @@ func TestDPoSRuntime_TransferFrom(t *testing.T) {
} }
func TestOwnerCert(t *testing.T) { func TestOwnerCert(t *testing.T) {
address, err := parseUserAddress(ownerCert()) pubkey, err := getPubkeyFromCert(ownerCert())
if err != nil {
fmt.Println(err)
}
address, err := calUserAddr(pubkey, "SHA256")
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
...@@ -193,6 +197,10 @@ func initEnv(t *testing.T) (*DPoSRuntime, protocol.TxSimContext, func()) { ...@@ -193,6 +197,10 @@ func initEnv(t *testing.T) (*DPoSRuntime, protocol.TxSimContext, func()) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl) txSimContext := mock.NewMockTxSimContext(ctrl)
acTest := mock.NewMockAccessControlProvider(ctrl)
acTest.EXPECT().GetHashAlg().Return("SHA256").AnyTimes()
txSimContext.EXPECT().GetAccessControl().Return(acTest, nil).AnyTimes()
cache := NewCacheMock() cache := NewCacheMock()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(name string, key []byte, value []byte) error { func(name string, key []byte, value []byte) error {
...@@ -226,8 +234,7 @@ func initEnv(t *testing.T) (*DPoSRuntime, protocol.TxSimContext, func()) { ...@@ -226,8 +234,7 @@ func initEnv(t *testing.T) (*DPoSRuntime, protocol.TxSimContext, func()) {
} }
func NewLogger() protocol.Logger { func NewLogger() protocol.Logger {
cmLogger := logger.GetLogger("DPoS") return &test.GoLogger{}
return cmLogger
} }
func ownerCert() []byte { func ownerCert() []byte {
......
This diff is collapsed.
...@@ -333,11 +333,37 @@ func TestSortCollections(t *testing.T) { ...@@ -333,11 +333,37 @@ func TestSortCollections(t *testing.T) {
require.Equal(t, c, Collections{"400000000000000", "50000000000", "3", "2", "1"}) require.Equal(t, c, Collections{"400000000000000", "50000000000", "3", "2", "1"})
} }
func TestEmptyBasicParams(t *testing.T) {
rt, ctx, fn := setUp(t)
defer fn()
// remove basic params
ctx.Del(syscontract.SystemContract_DPOS_STAKE.String(), []byte(KeyMinSelfDelegation))
ctx.Del(syscontract.SystemContract_DPOS_STAKE.String(), []byte(KeyCompletionUnbondingEpochNumber))
ctx.Del(syscontract.SystemContract_DPOS_STAKE.String(), []byte(KeyEpochValidatorNumber))
ctx.Del(syscontract.SystemContract_DPOS_STAKE.String(), []byte(KeyEpochBlockNumber))
// call api
var (
err error
)
_, err = rt.ReadMinSelfDelegation(ctx, nil)
require.Equal(t, err, fmt.Errorf(fmt.Sprintf(ErrorGetValueByKey, "KeyMinSelfDelegation")))
_, err = rt.ReadCompleteUnBoundingEpochNumber(ctx, nil)
require.Equal(t, err, fmt.Errorf(fmt.Sprintf(ErrorGetValueByKey, "KeyCompletionUnbondingEpochNumber")))
_, err = rt.ReadEpochValidatorNumber(ctx, nil)
require.Equal(t, err, fmt.Errorf(fmt.Sprintf(ErrorGetValueByKey, "KeyEpochValidatorNumber")))
_, err = rt.ReadEpochBlockNumber(ctx, nil)
require.Equal(t, err, fmt.Errorf(fmt.Sprintf(ErrorGetValueByKey, "KeyEpochBlockNumber")))
}
func setUp(t *testing.T) (*DPoSStakeRuntime, protocol.TxSimContext, func()) { func setUp(t *testing.T) (*DPoSStakeRuntime, protocol.TxSimContext, func()) {
dPoSStakeRuntime := NewDPoSStakeRuntime(NewLogger()) dPoSStakeRuntime := NewDPoSStakeRuntime(NewLogger())
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
txSimContext := mock.NewMockTxSimContext(ctrl) txSimContext := mock.NewMockTxSimContext(ctrl)
acTest := mock.NewMockAccessControlProvider(ctrl)
acTest.EXPECT().GetHashAlg().Return("SHA256").AnyTimes()
txSimContext.EXPECT().GetAccessControl().Return(acTest, nil).AnyTimes()
cache := NewCacheMock() cache := NewCacheMock()
txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( txSimContext.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(name string, key []byte, value []byte) error { func(name string, key []byte, value []byte) error {
......
module chainmaker.org/chainmaker/vm-native module chainmaker.org/chainmaker/vm-native/v2
go 1.15 go 1.15
require ( require (
chainmaker.org/chainmaker/chainconf/v2 v2.0.0-20210913144615-f27c44059848 chainmaker.org/chainmaker/chainconf/v2 v2.1.2-0.20220113072252-aecb4f7ffef0
chainmaker.org/chainmaker/common/v2 v2.0.1-0.20211013080046-91ad24ce4d14 chainmaker.org/chainmaker/common/v2 v2.1.2-0.20220118101118-f256fc9c55e6
chainmaker.org/chainmaker/localconf/v2 v2.0.0-20210913154622-9f9774ed7d1b chainmaker.org/chainmaker/localconf/v2 v2.1.1-0.20220112085516-908b8478be8f
chainmaker.org/chainmaker/logger/v2 v2.0.0-20210907134457-53647922a89d chainmaker.org/chainmaker/logger/v2 v2.1.1-0.20211214124250-621f11b35ab0
chainmaker.org/chainmaker/pb-go/v2 v2.0.1-0.20211011124513-b828aaef61ff chainmaker.org/chainmaker/pb-go/v2 v2.1.1-0.20220214071858-6aaf92e86f04
chainmaker.org/chainmaker/protocol/v2 v2.0.1-0.20210910112253-04256ae9c5ed chainmaker.org/chainmaker/protocol/v2 v2.1.2-0.20220113081648-bbf6c1946b59
chainmaker.org/chainmaker/utils/v2 v2.0.0-20210907033606-84c6c841cbdb chainmaker.org/chainmaker/utils/v2 v2.1.1-0.20220114120415-8e1af1e262a7
github.com/gogo/protobuf v1.3.2 github.com/gogo/protobuf v1.3.2
github.com/golang/mock v1.6.0 github.com/golang/mock v1.6.0
github.com/golang/protobuf v1.5.2 github.com/golang/protobuf v1.5.2
...@@ -17,5 +17,4 @@ require ( ...@@ -17,5 +17,4 @@ require (
github.com/mr-tron/base58 v1.2.0 github.com/mr-tron/base58 v1.2.0
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0 github.com/stretchr/testify v1.7.0
google.golang.org/protobuf v1.27.1 // indirect
) )
This diff is collapsed.
...@@ -10,7 +10,7 @@ package government ...@@ -10,7 +10,7 @@ package government
import ( import (
"fmt" "fmt"
"chainmaker.org/chainmaker/vm-native/common" "chainmaker.org/chainmaker/vm-native/v2/common"
"chainmaker.org/chainmaker/pb-go/v2/syscontract" "chainmaker.org/chainmaker/pb-go/v2/syscontract"
"chainmaker.org/chainmaker/protocol/v2" "chainmaker.org/chainmaker/protocol/v2"
...@@ -40,7 +40,9 @@ func registerGovernmentContractMethods(log protocol.Logger) map[string]common.Co ...@@ -40,7 +40,9 @@ func registerGovernmentContractMethods(log protocol.Logger) map[string]common.Co
methodMap := make(map[string]common.ContractFunc, 64) methodMap := make(map[string]common.ContractFunc, 64)
// cert manager // cert manager
governmentRuntime := &GovernmentRuntime{log: log} governmentRuntime := &GovernmentRuntime{log: log}
methodMap[syscontract.ChainQueryFunction_GET_GOVERNANCE_CONTRACT.String()] = governmentRuntime.GetGovernmentContract methodMap[syscontract.ChainQueryFunction_GET_GOVERNANCE_CONTRACT.String()] = common.WrapResultFunc(
governmentRuntime.GetGovernmentContract)
return methodMap return methodMap
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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