├── pkg ├── core │ ├── entity │ │ ├── base │ │ │ ├── resInterdace.go │ │ │ ├── reqInterface.go │ │ │ ├── res.go │ │ │ └── req.go │ │ ├── enum │ │ │ ├── caType.go │ │ │ └── algorithmType.go │ │ ├── msp │ │ │ ├── fiscoUser.go │ │ │ └── userData.go │ │ ├── req │ │ │ ├── fabric │ │ │ │ ├── event │ │ │ │ │ ├── queryReqData.go │ │ │ │ │ ├── removeReqData.go │ │ │ │ │ └── registerReqData.go │ │ │ │ ├── node │ │ │ │ │ ├── ledgerReqData.go │ │ │ │ │ ├── sdkTransReqData.go │ │ │ │ │ ├── txTransReqData.go │ │ │ │ │ ├── blockReqData.go │ │ │ │ │ └── transReqData.go │ │ │ │ └── user │ │ │ │ │ ├── enroll.go │ │ │ │ │ └── register.go │ │ │ ├── cita │ │ │ │ ├── event │ │ │ │ │ ├── query.go │ │ │ │ │ ├── remove.go │ │ │ │ │ └── register.go │ │ │ │ ├── node │ │ │ │ │ ├── txTransReqData.go │ │ │ │ │ ├── blockReqData.go │ │ │ │ │ ├── transReqDataBody.go │ │ │ │ │ └── transData.go │ │ │ │ └── user │ │ │ │ │ └── register.go │ │ │ ├── xuperchain │ │ │ │ ├── event │ │ │ │ │ ├── query.go │ │ │ │ │ ├── remove.go │ │ │ │ │ └── register.go │ │ │ │ ├── node │ │ │ │ │ ├── getTx.go │ │ │ │ │ ├── getBlock.go │ │ │ │ │ ├── upukCallContract.go │ │ │ │ │ └── callContract.go │ │ │ │ └── user │ │ │ │ │ └── registerUser.go │ │ │ ├── fiscobcos │ │ │ │ ├── event │ │ │ │ │ ├── query.go │ │ │ │ │ ├── remove.go │ │ │ │ │ └── register.go │ │ │ │ ├── node │ │ │ │ │ ├── ledgerReqData.go │ │ │ │ │ ├── txReqData.go │ │ │ │ │ ├── blockReqData.go │ │ │ │ │ ├── transReqDataBody.go │ │ │ │ │ └── transData.go │ │ │ │ └── user │ │ │ │ │ └── register.go │ │ │ └── appInfo.go │ │ └── res │ │ │ ├── xuperchain │ │ │ ├── event │ │ │ │ ├── remove.go │ │ │ │ ├── register.go │ │ │ │ └── query.go │ │ │ ├── node │ │ │ │ ├── callContract.go │ │ │ │ ├── upukCallContract.go │ │ │ │ ├── getTx.go │ │ │ │ ├── getBlock.go │ │ │ │ └── common.go │ │ │ └── user │ │ │ │ └── registerUser.go │ │ │ ├── cita │ │ │ ├── event │ │ │ │ ├── remove.go │ │ │ │ ├── query.go │ │ │ │ ├── register.go │ │ │ │ └── event.go │ │ │ ├── node │ │ │ │ ├── blockHeightResData.go │ │ │ │ ├── transactionResData.go │ │ │ │ ├── blockResData.go │ │ │ │ ├── blockTxResData.go │ │ │ │ └── blockTxReceiptResData.go │ │ │ └── user │ │ │ │ └── register.go │ │ │ ├── fiscobcos │ │ │ ├── event │ │ │ │ ├── remove.go │ │ │ │ ├── query.go │ │ │ │ ├── register.go │ │ │ │ └── event.go │ │ │ ├── node │ │ │ │ ├── blockHeightResData.go │ │ │ │ ├── blockTxResData.go │ │ │ │ ├── blockTxReceiptResData.go │ │ │ │ ├── blockResData.go │ │ │ │ └── transResData.go │ │ │ └── user │ │ │ │ └── register.go │ │ │ ├── fabric │ │ │ ├── user │ │ │ │ ├── enroll.go │ │ │ │ └── register.go │ │ │ ├── event │ │ │ │ ├── registerResData.go │ │ │ │ └── queryResData.go │ │ │ └── node │ │ │ │ ├── transData.go │ │ │ │ ├── ledgerResData.go │ │ │ │ ├── blockDataRes.go │ │ │ │ ├── tranResData.go │ │ │ │ ├── transactionResData.go │ │ │ │ └── blockResData.go │ │ │ └── appInfo.go │ ├── config │ │ ├── config_test.go │ │ ├── fileConfig_test.go │ │ ├── conf │ │ │ └── config.json │ │ ├── fileConfig.go │ │ ├── mockConfig.go │ │ ├── config.go │ │ └── pukConfig.go │ ├── trans │ │ ├── fabric │ │ │ ├── request.go │ │ │ ├── transactionHeader.go │ │ │ ├── block.go │ │ │ ├── utils │ │ │ │ ├── utils.go │ │ │ │ ├── txutils.go │ │ │ │ └── commonutils.go │ │ │ └── fab │ │ │ │ └── proposer.go │ │ ├── xuperchain │ │ │ ├── crypto │ │ │ │ └── client.go │ │ │ ├── account │ │ │ │ ├── account_ext_test.go │ │ │ │ └── account_ext.go │ │ │ ├── common │ │ │ │ └── common.go │ │ │ ├── pb │ │ │ │ └── chainedbft.proto │ │ │ └── trans.go │ │ ├── cita │ │ │ ├── pb │ │ │ │ └── blockchain.proto │ │ │ ├── trans.go │ │ │ └── txdata.go │ │ └── fiscobcos │ │ │ ├── trans.go │ │ │ └── txdata.go │ └── sign │ │ └── bsnCrypto.go ├── util │ └── keystore │ │ ├── keystore.go │ │ ├── userstore.go │ │ ├── filekeystore.go │ │ └── fileusercertstore.go ├── common │ ├── uuid │ │ └── uuid.go │ ├── errors │ │ └── error.go │ ├── cache │ │ ├── cache.go │ │ └── proc │ │ │ └── proc.go │ ├── http │ │ └── http.go │ └── file │ │ └── file.go └── client │ ├── xuperchain │ ├── xuperchain_user_test.go │ ├── xuperchainClient.go │ ├── xuperchain_event_test.go │ ├── xuperchain_user.go │ ├── xuperchain_event.go │ └── xuperchain_node.go │ ├── cita │ ├── citaClient_user_test.go │ ├── citaClient_event_test.go │ ├── citaClient.go │ ├── citaClient_event.go │ ├── citaClient_user.go │ └── citaClient_node.go │ ├── app │ ├── app_test.go │ └── app.go │ ├── fisco-bcos │ ├── fiscobcosClient_user_test.go │ ├── fiscobcosClient_event_test.go │ ├── fiscobcosClient.go │ ├── fiscobcosClient_event.go │ └── fiscobcosClient_user.go │ ├── fabric │ ├── fabricClient_user_test.go │ ├── fabricClient_event_test.go │ ├── fabricClient_event.go │ ├── node │ │ └── client.go │ ├── fabricClient.go │ ├── fabricClient_user.go │ ├── fabricClient_node_test.go │ └── fabricClient_node.go │ └── client.go ├── .gitignore ├── conf └── config.json └── go.mod /pkg/core/entity/base/resInterdace.go: -------------------------------------------------------------------------------- 1 | package base 2 | 3 | type ResInterface interface { 4 | GetMac() string 5 | GetEncryptionValue() string 6 | } 7 | -------------------------------------------------------------------------------- /pkg/core/entity/base/reqInterface.go: -------------------------------------------------------------------------------- 1 | package base 2 | 3 | type ReqInterface interface { 4 | SetMac(mac string) 5 | GetEncryptionValue() string 6 | } 7 | -------------------------------------------------------------------------------- /pkg/util/keystore/keystore.go: -------------------------------------------------------------------------------- 1 | package keystore 2 | 3 | type KeyStore interface { 4 | StoreKey(rawPem []byte, alias string) error 5 | 6 | LoadKey(alias string) ([]byte, error) 7 | } 8 | -------------------------------------------------------------------------------- /pkg/core/entity/enum/caType.go: -------------------------------------------------------------------------------- 1 | package enum 2 | 3 | type App_CaType int 4 | 5 | const ( 6 | AppCaType_Not App_CaType = 0 7 | 8 | AppCaType_Trust App_CaType = 1 9 | 10 | AppCaType_NoTrust App_CaType = 2 11 | ) 12 | -------------------------------------------------------------------------------- /pkg/common/uuid/uuid.go: -------------------------------------------------------------------------------- 1 | package uuid 2 | 3 | import ( 4 | "github.com/satori/go.uuid" 5 | "strings" 6 | ) 7 | 8 | func GetUUID() string { 9 | 10 | u1 := uuid.NewV4() 11 | return strings.Replace(u1.String(), "-", "", -1) 12 | 13 | } 14 | -------------------------------------------------------------------------------- /pkg/common/errors/error.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | func New(message string) error { 4 | return &BsnError{ 5 | msg: message, 6 | } 7 | } 8 | 9 | type BsnError struct { 10 | msg string 11 | } 12 | 13 | func (b *BsnError) Error() string { return b.msg } 14 | -------------------------------------------------------------------------------- /pkg/util/keystore/userstore.go: -------------------------------------------------------------------------------- 1 | package keystore 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/msp" 5 | ) 6 | 7 | type UserCertStore interface { 8 | Load(user *msp.UserData) error 9 | LoadAll(appCode string) []*msp.UserData 10 | Store(user *msp.UserData) error 11 | } 12 | -------------------------------------------------------------------------------- /pkg/core/config/config_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestConfigInit(t *testing.T) { 9 | 10 | config, err := NewMockFabricConfig() 11 | 12 | if err != nil { 13 | t.Fatal(err) 14 | } else { 15 | fmt.Println(*config) 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/msp/fiscoUser.go: -------------------------------------------------------------------------------- 1 | /** 2 | * @Author: Gao Chenxi 3 | * @Description: 4 | * @File: fiscoUser 5 | * @Version: 1.0.0 6 | * @Date: 2020/6/11 10:37 7 | */ 8 | 9 | package msp 10 | 11 | type FiscoBcosUser struct { 12 | UserId string 13 | UserPrivateKey interface{} 14 | UserAddress string 15 | } 16 | -------------------------------------------------------------------------------- /pkg/core/config/fileConfig_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestNewConfigFormFile(t *testing.T) { 9 | 10 | //path :="../../../conf/config.json" 11 | 12 | conf, err := NewConfigFormFile("") 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | 17 | fmt.Println(conf.user.UserCode) 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/event/queryReqData.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type QueryReqData struct { 6 | base.BaseReqModel 7 | Body interface{} `json:"body"` 8 | } 9 | 10 | func (f *QueryReqData) GetEncryptionValue() string { 11 | return f.GetBaseEncryptionValue() 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | 15 | # Dependency directories (remove the comment below to include it) 16 | # vendor/ 17 | 18 | .idea/ -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RemoveEventResData struct { 6 | base.BaseResModel 7 | Body interface{} `json:"body"` 8 | } 9 | 10 | func (f *RemoveEventResData) GetEncryptionValue() string { 11 | return f.GetBaseEncryptionValue() 12 | } 13 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RemoveEventResData struct { 6 | base.BaseResModel 7 | Body interface{} `json:"body"` 8 | } 9 | 10 | func (f *RemoveEventResData) GetEncryptionValue() string { 11 | 12 | return f.GetBaseEncryptionValue() 13 | 14 | } 15 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type QueryReqData struct { 8 | base.BaseReqModel 9 | Body interface{} `json:"body"` 10 | } 11 | 12 | func (f *QueryReqData) GetEncryptionValue() string { 13 | 14 | return f.GetBaseEncryptionValue() 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type QueryEventReqData struct { 8 | base.BaseReqModel 9 | Body interface{} `json:"body"` 10 | } 11 | 12 | func (f *QueryEventReqData) GetEncryptionValue() string { 13 | return f.GetBaseEncryptionValue() 14 | } 15 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RemoveEventResData struct { 6 | base.BaseResModel 7 | Body interface{} `json:"body"` 8 | } 9 | 10 | func (f *RemoveEventResData) GetEncryptionValue() string { 11 | 12 | return f.GetBaseEncryptionValue() 13 | 14 | } 15 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type QueryReqData struct { 8 | base.BaseReqModel 9 | Body interface{} `json:"body"` 10 | } 11 | 12 | func (f *QueryReqData) GetEncryptionValue() string { 13 | 14 | return f.GetBaseEncryptionValue() 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type QueryEventResData struct { 6 | base.BaseResModel 7 | Body EventList `json:"body"` 8 | } 9 | 10 | func (f *QueryEventResData) GetEncryptionValue() string { 11 | 12 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 13 | 14 | } 15 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type QueryEventResData struct { 6 | base.BaseResModel 7 | Body EventList `json:"body"` 8 | } 9 | 10 | func (f *QueryEventResData) GetEncryptionValue() string { 11 | 12 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 13 | 14 | } 15 | -------------------------------------------------------------------------------- /pkg/core/entity/req/appInfo.go: -------------------------------------------------------------------------------- 1 | package req 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type AppInfoReqData struct { 6 | base.BaseReqModel 7 | Body interface{} `json:"body,omitempty"` 8 | } 9 | 10 | type AppInfoReqDataBody struct { 11 | } 12 | 13 | func (f *AppInfoReqData) GetEncryptionValue() string { 14 | 15 | return f.GetBaseEncryptionValue() 16 | 17 | } 18 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/node/ledgerReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type LedgerReqData struct { 6 | base.BaseReqModel 7 | Body LedgerReqDataBody `json:"body"` 8 | } 9 | 10 | type LedgerReqDataBody struct { 11 | } 12 | 13 | func (f *LedgerReqData) GetEncryptionValue() string { 14 | 15 | return f.GetBaseEncryptionValue() 16 | 17 | } 18 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/node/ledgerReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type LedgerReqData struct { 8 | base.BaseReqModel 9 | Body LedgerReqDataBody `json:"body"` 10 | } 11 | 12 | type LedgerReqDataBody struct { 13 | } 14 | 15 | func (f *LedgerReqData) GetEncryptionValue() string { 16 | 17 | return f.GetBaseEncryptionValue() 18 | 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/node/txTransReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type TxTransReqData struct { 6 | base.BaseReqModel 7 | Body TxTransReqDataBody `json:"body"` 8 | } 9 | 10 | type TxTransReqDataBody struct { 11 | TxId string `json:"txHash"` 12 | } 13 | 14 | func (f *TxTransReqData) GetEncryptionValue() string { 15 | return f.GetBaseEncryptionValue() + f.Body.TxId 16 | } 17 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/node/txReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TxReqData struct { 8 | base.BaseReqModel 9 | Body TxReqDataBody `json:"body"` 10 | } 11 | type TxReqDataBody struct { 12 | TxHash string `json:"txHash"` 13 | } 14 | 15 | func (f *TxReqData) GetEncryptionValue() string { 16 | 17 | return f.GetBaseEncryptionValue() + f.Body.TxHash 18 | 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/event/removeReqData.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RemoveReqData struct { 6 | base.BaseReqModel 7 | Body RemoveReqDataBody `json:"body"` 8 | } 9 | 10 | type RemoveReqDataBody struct { 11 | EventId string `json:"eventId"` 12 | } 13 | 14 | func (f *RemoveReqData) GetEncryptionValue() string { 15 | return f.GetBaseEncryptionValue() + f.Body.EventId 16 | 17 | } 18 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterEventResData struct { 6 | base.BaseResModel 7 | Body RegisterEvent `json:"body"` 8 | } 9 | 10 | type RegisterEvent struct { 11 | EventId string `json:"eventId"` 12 | } 13 | 14 | func (f *RegisterEventResData) GetEncryptionValue() string { 15 | 16 | return f.GetBaseEncryptionValue() + f.Body.EventId 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RemoveReqData struct { 8 | base.BaseReqModel 9 | Body RemoveReqDataBody `json:"body"` 10 | } 11 | 12 | type RemoveReqDataBody struct { 13 | EventId string `json:"eventId"` 14 | } 15 | 16 | func (f *RemoveReqData) GetEncryptionValue() string { 17 | 18 | return f.GetBaseEncryptionValue() + f.Body.EventId 19 | 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterEventResData struct { 6 | base.BaseResModel 7 | Body RegisterEvent `json:"body"` 8 | } 9 | 10 | type RegisterEvent struct { 11 | EventId string `json:"eventId"` 12 | } 13 | 14 | func (f *RegisterEventResData) GetEncryptionValue() string { 15 | 16 | return f.GetBaseEncryptionValue() + f.Body.EventId 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterReqData struct { 8 | base.BaseReqModel 9 | Body RegisterReqDataBody `json:"body"` 10 | } 11 | 12 | type RegisterReqDataBody struct { 13 | UserId string `json:"userId"` 14 | } 15 | 16 | func (f *RegisterReqData) GetEncryptionValue() string { 17 | 18 | return f.GetBaseEncryptionValue() + f.Body.UserId 19 | 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RemoveReqData struct { 8 | base.BaseReqModel 9 | Body RemoveReqDataBody `json:"body"` 10 | } 11 | 12 | type RemoveReqDataBody struct { 13 | EventId string `json:"eventId"` 14 | } 15 | 16 | func (f *RemoveReqData) GetEncryptionValue() string { 17 | 18 | return f.GetBaseEncryptionValue() + f.Body.EventId 19 | 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/node/sdkTransReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type SdkTransReqData struct { 6 | base.BaseReqModel 7 | Body SdkTransReqDataBody `json:"body"` 8 | } 9 | 10 | type SdkTransReqDataBody struct { 11 | TransData string `json:"transData"` 12 | } 13 | 14 | func (f *SdkTransReqData) GetEncryptionValue() string { 15 | 16 | return f.GetBaseEncryptionValue() + f.Body.TransData 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterReqData struct { 8 | base.BaseReqModel 9 | Body RegisterReqDataBody `json:"body"` 10 | } 11 | 12 | type RegisterReqDataBody struct { 13 | UserId string `json:"userId"` 14 | } 15 | 16 | func (f *RegisterReqData) GetEncryptionValue() string { 17 | 18 | return f.GetBaseEncryptionValue() + f.Body.UserId 19 | 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/node/blockHeightResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type BlockHeightResData struct { 6 | base.BaseResModel 7 | Body BlockHeightResDataBody `json:"body"` 8 | } 9 | 10 | type BlockHeightResDataBody struct { 11 | Data string `json:"data"` 12 | } 13 | 14 | func (f *BlockHeightResData) GetEncryptionValue() string { 15 | 16 | return f.GetBaseEncryptionValue() + f.Body.Data 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterEventResData struct { 6 | base.BaseResModel 7 | Body RegisterEventResDataBody `json:"body"` 8 | } 9 | 10 | type RegisterEventResDataBody struct { 11 | EventId string `json:"eventId"` 12 | } 13 | 14 | func (f *RegisterEventResData) GetEncryptionValue() string { 15 | return f.GetBaseEncryptionValue() + f.Body.EventId 16 | } 17 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/event/remove.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RemoveEventReqData struct { 8 | base.BaseReqModel 9 | Body RemoveEventReqDataBody `json:"body"` 10 | } 11 | 12 | type RemoveEventReqDataBody struct { 13 | EventId string `json:"eventId"` 14 | } 15 | 16 | func (f *RemoveEventReqData) GetEncryptionValue() string { 17 | return f.GetBaseEncryptionValue() + f.Body.EventId 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/node/getTx.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type GetTxInfoReqData struct { 8 | base.BaseReqModel 9 | Body GetTxInfoReqDataBody `json:"body"` // 消息体 10 | } 11 | 12 | type GetTxInfoReqDataBody struct { 13 | TxHash string `json:"txHash"` 14 | } 15 | 16 | func (m *GetTxInfoReqData) GetEncryptionValue() string { 17 | 18 | return m.GetBaseEncryptionValue() + m.Body.TxHash 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/node/blockHeightResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type BlockHeightResData struct { 6 | base.BaseResModel 7 | Body BlockHeightResDataBody `json:"body"` 8 | } 9 | 10 | type BlockHeightResDataBody struct { 11 | Data string `json:"data"` 12 | } 13 | 14 | func (f *BlockHeightResData) GetEncryptionValue() string { 15 | 16 | return f.GetBaseEncryptionValue() + f.Body.Data 17 | 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/user/registerUser.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterUserReqData struct { 8 | base.BaseReqModel 9 | Body RegisterUserReqDataBody `json:"body"` // 消息体 10 | } 11 | 12 | type RegisterUserReqDataBody struct { 13 | UserId string `json:"userId"` 14 | } 15 | 16 | func (m *RegisterUserReqData) GetEncryptionValue() string { 17 | 18 | return m.GetBaseEncryptionValue() + m.Body.UserId 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/user/enroll.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type EnrollResData struct { 6 | base.BaseResModel 7 | Body *EnrollResDataBody `json:"body"` 8 | } 9 | 10 | type EnrollResDataBody struct { 11 | Cert string `json:"cert"` 12 | } 13 | 14 | func (f *EnrollResData) GetEncryptionValue() string { 15 | if f.Body == nil { 16 | return f.GetBaseEncryptionValue() 17 | } 18 | 19 | return f.GetBaseEncryptionValue() + f.Body.Cert 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterResData struct { 6 | base.BaseResModel 7 | Body RegisterResDataBody `json:"body"` 8 | } 9 | 10 | type RegisterResDataBody struct { 11 | UserId string `json:"userId"` 12 | UserAddress string `json:"userAddress"` 13 | } 14 | 15 | func (f *RegisterResData) GetEncryptionValue() string { 16 | 17 | return f.GetBaseEncryptionValue() + f.Body.UserId + f.Body.UserAddress 18 | } 19 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchain_user_test.go: -------------------------------------------------------------------------------- 1 | package xuperchain 2 | 3 | import ( 4 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/xuperchain/user" 5 | "testing" 6 | ) 7 | 8 | func TestXuperChainClient_RegisterUser(t *testing.T) { 9 | client := getXuperChainClient(t) 10 | body := req.RegisterUserReqDataBody{ 11 | UserId: "zxl072201708", 12 | } 13 | res, err := client.RegisterUser(body) 14 | if err != nil { 15 | t.Fatal(err) 16 | } 17 | if res.Header.Code != 0 { 18 | t.Fatal(res.Header.Msg) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/node/blockReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type BlockReqData struct { 8 | base.BaseReqModel 9 | Body BlockReqDataBody `json:"body"` 10 | } 11 | type BlockReqDataBody struct { 12 | BlockNumber string `json:"blockNumber"` 13 | BlockHash string `json:"blockHash"` 14 | } 15 | 16 | func (f *BlockReqData) GetEncryptionValue() string { 17 | return f.GetBaseEncryptionValue() + f.Body.BlockNumber + f.Body.BlockHash 18 | 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterResData struct { 6 | base.BaseResModel 7 | Body RegisterResDataBody `json:"body"` 8 | } 9 | 10 | type RegisterResDataBody struct { 11 | UserId string `json:"userId"` 12 | UserAddress string `json:"userAddress"` 13 | } 14 | 15 | func (f *RegisterResData) GetEncryptionValue() string { 16 | 17 | return f.GetBaseEncryptionValue() + f.Body.UserId + f.Body.UserAddress 18 | } 19 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/node/blockReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type BlockReqData struct { 8 | base.BaseReqModel 9 | Body BlockReqDataBody `json:"body"` 10 | } 11 | type BlockReqDataBody struct { 12 | BlockNumber string `json:"blockNumber"` 13 | BlockHash string `json:"blockHash"` 14 | } 15 | 16 | func (f *BlockReqData) GetEncryptionValue() string { 17 | return f.GetBaseEncryptionValue() + f.Body.BlockNumber + f.Body.BlockHash 18 | 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/event/registerResData.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterResData struct { 6 | base.BaseResModel 7 | Body *RegisterResDataBody `json:"body"` 8 | } 9 | 10 | type RegisterResDataBody struct { 11 | EventId string `json:"eventId"` 12 | } 13 | 14 | func (f *RegisterResData) GetEncryptionValue() string { 15 | if f.Body == nil { 16 | return f.GetBaseEncryptionValue() 17 | } 18 | return f.GetBaseEncryptionValue() + f.Body.EventId 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/node/txTransReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type TxTransReqData struct { 6 | base.BaseReqModel 7 | Body TxTransReqDataBody `json:"body"` 8 | } 9 | 10 | type TxTransReqDataBody struct { 11 | TxId string `json:"txId"` 12 | 13 | // DataType Options as json 14 | DataType string `json:"dataType,omitempty"` 15 | } 16 | 17 | func (f *TxTransReqData) GetEncryptionValue() string { 18 | return f.GetBaseEncryptionValue() + f.Body.TxId + f.Body.DataType 19 | } 20 | -------------------------------------------------------------------------------- /pkg/client/cita/citaClient_user_test.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/cita/user" 8 | ) 9 | 10 | func TestCitaClient_RegisterUser(t *testing.T) { 11 | 12 | citaClient := getCitaClient(t) 13 | 14 | body := req.RegisterReqDataBody{ 15 | UserId: "testcurel", 16 | } 17 | 18 | res, err := citaClient.RegisterUser(body) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | 23 | fmt.Println(res) 24 | fmt.Println(citaClient.Verify(res.Mac, res.GetEncryptionValue())) 25 | } 26 | -------------------------------------------------------------------------------- /conf/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "nodeApi": "http://192.168.1.60:17502", 3 | "userCode": "user0001", 4 | "appCode": "app001", 5 | "userPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgdEteON4eEPho9GVeDmi9\nPlw7HzI7EGUB2FmbLtbgbPChRANCAAQ1UfhbyOfasIlSgf15buSil1pGhDb9Fpuy\nT3bmAVdTJFpIMBCT0iHldH9+7em4X2iX7tatVPcv4kq3BDkRLqJ4\n-----END PRIVATE KEY-----", 6 | "bsnPublicKey": "-----BEGIN PUBLIC KEY-----\n\tMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEDW9srwJ97PuwNTXKpCBLz+Kgp8Bo\n\tKS/i2zlbzA3gnrZPKjh8jfh++exUmliaJ1qlzeNeXHyEbV31Rqk4+Go3Tw==\n\t-----END PUBLIC KEY-----", 7 | "mspPath":"./msp" 8 | } -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/node/getBlock.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type GetBlockInfoReqData struct { 9 | base.BaseReqModel 10 | Body GetBlockInfoReqDataBody `json:"body"` // 消息体 11 | } 12 | 13 | type GetBlockInfoReqDataBody struct { 14 | BlockHeight int64 `json:"blockHeight"` 15 | BlockHash string `json:"blockHash"` 16 | } 17 | 18 | func (m *GetBlockInfoReqData) GetEncryptionValue() string { 19 | 20 | return m.GetBaseEncryptionValue() + strconv.FormatInt(m.Body.BlockHeight, 10) + m.Body.BlockHash 21 | } 22 | -------------------------------------------------------------------------------- /pkg/core/config/conf/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "nodeApi": "http://192.168.1.60:17502", 3 | "userCode": "user0001", 4 | "appCode": "app001", 5 | "userPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgdEteON4eEPho9GVeDmi9\nPlw7HzI7EGUB2FmbLtbgbPChRANCAAQ1UfhbyOfasIlSgf15buSil1pGhDb9Fpuy\nT3bmAVdTJFpIMBCT0iHldH9+7em4X2iX7tatVPcv4kq3BDkRLqJ4\n-----END PRIVATE KEY-----", 6 | "bsnPublicKey": "-----BEGIN PUBLIC KEY-----\n\tMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEDW9srwJ97PuwNTXKpCBLz+Kgp8Bo\n\tKS/i2zlbzA3gnrZPKjh8jfh++exUmliaJ1qlzeNeXHyEbV31Rqk4+Go3Tw==\n\t-----END PUBLIC KEY-----", 7 | "mspPath":"./msp" 8 | } -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/user/enroll.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type EnrollReqData struct { 6 | base.BaseReqModel 7 | Body EnrollReqDataBody `json:"body"` 8 | } 9 | 10 | type EnrollReqDataBody struct { 11 | Name string `json:"name"` 12 | Secret string `json:"secret"` 13 | CsrPem string `json:"csrPem"` 14 | } 15 | 16 | func (f *EnrollReqData) GetEncryptionValue() string { 17 | 18 | fp := f.GetBaseEncryptionValue() 19 | 20 | fp = fp + f.Body.Name 21 | fp = fp + f.Body.Secret 22 | fp = fp + f.Body.CsrPem 23 | 24 | return fp 25 | 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/request.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/fabric/fab" 5 | ) 6 | 7 | type TransRequest struct { 8 | ChannelId string 9 | ChaincodeId string 10 | Fcn string 11 | Args [][]byte 12 | TransientMap map[string][]byte 13 | } 14 | 15 | func (t *TransRequest) GetRequest() *fab.ChaincodeInvokeRequest { 16 | 17 | request := &fab.ChaincodeInvokeRequest{ 18 | ChaincodeID: t.ChaincodeId, 19 | TransientMap: t.TransientMap, 20 | Fcn: t.Fcn, 21 | Args: t.Args, 22 | } 23 | 24 | return request 25 | 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/crypto/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019. Baidu Inc. All Rights Reserved. 2 | 3 | // package common is related to generate crypto client 4 | package crypto 5 | 6 | import ( 7 | "github.com/xuperchain/crypto/client/service/gm" 8 | "github.com/xuperchain/crypto/client/service/xchain" 9 | ) 10 | 11 | // GetXchainCryptoClient get xchain crypto client 12 | func GetXchainCryptoClient() *xchain.XchainCryptoClient { 13 | return &xchain.XchainCryptoClient{} 14 | } 15 | 16 | // GetGmCryptoClient get gm crypto client 17 | func GetGmCryptoClient() *gm.GmCryptoClient { 18 | return &gm.GmCryptoClient{} 19 | } 20 | -------------------------------------------------------------------------------- /pkg/core/entity/enum/algorithmType.go: -------------------------------------------------------------------------------- 1 | package enum 2 | 3 | import "github.com/BSNDA/bsn-sdk-crypto/types" 4 | 5 | type App_AlgorithmType int 6 | 7 | func (a App_AlgorithmType) ToKeyType() types.KeyType { 8 | 9 | if a == AppAlgorithmType_SM2 { 10 | return types.SM 11 | } else if a == AppAlgorithmType_K1 { 12 | return types.ECDSA_K1 13 | } else { 14 | return types.ECDSA_R1 15 | } 16 | 17 | } 18 | 19 | const ( 20 | AppAlgorithmType_Not App_AlgorithmType = 0 21 | 22 | AppAlgorithmType_SM2 App_AlgorithmType = 1 23 | AppAlgorithmType_R1 App_AlgorithmType = 2 24 | AppAlgorithmType_K1 App_AlgorithmType = 3 25 | ) 26 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/transData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TranDataRes struct { 8 | base.BaseResModel 9 | Body *TranDataResBody `json:"body"` 10 | } 11 | 12 | type TranDataResBody struct { 13 | TxId string `json:"txId"` 14 | TransData string `json:"transData"` 15 | } 16 | 17 | func (f *TranDataRes) GetEncryptionValue() string { 18 | if f.Body == nil { 19 | return f.GetBaseEncryptionValue() 20 | } 21 | 22 | fp := f.GetBaseEncryptionValue() 23 | fp = fp + f.Body.TxId 24 | fp = fp + f.Body.TransData 25 | return fp 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterResData struct { 6 | base.BaseResModel 7 | Body *RegisterResDataBody `json:"body"` 8 | } 9 | 10 | type RegisterResDataBody struct { 11 | Name string `json:"name"` //Less than 20 bits 12 | Secret string `json:"secret"` 13 | } 14 | 15 | func (f *RegisterResData) GetEncryptionValue() string { 16 | 17 | if f.Body == nil { 18 | return f.GetBaseEncryptionValue() 19 | } 20 | 21 | fp := f.GetBaseEncryptionValue() 22 | 23 | fp = fp + f.Body.Name 24 | fp = fp + f.Body.Secret 25 | return fp 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/node/callContract.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type CallContractResData struct { 8 | base.BaseResModel 9 | Body *CallContractResDataBody `json:"body"` 10 | } 11 | 12 | type CallContractResDataBody struct { 13 | TxId string `json:"txId"` 14 | QueryInfo string `json:"queryInfo"` 15 | } 16 | 17 | func (f *CallContractResData) GetEncryptionValue() string { 18 | if f.Body == nil { 19 | return f.GetBaseEncryptionValue() 20 | } 21 | fp := f.GetBaseEncryptionValue() 22 | 23 | fp = fp + f.Body.TxId + f.Body.QueryInfo 24 | return fp 25 | } 26 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/user/registerUser.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterUserResData struct { 8 | base.BaseResModel 9 | Body *RegisterUserResDataBody `json:"body"` // 消息体 10 | } 11 | 12 | type RegisterUserResDataBody struct { 13 | UserId string `json:"userId"` 14 | UserAddr string `json:"userAddr"` 15 | } 16 | 17 | func (f *RegisterUserResData) GetEncryptionValue() string { 18 | if f.Body == nil { 19 | return f.GetBaseEncryptionValue() 20 | } 21 | fp := f.GetBaseEncryptionValue() 22 | 23 | fp = fp + f.Body.UserId + f.Body.UserAddr 24 | return fp 25 | } 26 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/node/upukCallContract.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type UPukCallContractReqData struct { 9 | base.BaseReqModel 10 | Body UPukCallContractReqDataReqDataBody `json:"body"` // 消息体 11 | } 12 | 13 | type UPukCallContractReqDataReqDataBody struct { 14 | Initiator string `json:"initiator"` 15 | TransData string `json:"transData"` 16 | Flag int `json:"flag"` // 0:预执行 1:执行 17 | } 18 | 19 | func (m *UPukCallContractReqData) GetEncryptionValue() string { 20 | return m.GetBaseEncryptionValue() + m.Body.Initiator + m.Body.TransData + strconv.Itoa(m.Body.Flag) 21 | } 22 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/user/register.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterReqData struct { 8 | base.BaseReqModel 9 | Body RegisterReqDataBody `json:"body"` 10 | } 11 | 12 | type RegisterReqDataBody struct { 13 | Name string `json:"name"` 14 | Secret string `json:"secret"` 15 | ExtendProperties string `json:"extendProperties"` //拓展属性 16 | } 17 | 18 | func (f *RegisterReqData) GetEncryptionValue() string { 19 | fp := f.GetBaseEncryptionValue() 20 | 21 | fp = fp + f.Body.Name 22 | fp = fp + f.Body.Secret 23 | fp = fp + f.Body.ExtendProperties 24 | 25 | return fp 26 | 27 | } 28 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/node/transReqDataBody.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TransReqData struct { 8 | base.BaseReqModel 9 | Body TransReqDataBody `json:"body"` 10 | } 11 | 12 | type TransReqDataBody struct { 13 | UserId string `json:"userId"` 14 | ContractName string `json:"contractName"` 15 | FuncName string `json:"funcName"` 16 | FuncParam string `json:"funcParam"` 17 | } 18 | 19 | func (f *TransReqData) GetEncryptionValue() string { 20 | 21 | fp := f.Body.FuncParam 22 | 23 | return f.GetBaseEncryptionValue() + f.Body.UserId + f.Body.ContractName + f.Body.FuncName + fp 24 | 25 | } 26 | -------------------------------------------------------------------------------- /pkg/core/entity/base/res.go: -------------------------------------------------------------------------------- 1 | package base 2 | 3 | import "strconv" 4 | 5 | const Header_error_code int = -1 6 | 7 | const Header_success_code int = 0 8 | 9 | type ResHeader struct { 10 | Code int `json:"code"` 11 | 12 | Msg string `json:"msg"` 13 | } 14 | 15 | type BaseResModel struct { 16 | Header *ResHeader `json:"header"` 17 | 18 | Mac string `json:"mac"` // mac 19 | } 20 | 21 | func (b *BaseResModel) GetMac() string { 22 | return b.Mac 23 | } 24 | 25 | func (b *BaseResModel) GetEncryptionValue() string { 26 | 27 | return b.GetBaseEncryptionValue() 28 | } 29 | func (b *BaseResModel) GetBaseEncryptionValue() string { 30 | 31 | return strconv.Itoa(b.Header.Code) + b.Header.Msg 32 | } 33 | -------------------------------------------------------------------------------- /pkg/client/app/app_test.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req" 9 | ) 10 | 11 | func TestGetAppInfo(t *testing.T) { 12 | 13 | api := "http://192.168.1.43:17502" 14 | 15 | reqData := req.AppInfoReqData{} 16 | 17 | header := base.ReqHeader{ 18 | UserCode: "USER0001202004161009309407413", 19 | AppCode: "app0001202004161017141233920", 20 | } 21 | 22 | reqData.Header = header 23 | 24 | res, _ := GetAppInfo(&reqData, api, "") 25 | 26 | if res.Header.Code != 0 { 27 | fmt.Println(res.Header.Msg) 28 | } else { 29 | fmt.Println(res.Body) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /pkg/core/entity/base/req.go: -------------------------------------------------------------------------------- 1 | package base 2 | 3 | import "encoding/json" 4 | 5 | type ReqHeader struct { 6 | UserCode string `json:"userCode"` // User unique identification 7 | AppCode string `json:"appCode"` // App unique identification 8 | //TId string `json:"tId"` 9 | } 10 | 11 | type BaseReqModel struct { 12 | Header ReqHeader `json:"header"` 13 | Mac string `json:"mac"` 14 | } 15 | 16 | func (b *BaseReqModel) SetMac(mac string) { 17 | b.Mac = mac 18 | } 19 | 20 | func (b *BaseReqModel) GetBaseEncryptionValue() string { 21 | 22 | return b.Header.UserCode + b.Header.AppCode 23 | } 24 | 25 | func (b *BaseReqModel) ToJson() []byte { 26 | 27 | jsonBytes, _ := json.Marshal(b) 28 | return jsonBytes 29 | } 30 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/node/upukCallContract.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type UPukCallContractResData struct { 8 | base.BaseResModel 9 | Body *UPukCallContractResDataBody `json:"body"` 10 | } 11 | 12 | type UPukCallContractResDataBody struct { 13 | TxId string `json:"txId"` 14 | QueryInfo string `json:"queryInfo"` 15 | PreExecRes string `json:"preExecRes"` 16 | } 17 | 18 | func (f *UPukCallContractResData) GetEncryptionValue() string { 19 | if f.Body == nil { 20 | return f.GetBaseEncryptionValue() 21 | } 22 | fp := f.GetBaseEncryptionValue() 23 | fp += f.Body.TxId + f.Body.QueryInfo + f.Body.PreExecRes 24 | return fp 25 | } 26 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/BSNDA/PCNGateway-Go-SDK 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/BSNDA/bsn-sdk-crypto v1.1.1 7 | github.com/ethereum/go-ethereum v1.9.18 8 | github.com/golang/protobuf v1.5.2 9 | github.com/hyperledger/fabric-config v0.0.5 10 | github.com/hyperledger/fabric-protos-go v0.0.0-20211006172752-14f4318ce71c 11 | github.com/pkg/errors v0.9.1 12 | github.com/satori/go.uuid v1.2.0 13 | github.com/wonderivan/logger v1.0.0 14 | github.com/xuperchain/crypto v0.0.0-20201022090047-228df0d80193 15 | golang.org/x/crypto v0.0.0-20220128200615-198e4374d7ed 16 | golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd 17 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 18 | google.golang.org/grpc v1.31.0 19 | ) 20 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/event/registerReqData.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type RegisterReqData struct { 6 | base.BaseReqModel 7 | Body RegisterReqDataBody `json:"body"` 8 | } 9 | 10 | type RegisterReqDataBody struct { 11 | ChainCode string `json:"chainCode"` 12 | EventKey string `json:"eventKey"` 13 | NotifyUrl string `json:"notifyUrl"` 14 | AttachArgs string `json:"attachArgs"` 15 | } 16 | 17 | func (f *RegisterReqData) GetEncryptionValue() string { 18 | 19 | fp := f.GetBaseEncryptionValue() 20 | 21 | fp = fp + f.Body.ChainCode 22 | fp = fp + f.Body.EventKey 23 | fp = fp + f.Body.NotifyUrl 24 | fp = fp + f.Body.AttachArgs 25 | 26 | return fp 27 | 28 | } 29 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/node/getTx.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type GetTxInfoResData struct { 9 | base.BaseResModel 10 | Body *Transaction `json:"body"` // 消息体 11 | } 12 | 13 | func (f *GetTxInfoResData) GetEncryptionValue() string { 14 | if f.Body == nil { 15 | return f.GetBaseEncryptionValue() 16 | } 17 | fp := f.GetBaseEncryptionValue() 18 | 19 | fp = fp + f.Body.Txid + f.Body.Blockid + strconv.Itoa(int(f.Body.Version)) 20 | 21 | for _, v := range f.Body.ContractRequests { 22 | fp += v.ContractName 23 | fp += v.MethodName 24 | fp += v.Args 25 | } 26 | fp += strconv.FormatInt(f.Body.ReceivedTimestamp, 10) 27 | return fp 28 | } 29 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type RegisterEventReqData struct { 8 | base.BaseReqModel 9 | Body RegisterEventReqDataBody `json:"body"` 10 | } 11 | 12 | type RegisterEventReqDataBody struct { 13 | ContractName string `json:"contractName"` 14 | EventKey string `json:"eventKey"` 15 | NotifyUrl string `json:"notifyUrl"` 16 | AttachArgs string `json:"attachArgs"` 17 | } 18 | 19 | func (f *RegisterEventReqData) GetEncryptionValue() string { 20 | fp := f.Body.ContractName 21 | fp = fp + f.Body.EventKey 22 | fp = fp + f.Body.NotifyUrl 23 | fp = fp + f.Body.AttachArgs 24 | return f.GetBaseEncryptionValue() + fp 25 | } 26 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/node/transReqDataBody.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TransReqData struct { 8 | base.BaseReqModel 9 | Body TransReqDataBody `json:"body"` 10 | } 11 | 12 | type TransReqDataBody struct { 13 | UserId string `json:"userId"` 14 | ContractName string `json:"contractName"` 15 | FuncName string `json:"funcName"` 16 | //JSON string after serialization with []string , function name not included. 17 | FuncParam string `json:"funcParam"` 18 | } 19 | 20 | func (f *TransReqData) GetEncryptionValue() string { 21 | 22 | fp := f.Body.FuncParam 23 | 24 | return f.GetBaseEncryptionValue() + f.Body.UserId + f.Body.ContractName + f.Body.FuncName + fp 25 | 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/ledgerResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type LedgerResData struct { 9 | base.BaseResModel 10 | Body *LedgerResDataBody `json:"body"` 11 | } 12 | 13 | type LedgerResDataBody struct { 14 | BlockHash string `json:"blockHash"` 15 | PreBlockHash string `json:"preBlockHash"` 16 | Height uint64 `json:"height"` 17 | } 18 | 19 | func (f *LedgerResData) GetEncryptionValue() string { 20 | if f.Body == nil { 21 | return f.GetBaseEncryptionValue() 22 | } 23 | 24 | fp := f.GetBaseEncryptionValue() 25 | fp = fp + f.Body.BlockHash 26 | fp = fp + strconv.FormatUint(f.Body.Height, 10) 27 | fp = fp + f.Body.PreBlockHash 28 | 29 | return fp 30 | } 31 | -------------------------------------------------------------------------------- /pkg/core/entity/req/xuperchain/node/callContract.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type CallContractReqData struct { 8 | base.BaseReqModel 9 | Body CallContractReqDataReqDataBody `json:"body"` // 消息体 10 | } 11 | 12 | type CallContractReqDataReqDataBody struct { 13 | UserId string `json:"userId"` //用户ID必须由6~100位字母或数字组成! 14 | UserAddr string `json:"userAddr"` 15 | ContractName string `json:"contractName"` 16 | FuncName string `json:"funcName"` 17 | FuncParam string `json:"funcParam"` 18 | } 19 | 20 | func (m *CallContractReqData) GetEncryptionValue() string { 21 | 22 | return m.GetBaseEncryptionValue() + m.Body.UserId + m.Body.UserAddr + m.Body.ContractName + m.Body.FuncName + m.Body.FuncParam 23 | } 24 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/node/blockReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockReqData struct { 9 | base.BaseReqModel 10 | Body BlockReqDataBody `json:"body"` 11 | } 12 | 13 | type BlockReqDataBody struct { 14 | BlockNumber uint64 `json:"blockNumber"` 15 | BlockHash string `json:"blockHash"` 16 | TxId string `json:"txId"` 17 | // DataType Options as json 18 | DataType string `json:"dataType,omitempty"` 19 | } 20 | 21 | func (f *BlockReqData) GetEncryptionValue() string { 22 | 23 | fp := f.GetBaseEncryptionValue() 24 | fp = fp + strconv.FormatUint(f.Body.BlockNumber, 10) 25 | fp = fp + f.Body.BlockHash 26 | fp = fp + f.Body.TxId 27 | fp = fp + f.Body.DataType 28 | return fp 29 | 30 | } 31 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/node/transactionResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TransResData struct { 8 | base.BaseResModel 9 | Body *TransResDataDataBody `json:"body"` 10 | } 11 | 12 | type TransResDataDataBody struct { 13 | TxId string `json:"txId"` 14 | 15 | Status string `json:"status"` 16 | 17 | Data string `json:"data"` 18 | } 19 | 20 | func (f *TransResData) getBlockValue() string { 21 | 22 | if f.Body == nil { 23 | return "" 24 | } 25 | 26 | fb := "" 27 | 28 | fb = fb + f.Body.TxId 29 | 30 | fb = fb + f.Body.Status 31 | fb = fb + f.Body.Data 32 | 33 | return fb 34 | } 35 | 36 | func (f *TransResData) GetEncryptionValue() string { 37 | 38 | return f.GetBaseEncryptionValue() + f.getBlockValue() 39 | 40 | } 41 | -------------------------------------------------------------------------------- /pkg/client/app/app.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res" 9 | ) 10 | 11 | // GetAppInfo query basic information of Dapp 12 | func GetAppInfo(data *req.AppInfoReqData, baseApi string, cert string) (*res.AppInfoResData, error) { 13 | 14 | url := baseApi + "/api/app/getAppInfo" 15 | 16 | reqBytes, _ := json.Marshal(data) 17 | 18 | resBytes, err := http.SendPost(reqBytes, url) 19 | 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | resData := &res.AppInfoResData{} 25 | 26 | err = json.Unmarshal(resBytes, resData) 27 | 28 | if err != nil { 29 | return nil, err 30 | } 31 | 32 | return resData, nil 33 | 34 | } 35 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/node/transData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TransData struct { 8 | Contract ContractData 9 | FuncName string 10 | Args []interface{} 11 | UserName string 12 | } 13 | 14 | type ContractData struct { 15 | ContractName string 16 | ContractAbi string 17 | ContractAddress string 18 | } 19 | 20 | type KeyTransReqData struct { 21 | base.BaseReqModel 22 | Body KeyTransReqDataBody `json:"body"` //消息体 23 | } 24 | 25 | type KeyTransReqDataBody struct { 26 | ContractName string `json:"contractName"` //合约名称 27 | TransData string `json:"transData"` 28 | } 29 | 30 | func (f *KeyTransReqData) GetEncryptionValue() string { 31 | 32 | return f.GetBaseEncryptionValue() + f.Body.ContractName + f.Body.TransData 33 | 34 | } 35 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/blockDataRes.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockDataRes struct { 9 | base.BaseResModel 10 | Body *BlockDataResBody `json:"body"` 11 | } 12 | 13 | type BlockDataResBody struct { 14 | BlockHash string `json:"blockHash"` 15 | BlockNumber uint64 `json:"blockNumber"` 16 | PreBlockHash string `json:"preBlockHash"` 17 | BlockData string `json:"blockData"` 18 | } 19 | 20 | func (f *BlockDataRes) GetEncryptionValue() string { 21 | if f.Body == nil { 22 | return f.GetBaseEncryptionValue() 23 | } 24 | 25 | fp := f.GetBaseEncryptionValue() 26 | fp = fp + f.Body.BlockHash 27 | fp = fp + strconv.FormatUint(f.Body.BlockNumber, 10) 28 | fp = fp + f.Body.PreBlockHash 29 | fp = fp + f.Body.BlockData 30 | 31 | return fp 32 | } 33 | -------------------------------------------------------------------------------- /pkg/client/fisco-bcos/fiscobcosClient_user_test.go: -------------------------------------------------------------------------------- 1 | package fisco_bcos 2 | 3 | import ( 4 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fiscobcos/user" 5 | "testing" 6 | ) 7 | 8 | func TestFiscoBcosClient_RegisterUser(t *testing.T) { 9 | 10 | fiscoClient := getSMClient(t) 11 | 12 | body := req.RegisterReqDataBody{ 13 | UserId: "test0927", 14 | } 15 | 16 | res, err := fiscoClient.RegisterUser(body) 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | 21 | if res.Header.Code != 0 { 22 | t.Fatal(res.Header.Msg) 23 | } 24 | } 25 | 26 | func TestFiscoBcosClient_RegisterUserK1(t *testing.T) { 27 | 28 | fiscoClient := getK1Client(t) 29 | 30 | body := req.RegisterReqDataBody{ 31 | UserId: "test0611", 32 | } 33 | 34 | res, err := fiscoClient.RegisterUser(body) 35 | if err != nil { 36 | t.Fatal(err) 37 | } 38 | 39 | if res.Header.Code != 0 { 40 | t.Fatal(res.Header.Msg) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/account/account_ext_test.go: -------------------------------------------------------------------------------- 1 | package account 2 | 3 | import "testing" 4 | 5 | func TestGetAddressFromPublicKey(t *testing.T) { 6 | publicKey := `-----BEGIN PUBLIC KEY----- 7 | MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAELkdua4oPfiLIq6u3mqcUrAwqPBQn 8 | bdKnwmu3hgguwRHRnq21+KmuY96pY5df3eiNNHO73hQL4Bjz/AxU/pne6w== 9 | -----END PUBLIC KEY-----` 10 | puk, err := GetAddressFromPublicKey(publicKey) 11 | if err != nil { 12 | t.Fatal(err) 13 | } 14 | t.Logf("address:%s", puk) 15 | } 16 | 17 | func TestGetEcdsaPublicKeyJsonFormatFromPublicKey(t *testing.T) { 18 | publicKey := `-----BEGIN PUBLIC KEY----- 19 | MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAELkdua4oPfiLIq6u3mqcUrAwqPBQn 20 | bdKnwmu3hgguwRHRnq21+KmuY96pY5df3eiNNHO73hQL4Bjz/AxU/pne6w== 21 | -----END PUBLIC KEY-----` 22 | puk, err := GetEcdsaPublicKeyJsonFormatFromPublicKey(publicKey) 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | t.Logf("jsonFormat:%s", puk) 27 | } 28 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/account/account_ext.go: -------------------------------------------------------------------------------- 1 | package account 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "github.com/BSNDA/bsn-sdk-crypto/crypto/sm" 6 | "github.com/xuperchain/crypto/gm/account" 7 | ) 8 | 9 | //根据公钥生成address 10 | func GetAddressFromPublicKey(pubkey string) (string, error) { 11 | key, err := sm.ConvertSMPublicKey(pubkey) 12 | if err != nil { 13 | return "", err 14 | } 15 | 16 | address, err := account.GetAddressFromPublicKey(key) 17 | return address, err 18 | } 19 | 20 | func GetEcdsaPrivateKey(prikey string) (*ecdsa.PrivateKey, error) { 21 | return sm.ConvertSMPrivateKey(prikey) 22 | } 23 | 24 | //获取json格式的公钥信息 25 | func GetEcdsaPublicKeyJsonFormatFromPublicKey(pubkey string) (string, error) { 26 | key, err := sm.ConvertSMPublicKey(pubkey) 27 | if err != nil { 28 | return "", err 29 | } 30 | publicKeyJsonStr, err := account.GetEcdsaPublicKeyJsonFormatFromPublicKey(key) 31 | return publicKeyJsonStr, err 32 | } 33 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_user_test.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/user" 5 | "testing" 6 | ) 7 | 8 | func TestFabricClient_RegisterUser(t *testing.T) { 9 | fabricClient := getFabricClient(t) 10 | body := req.RegisterReqDataBody{ 11 | Name: "user20220421", 12 | Secret: "123456", 13 | ExtendProperties: "{'key1':'abc'}", //用户拓展属性,json格式,非必填 14 | } 15 | 16 | res, err := fabricClient.RegisterUser(body) 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | 21 | if res.Header.Code != 0 { 22 | t.Fatal(res.Header.Msg) 23 | } 24 | 25 | } 26 | 27 | func TestFabricClient_EnrollUser(t *testing.T) { 28 | 29 | fabricClient := getFabricClient(t) 30 | 31 | body := req.RegisterReqDataBody{ 32 | Name: "user20220421", 33 | Secret: "123456", 34 | } 35 | 36 | _, err := fabricClient.EnrollUser(body) 37 | 38 | if err != nil { 39 | t.Fatal(err.Error()) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/node/getBlock.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type GetBlockInfoResData struct { 9 | base.BaseResModel 10 | Body *Block `json:"body"` // 消息体 11 | } 12 | 13 | func (f *GetBlockInfoResData) GetEncryptionValue() string { 14 | if f.Body == nil { 15 | return f.GetBaseEncryptionValue() 16 | } 17 | fp := f.GetBaseEncryptionValue() 18 | fp = fp + strconv.Itoa(int(f.Body.Version)) + f.Body.Blockid + f.Body.PreHash + strconv.FormatInt(f.Body.Height, 10) + strconv.FormatInt(f.Body.Timestamp, 10) 19 | for _, t := range f.Body.Transactions { 20 | fp = fp + t.Txid + t.Blockid + strconv.Itoa(int(t.Version)) 21 | for _, v := range t.ContractRequests { 22 | fp += v.ContractName 23 | fp += v.MethodName 24 | fp += v.Args 25 | } 26 | fp += strconv.FormatInt(t.ReceivedTimestamp, 10) 27 | } 28 | fp += strconv.Itoa(int(f.Body.TxCount)) + f.Body.NextHash 29 | return fp 30 | } 31 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/transactionHeader.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/fabric/fab" 5 | ) 6 | 7 | // TransactionHeader contains metadata for a transaction created by the SDK. 8 | type TransactionHeader struct { 9 | id fab.TransactionID 10 | creator []byte 11 | nonce []byte 12 | channelID string 13 | } 14 | 15 | // TransactionID returns the transaction's computed identifier. 16 | func (th *TransactionHeader) TransactionID() fab.TransactionID { 17 | return th.id 18 | } 19 | 20 | // Creator returns the transaction creator's identity bytes. 21 | func (th *TransactionHeader) Creator() []byte { 22 | return th.creator 23 | } 24 | 25 | // Nonce returns the transaction's generated nonce. 26 | func (th *TransactionHeader) Nonce() []byte { 27 | return th.nonce 28 | } 29 | 30 | // ChannelID returns the transaction's target channel identifier. 31 | func (th *TransactionHeader) ChannelID() string { 32 | return th.channelID 33 | } 34 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/block.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "encoding/base64" 5 | "github.com/golang/protobuf/proto" 6 | "github.com/hyperledger/fabric-config/protolator" 7 | "github.com/hyperledger/fabric-protos-go/common" 8 | "github.com/pkg/errors" 9 | "strings" 10 | ) 11 | 12 | func ConvertToBlock(blockData string) (*common.Block, error) { 13 | 14 | blockBytes, err := base64.StdEncoding.DecodeString(blockData) 15 | if err != nil { 16 | return nil, errors.WithMessage(err, "convert block data has error") 17 | } 18 | block := &common.Block{} 19 | 20 | err = proto.Unmarshal(blockBytes, block) 21 | if err != nil { 22 | return nil, errors.WithMessage(err, "convert block bytes has error") 23 | } 24 | 25 | return block, nil 26 | } 27 | 28 | func ConvertBlockToJson(block *common.Block) (string, error) { 29 | 30 | var sb strings.Builder 31 | 32 | err := protolator.DeepMarshalJSON(&sb, block) 33 | if err != nil { 34 | return "", err 35 | } 36 | 37 | return sb.String(), err 38 | 39 | } 40 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/node/common.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | type Block struct { 4 | Version int32 `json:"version""` 5 | Blockid string `json:"blockid""` 6 | PreHash string `json:"preHash""` 7 | Height int64 `json:"height""` 8 | Timestamp int64 `json:"timestamp""` 9 | Transactions []*Transaction `json:"transactions""` 10 | TxCount int32 `json:"txCount""` 11 | NextHash string `json:"nextHash""` 12 | } 13 | 14 | type Transaction struct { 15 | Txid string `json:"txId""` 16 | Blockid string `json:"blockId""` 17 | Version int32 `json:"version""` 18 | ContractRequests []*InvokeRequest `json:"contractRequests""` 19 | ReceivedTimestamp int64 `json:"receivedTimestamp""` 20 | } 21 | 22 | type InvokeRequest struct { 23 | ContractName string `json:"contractName""` 24 | MethodName string `json:"methodName""` 25 | Args string `json:"args""` 26 | } 27 | -------------------------------------------------------------------------------- /pkg/core/entity/res/appInfo.go: -------------------------------------------------------------------------------- 1 | package res 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type AppInfoResData struct { 9 | base.BaseResModel 10 | Body AppInfoResDataBody `json:"body"` 11 | } 12 | 13 | type AppInfoResDataBody struct { 14 | AppType string `json:"appType"` 15 | CaType int `json:"caType"` 16 | AlgorithmType int `json:"algorithmType"` 17 | MspId string `json:"mspId"` 18 | //groupId in FISCO BCOS Dapp 19 | ChannelId string `json:"channelId"` 20 | Version string `json:"version"` 21 | 22 | FabricVersion string `json:"fabricVersion,omitempty"` 23 | } 24 | 25 | func (f *AppInfoResData) GetEncryptionValue() string { 26 | 27 | fp := f.GetBaseEncryptionValue() 28 | 29 | fp = fp + f.Body.AppType 30 | fp = fp + strconv.Itoa(f.Body.CaType) 31 | fp = fp + strconv.Itoa(f.Body.AlgorithmType) 32 | fp = fp + f.Body.MspId 33 | fp = fp + f.Body.ChannelId 34 | fp = fp + f.Body.Version 35 | fp = fp + f.Body.FabricVersion 36 | return fp 37 | } 38 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/tranResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type TranResData struct { 9 | base.BaseResModel 10 | Body *TranResDataBody `json:"body"` 11 | } 12 | 13 | type TranResDataBody struct { 14 | BlockInfo BlockInfo `json:"blockInfo"` 15 | 16 | CCRes CCRes `json:"ccRes"` 17 | } 18 | 19 | type BlockInfo struct { 20 | TxId string `json:"txId"` 21 | 22 | BlockHash string `json:"blockHash"` 23 | 24 | Status int `json:"status"` 25 | } 26 | 27 | type CCRes struct { 28 | CCCode int `json:"ccCode"` 29 | 30 | CCData string `json:"ccData"` 31 | } 32 | 33 | func (f *TranResData) GetEncryptionValue() string { 34 | if f.Body == nil { 35 | return f.GetBaseEncryptionValue() 36 | } 37 | 38 | fp := f.GetBaseEncryptionValue() 39 | fp = fp + f.Body.BlockInfo.TxId 40 | fp = fp + f.Body.BlockInfo.BlockHash 41 | fp = fp + strconv.Itoa(f.Body.BlockInfo.Status) 42 | 43 | fp = fp + strconv.Itoa(f.Body.CCRes.CCCode) 44 | fp = fp + f.Body.CCRes.CCData 45 | 46 | return fp 47 | } 48 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/transactionResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type TransactionResData struct { 9 | base.BaseResModel 10 | Body *TransactionResDataBody `json:"body"` 11 | } 12 | 13 | type TransactionResDataBody struct { 14 | BlockHash string `json:"blockHash"` 15 | BlockNumber uint64 `json:"blockNumber"` 16 | 17 | Status int `json:"status"` 18 | CreateName string `json:"createName"` 19 | TimeSpanSec int64 `json:"timeSpanSec"` 20 | TimeSpanNsec int64 `json:"timeSpanNsec"` 21 | } 22 | 23 | func (f *TransactionResData) GetEncryptionValue() string { 24 | 25 | if f.Body == nil { 26 | return f.GetBaseEncryptionValue() 27 | } 28 | 29 | fp := f.GetBaseEncryptionValue() 30 | fp = fp + f.Body.BlockHash 31 | fp = fp + strconv.FormatUint(f.Body.BlockNumber, 10) 32 | fp = fp + strconv.Itoa(f.Body.Status) 33 | fp = fp + f.Body.CreateName 34 | fp = fp + strconv.FormatInt(f.Body.TimeSpanSec, 10) 35 | fp = fp + strconv.FormatInt(f.Body.TimeSpanNsec, 10) 36 | 37 | return fp 38 | } 39 | -------------------------------------------------------------------------------- /pkg/core/sign/bsnCrypto.go: -------------------------------------------------------------------------------- 1 | package sign 2 | 3 | import ( 4 | "encoding/base64" 5 | "github.com/BSNDA/bsn-sdk-crypto/sign" 6 | ) 7 | 8 | type Crypto interface { 9 | Sign(value string) (string, error) 10 | Verify(mac, value string) bool 11 | } 12 | 13 | func NewCrypto(sign sign.SignProvider) Crypto { 14 | 15 | return &gatewayCrypto{ 16 | sign: sign, 17 | } 18 | 19 | } 20 | 21 | type gatewayCrypto struct { 22 | sign sign.SignProvider 23 | } 24 | 25 | func (g *gatewayCrypto) Sign(value string) (string, error) { 26 | 27 | digest := g.sign.Hash([]byte(value)) 28 | 29 | signBytes, err := g.sign.Sign(digest) 30 | if err != nil { 31 | return "", err 32 | } 33 | 34 | mac := base64.StdEncoding.EncodeToString(signBytes) 35 | 36 | return mac, nil 37 | } 38 | 39 | func (g *gatewayCrypto) Verify(mac, value string) bool { 40 | 41 | signBytes, err := base64.StdEncoding.DecodeString(mac) 42 | if err != nil { 43 | return false 44 | } 45 | 46 | digest := g.sign.Hash([]byte(value)) 47 | 48 | falg, err := g.sign.Verify(signBytes, digest) 49 | 50 | if err != nil { 51 | return false 52 | } 53 | 54 | return falg 55 | } 56 | -------------------------------------------------------------------------------- /pkg/core/entity/req/cita/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type RegisterReqData struct { 9 | base.BaseReqModel 10 | Body RegisterReqDataBody `json:"body"` 11 | } 12 | 13 | type RegisterReqDataBody struct { 14 | EventType int `json:"eventType"` //1 block 2 contract 15 | 16 | //if EventType is 1,ContractAddress and ContractName Can be empty 17 | //if EventType is 2,ContractAddress and ContractName Cannot be empty at the same time, ContractAddress first 18 | ContractAddress string `json:"contractAddress"` 19 | ContractName string `json:"contractName"` 20 | 21 | NotifyUrl string `json:"notifyUrl"` 22 | AttachArgs string `json:"attachArgs"` 23 | } 24 | 25 | func (f *RegisterReqDataBody) GetEncryptionValue() string { 26 | fp := strconv.Itoa(f.EventType) 27 | fp = fp + f.ContractAddress 28 | fp = fp + f.ContractName 29 | fp = fp + f.NotifyUrl 30 | fp = fp + f.AttachArgs 31 | return fp 32 | } 33 | 34 | func (f *RegisterReqData) GetEncryptionValue() string { 35 | 36 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 37 | 38 | } 39 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/node/transData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type TransData struct { 8 | Contract ContractData 9 | FuncName string 10 | Args []interface{} 11 | UserName string 12 | } 13 | 14 | type ContractData struct { 15 | ContractName string 16 | ContractAbi string 17 | ContractAddress string 18 | } 19 | 20 | type KeyTransReqData struct { 21 | base.BaseReqModel 22 | Body KeyTransReqDataBody `json:"body"` //消息体 23 | } 24 | 25 | type KeyTransReqDataBody struct { 26 | ContractName string `json:"contractName"` //合约名称 27 | TransData string `json:"transData"` 28 | ContractAddress string `json:"contractAddress,omitempty"` 29 | ContractAbi string `json:"contractAbi,omitempty"` 30 | } 31 | 32 | func (f *KeyTransReqData) GetEncryptionValue() string { 33 | 34 | fb := f.GetBaseEncryptionValue() + f.Body.ContractName + f.Body.TransData 35 | 36 | if len(f.Body.ContractAddress) > 0 { 37 | fb = fb + f.Body.ContractAddress 38 | } 39 | if len(f.Body.ContractAbi) > 0 { 40 | fb = fb + f.Body.ContractAbi 41 | } 42 | 43 | return fb 44 | } 45 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/node/blockTxResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockTxResData struct { 9 | base.BaseResModel 10 | Body TransactionData `json:"body"` 11 | } 12 | 13 | type TransactionData struct { 14 | TxId string `json:"txId"` 15 | BlockHash string `json:"blockHash"` 16 | BlockNumber uint64 `json:"blockNumber"` 17 | 18 | GasUsed int64 `json:"gasUsed"` 19 | 20 | From string `json:"from"` 21 | To string `json:"to"` 22 | Value int64 `json:"value"` 23 | 24 | Input string `json:"input"` 25 | } 26 | 27 | func (f *TransactionData) GetEncryptionValue() string { 28 | 29 | fb := "" 30 | 31 | fb = fb + f.TxId 32 | fb = fb + f.BlockHash 33 | fb = fb + strconv.FormatUint(f.BlockNumber, 10) 34 | fb = fb + strconv.FormatInt(f.GasUsed, 10) 35 | fb = fb + f.From 36 | fb = fb + f.To 37 | fb = fb + strconv.FormatInt(f.Value, 10) 38 | fb = fb + f.Input 39 | 40 | return fb 41 | } 42 | 43 | func (f *BlockTxResData) GetEncryptionValue() string { 44 | 45 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 46 | 47 | } 48 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchainClient.go: -------------------------------------------------------------------------------- 1 | // @Title xuperchainClient 2 | // @Description 3 | // @Author zxl 2020/7/22 19:31 4 | // @Version 1.0.0 5 | // @Update 2020/7/22 19:31 6 | package xuperchain 7 | 8 | import ( 9 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/client" 10 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 11 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 12 | "github.com/wonderivan/logger" 13 | ) 14 | 15 | func NewXuperChainClient(config *config.Config) (*XuperChainClient, error) { 16 | client := client.Client{ 17 | Config: config, 18 | } 19 | 20 | xuperChainClient := &XuperChainClient{ 21 | client, 22 | } 23 | 24 | err := xuperChainClient.SetAlgorithm(config.GetAppInfo().AlgorithmType, config.GetAppCert().AppPublicCert, config.GetAppCert().UserAppPrivateCert) 25 | 26 | if err != nil { 27 | logger.Error("signHandle initialization failed") 28 | return nil, err 29 | } 30 | 31 | return xuperChainClient, nil 32 | } 33 | 34 | type XuperChainClient struct { 35 | client.Client 36 | } 37 | 38 | func (f *XuperChainClient) isSM() bool { 39 | return f.Config.GetAppInfo().AlgorithmType == enum.AppAlgorithmType_SM2 40 | } 41 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fiscobcos/event/register.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type RegisterReqData struct { 9 | base.BaseReqModel 10 | Body RegisterReqDataBody `json:"body"` 11 | } 12 | 13 | type RegisterReqDataBody struct { 14 | EventType int `json:"eventType"` //1 block 2 contract 15 | 16 | //if EventType is 1,ContractAddress and ContractName Can be empty 17 | //if EventType is 2,ContractAddress and ContractName Cannot be empty at the same time, ContractAddress first 18 | ContractAddress string `json:"contractAddress"` 19 | ContractName string `json:"contractName"` 20 | 21 | NotifyUrl string `json:"notifyUrl"` 22 | AttachArgs string `json:"attachArgs"` 23 | } 24 | 25 | func (f *RegisterReqDataBody) GetEncryptionValue() string { 26 | fp := strconv.Itoa(f.EventType) 27 | fp = fp + f.ContractAddress 28 | fp = fp + f.ContractName 29 | fp = fp + f.NotifyUrl 30 | fp = fp + f.AttachArgs 31 | return fp 32 | } 33 | 34 | func (f *RegisterReqData) GetEncryptionValue() string { 35 | 36 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 37 | 38 | } 39 | -------------------------------------------------------------------------------- /pkg/core/entity/res/xuperchain/event/query.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | ) 6 | 7 | type QueryEventResData struct { 8 | base.BaseResModel 9 | Body QueryEventResDataBody `json:"body"` // 消息体 10 | } 11 | 12 | type QueryEventResDataBody struct { 13 | BlockEvent []QueryEventResData_BlockEvent `json:"blockEvent"` 14 | } 15 | 16 | type QueryEventResData_BlockEvent struct { 17 | EventId string `json:"eventId"` 18 | EventKey string `json:"eventKey"` 19 | NotifyUrl string `json:"notifyUrl"` 20 | AttachArgs string `json:"attachArgs"` 21 | CreateTime string `json:"createTime"` 22 | UserCode string `json:"userCode"` 23 | AppCode string `json:"appCode"` 24 | ContractName string `json:"contractName"` 25 | } 26 | 27 | func (f *QueryEventResData) GetEncryptionValue() string { 28 | fp := "" 29 | for _, b := range f.Body.BlockEvent { 30 | fp += b.EventId 31 | fp += b.EventKey 32 | fp += b.AppCode 33 | fp += b.UserCode 34 | fp += b.ContractName 35 | fp += b.NotifyUrl 36 | fp += b.AttachArgs 37 | fp += b.CreateTime 38 | } 39 | 40 | return f.GetBaseEncryptionValue() + fp 41 | } 42 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/node/blockTxReceiptResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockTxReceiptResData struct { 9 | base.BaseResModel 10 | Body *TxReceiptData `json:"body"` 11 | } 12 | 13 | type TxReceiptData struct { 14 | TxId string `json:"txId"` 15 | BlockHash string `json:"blockHash"` 16 | BlockNumber int64 `json:"blockNumber"` 17 | 18 | GasUsed int64 `json:"gasUsed"` 19 | 20 | From string `json:"from"` 21 | To string `json:"to"` 22 | 23 | ContractAddress string `json:"contractAddress"` 24 | Logs string `json:"logs"` 25 | } 26 | 27 | func (f *TxReceiptData) GetEncryptionValue() string { 28 | 29 | fb := "" 30 | 31 | fb = fb + f.TxId 32 | fb = fb + f.BlockHash 33 | fb = fb + strconv.FormatInt(f.BlockNumber, 10) 34 | fb = fb + strconv.FormatInt(f.GasUsed, 10) 35 | fb = fb + f.From 36 | fb = fb + f.To 37 | 38 | fb = fb + f.ContractAddress 39 | fb = fb + f.Logs 40 | return fb 41 | } 42 | 43 | func (f *BlockTxReceiptResData) GetEncryptionValue() string { 44 | 45 | return f.GetBaseEncryptionValue() + f.GetEncryptionValue() 46 | 47 | } 48 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchain_event_test.go: -------------------------------------------------------------------------------- 1 | package xuperchain 2 | 3 | import ( 4 | "fmt" 5 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/xuperchain/event" 6 | "testing" 7 | ) 8 | 9 | func TestXuperChainClient_EventRegister(t *testing.T) { 10 | client := getXuperChainClient(t) 11 | body := req.RegisterEventReqDataBody{ 12 | ContractName: "cc_appxc_01", 13 | EventKey: "increase_event", 14 | NotifyUrl: "http://192.168.7.141:8088/revNotify1", 15 | AttachArgs: "abc=123", 16 | } 17 | 18 | res, err := client.RegisterEvent(body) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | 23 | fmt.Println(res) 24 | } 25 | func TestXuperChainClient_EventQuery(t *testing.T) { 26 | client := getXuperChainClient(t) 27 | 28 | res, err := client.QueryEvent() 29 | if err != nil { 30 | t.Fatal(err) 31 | } 32 | 33 | fmt.Println(res) 34 | 35 | } 36 | func TestXuperChainClient_EventRemove(t *testing.T) { 37 | client := getXuperChainClient(t) 38 | body := req.RemoveEventReqDataBody{ 39 | EventId: "f4c6912f5b0540399ff080ef798763fa", 40 | } 41 | 42 | res, err := client.RemoveEvent(body) 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | 47 | fmt.Println(res) 48 | } 49 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/event/queryResData.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 4 | 5 | type QueryResData struct { 6 | base.BaseResModel 7 | Body []EventQueryBody `json:"body"` 8 | } 9 | 10 | type EventQueryBody struct { 11 | EventKey string `json:"eventKey,omitempty"` 12 | NotifyUrl string `json:"notifyUrl"` 13 | AttachArgs string `json:"attachArgs"` 14 | EventId string `json:"eventId"` 15 | CreateTime string `json:"createTime"` 16 | OrgCode string `json:"orgCode"` 17 | UserCode string `json:"userCode"` 18 | AppCode string `json:"appCode"` 19 | ChainCode string `json:"chainCode,omitempty"` 20 | EventType string `json:"eventType,omitempty"` 21 | } 22 | 23 | func (f *QueryResData) GetEncryptionValue() string { 24 | 25 | fp := f.GetBaseEncryptionValue() 26 | for _, task := range f.Body { 27 | fp = fp + task.EventId 28 | fp = fp + task.EventKey 29 | fp = fp + task.NotifyUrl 30 | fp = fp + task.AttachArgs 31 | fp = fp + task.CreateTime 32 | fp = fp + task.OrgCode 33 | fp = fp + task.UserCode 34 | fp = fp + task.AppCode 35 | fp = fp + task.ChainCode 36 | fp = fp + task.EventType 37 | } 38 | 39 | return fp 40 | } 41 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/event/event.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | type EventList struct { 4 | BlockEvent []BlockEvent `json:"blockEvent"` 5 | ContractEvent []ContractEvent `json:"contractEvent"` 6 | } 7 | 8 | type Event struct { 9 | EventId string `json:"eventId"` 10 | AppCode string `json:"appCode"` 11 | UserCode string `json:"userCode"` 12 | NotifyUrl string `json:"notifyUrl"` 13 | AttachArgs string `json:"attachArgs"` 14 | CreateTime string `json:"createTime"` 15 | } 16 | 17 | type BlockEvent struct { 18 | Event 19 | } 20 | 21 | type ContractEvent struct { 22 | Event 23 | ContractAddress string `json:"contractAddress"` 24 | } 25 | 26 | func (e *EventList) GetEncryptionValue() string { 27 | 28 | fp := "" 29 | for _, b := range e.BlockEvent { 30 | fp = fp + b.EventId 31 | fp = fp + b.AppCode 32 | fp = fp + b.UserCode 33 | fp = fp + b.NotifyUrl 34 | fp = fp + b.AttachArgs 35 | fp = fp + b.CreateTime 36 | } 37 | 38 | for _, b := range e.ContractEvent { 39 | fp = fp + b.EventId 40 | fp = fp + b.AppCode 41 | fp = fp + b.UserCode 42 | fp = fp + b.NotifyUrl 43 | fp = fp + b.AttachArgs 44 | fp = fp + b.CreateTime 45 | fp = fp + b.ContractAddress 46 | } 47 | 48 | return fp 49 | } 50 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/event/event.go: -------------------------------------------------------------------------------- 1 | package event 2 | 3 | type EventList struct { 4 | BlockEvent []BlockEvent `json:"blockEvent"` 5 | ContractEvent []ContractEvent `json:"contractEvent"` 6 | } 7 | 8 | type Event struct { 9 | EventId string `json:"eventId"` 10 | AppCode string `json:"appCode"` 11 | UserCode string `json:"userCode"` 12 | NotifyUrl string `json:"notifyUrl"` 13 | AttachArgs string `json:"attachArgs"` 14 | CreateTime string `json:"createTime"` 15 | } 16 | 17 | type BlockEvent struct { 18 | Event 19 | } 20 | 21 | type ContractEvent struct { 22 | Event 23 | ContractAddress string `json:"contractAddress"` 24 | } 25 | 26 | func (e *EventList) GetEncryptionValue() string { 27 | 28 | fp := "" 29 | for _, b := range e.BlockEvent { 30 | fp = fp + b.EventId 31 | fp = fp + b.AppCode 32 | fp = fp + b.UserCode 33 | fp = fp + b.NotifyUrl 34 | fp = fp + b.AttachArgs 35 | fp = fp + b.CreateTime 36 | } 37 | 38 | for _, b := range e.ContractEvent { 39 | fp = fp + b.EventId 40 | fp = fp + b.AppCode 41 | fp = fp + b.UserCode 42 | fp = fp + b.NotifyUrl 43 | fp = fp + b.AttachArgs 44 | fp = fp + b.CreateTime 45 | fp = fp + b.ContractAddress 46 | } 47 | 48 | return fp 49 | } 50 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/node/blockResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockResData struct { 9 | base.BaseResModel 10 | Body *BlockData `json:"body"` 11 | } 12 | 13 | type BlockData struct { 14 | BlockHash string `json:"blockHash"` 15 | BlockNumber int64 `json:"blockNumber"` 16 | 17 | ParentBlockHash string `json:"parentBlockHash"` 18 | 19 | BlockSize int64 `json:"blockSize"` 20 | 21 | BlockTime int64 `json:"blockTime"` 22 | 23 | Author string `json:"author"` 24 | 25 | Transactions []*TransactionData `json:"transactions"` 26 | } 27 | 28 | func (f *BlockData) GetEncryptionValue() string { 29 | 30 | fb := "" 31 | fb = fb + f.BlockHash 32 | fb = fb + strconv.FormatInt(f.BlockNumber, 10) 33 | fb = fb + f.ParentBlockHash 34 | fb = fb + strconv.FormatInt(f.BlockSize, 10) 35 | fb = fb + strconv.FormatInt(f.BlockTime, 10) 36 | fb = fb + f.Author 37 | 38 | for _, tx := range f.Transactions { 39 | fb = fb + tx.GetEncryptionValue() 40 | } 41 | 42 | return fb 43 | } 44 | 45 | func (f *BlockResData) GetEncryptionValue() string { 46 | 47 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 48 | 49 | } 50 | -------------------------------------------------------------------------------- /pkg/util/keystore/filekeystore.go: -------------------------------------------------------------------------------- 1 | package keystore 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/file" 5 | "github.com/wonderivan/logger" 6 | "io/ioutil" 7 | "path" 8 | "sync" 9 | ) 10 | 11 | func NewFileKeyStore(keyDir string) KeyStore { 12 | 13 | file.CheckDir(keyDir) 14 | 15 | return &fileKeyStore{ 16 | path: keyDir, 17 | } 18 | } 19 | 20 | type fileKeyStore struct { 21 | path string 22 | 23 | m sync.Mutex 24 | } 25 | 26 | func (f *fileKeyStore) keyPath(alias string) string { 27 | return path.Join(f.path, alias+"_sk") 28 | } 29 | 30 | func (f *fileKeyStore) StoreKey(rawPem []byte, alias string) error { 31 | 32 | f.m.Lock() 33 | defer f.m.Unlock() 34 | 35 | keyFile := f.keyPath(alias) 36 | 37 | err := ioutil.WriteFile(keyFile, rawPem, 0600) 38 | if err != nil { 39 | logger.Debug("Failed storing private key [%s]: [%s]", keyFile, err) 40 | return err 41 | } 42 | return nil 43 | } 44 | 45 | func (f *fileKeyStore) LoadKey(alias string) ([]byte, error) { 46 | 47 | f.m.Lock() 48 | defer f.m.Unlock() 49 | 50 | keyFile := f.keyPath(alias) 51 | raw, err := ioutil.ReadFile(keyFile) 52 | if err != nil { 53 | logger.Error("Failed loading private key [%s]: [%s].", alias, err.Error()) 54 | 55 | return nil, err 56 | } 57 | return raw, nil 58 | } 59 | -------------------------------------------------------------------------------- /pkg/client/cita/citaClient_event_test.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | eventreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/cita/event" 8 | ) 9 | 10 | func TestCitaClient_EventRegister(t *testing.T) { 11 | 12 | citaClient := getCitaClient(t) 13 | 14 | body := eventreq.RegisterReqDataBody{ 15 | EventType: 2, 16 | ContractAddress: "0xb4e5fa1f9f65908e04d322d6d0bb89702e88c986", 17 | //ContractName: "GetTopic", 18 | NotifyUrl: "http://192.168.1.172:58011/v1/fabric/test", 19 | AttachArgs: "abc=123", 20 | } 21 | 22 | res, err := citaClient.EventRegister(body) 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | 27 | fmt.Println(res) 28 | 29 | } 30 | 31 | func TestCitaClient_EventQuery(t *testing.T) { 32 | citaClient := getCitaClient(t) 33 | 34 | res, err := citaClient.EventQuery() 35 | if err != nil { 36 | t.Fatal(err) 37 | } 38 | 39 | fmt.Println(res) 40 | } 41 | 42 | func TestCitaClient_EventRemove(t *testing.T) { 43 | citaClient := getCitaClient(t) 44 | 45 | body := eventreq.RemoveReqDataBody{ 46 | EventId: "41d7d52e604e110365e4046072be88da970c96c533452ceeca77aa4e1cab54c3", 47 | } 48 | res, err := citaClient.EventRemove(body) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | 53 | fmt.Println(res) 54 | } 55 | -------------------------------------------------------------------------------- /pkg/core/entity/msp/userData.go: -------------------------------------------------------------------------------- 1 | package msp 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 5 | "github.com/BSNDA/bsn-sdk-crypto/key" 6 | "github.com/golang/protobuf/proto" 7 | pb_msp "github.com/hyperledger/fabric-protos-go/msp" 8 | ) 9 | 10 | type UserData struct { 11 | UserName string 12 | AppCode string 13 | MspId string 14 | EnrollmentCertificate []byte 15 | 16 | PrivateKey key.PrivateKeyProvider 17 | 18 | TxHash key.HashProvider 19 | } 20 | 21 | func (u *UserData) Hash() key.HashProvider { 22 | if u.TxHash == nil { 23 | return u.PrivateKey 24 | } else { 25 | return u.TxHash 26 | } 27 | } 28 | 29 | //func (u *UserData) SetSignHandle(s sign.SignProvider) { 30 | // u.sign = s 31 | //} 32 | 33 | func (u *UserData) Sign(digest []byte) (signature []byte, err error) { 34 | hash := u.PrivateKey.Hash(digest) 35 | return u.PrivateKey.Sign(hash) 36 | } 37 | 38 | func (u *UserData) Serialize() ([]byte, error) { 39 | serializedIdentity := &pb_msp.SerializedIdentity{ 40 | Mspid: u.MspId, 41 | IdBytes: u.EnrollmentCertificate, 42 | } 43 | identity, err := proto.Marshal(serializedIdentity) 44 | if err != nil { 45 | return nil, errors.New("marshal serializedIdentity failed") 46 | } 47 | return identity, nil 48 | } 49 | -------------------------------------------------------------------------------- /pkg/client/fisco-bcos/fiscobcosClient_event_test.go: -------------------------------------------------------------------------------- 1 | package fisco_bcos 2 | 3 | import ( 4 | "fmt" 5 | eventreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fiscobcos/event" 6 | "testing" 7 | ) 8 | 9 | func TestFiscoBcosClient_EventRegister(t *testing.T) { 10 | 11 | fiscoClient := getK1Client(t) 12 | 13 | body := eventreq.RegisterReqDataBody{ 14 | EventType: 1, 15 | ContractAddress: "0x866aefc204b8f8fdc3e45b908fd43d76667d7f76", 16 | ContractName: "BsnBaseContractk1", 17 | NotifyUrl: "http://192.168.6.85:18080/api/fiscobcos/test", 18 | AttachArgs: "abc=123", 19 | } 20 | 21 | res, err := fiscoClient.EventRegister(body) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | 26 | fmt.Println(res) 27 | 28 | } 29 | 30 | func TestFiscoBcosClient_EventQuery(t *testing.T) { 31 | fiscoClient := getK1Client(t) 32 | 33 | res, err := fiscoClient.EventQuery() 34 | if err != nil { 35 | t.Fatal(err) 36 | } 37 | 38 | fmt.Println(res) 39 | } 40 | 41 | func TestFiscoBcosClient_EventRemove(t *testing.T) { 42 | fiscoClient := getK1Client(t) 43 | 44 | body := eventreq.RemoveReqDataBody{ 45 | EventId: "764d6a2d8c0e44dd824bbc196830f282", 46 | } 47 | 48 | res, err := fiscoClient.EventRemove(body) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | 53 | fmt.Println(res) 54 | } 55 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchain_user.go: -------------------------------------------------------------------------------- 1 | package xuperchain 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 7 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/xuperchain/user" 8 | res "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/xuperchain/user" 9 | "github.com/wonderivan/logger" 10 | ) 11 | 12 | func (c *XuperChainClient) RegisterUser(body req.RegisterUserReqDataBody) (*res.RegisterUserResData, error) { 13 | url := c.GetURL("/api/xuperchain/v1/user/register") 14 | 15 | data := &req.RegisterUserReqData{} 16 | data.Header = c.GetHeader() 17 | data.Body = body 18 | data.Mac = c.Sign(data.GetEncryptionValue()) 19 | 20 | reqBytes, _ := json.Marshal(data) 21 | 22 | resBytes, err := http.SendPost(reqBytes, url) 23 | 24 | if err != nil { 25 | logger.Error("gateway interface call failed:", err) 26 | return nil, err 27 | } 28 | 29 | resData := &res.RegisterUserResData{} 30 | 31 | err = json.Unmarshal(resBytes, resData) 32 | if err != nil { 33 | logger.Error("return parameter serialization failed:", err) 34 | return nil, err 35 | } 36 | if !c.Verify(resData.Mac, resData.GetEncryptionValue()) { 37 | return nil, errors.New("sign has error") 38 | } 39 | 40 | return resData, nil 41 | } 42 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/node/blockResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockResData struct { 9 | base.BaseResModel 10 | Body *BlockData `json:"body"` 11 | } 12 | 13 | type BlockData struct { 14 | BlockHash string `json:"blockHash"` 15 | BlockNumber int64 `json:"blockNumber"` 16 | PrevBlockHash string `json:"prevBlockHash"` 17 | BlockTime string `json:"blockTime"` 18 | QuotaUsed string `json:"quotaUsed"` 19 | TransactionsRoot string `json:"transactionsRoot"` 20 | StateRoot string `json:"stateRoot"` 21 | ReceiptsRoot string `json:"receiptsRoot"` 22 | 23 | Transactions []*TransactionData `json:"transactions"` 24 | } 25 | 26 | func (f *BlockData) GetEncryptionValue() string { 27 | fp := "" 28 | 29 | fp = fp + f.BlockHash 30 | fp = fp + strconv.FormatInt(f.BlockNumber, 10) 31 | fp = fp + f.PrevBlockHash 32 | fp = fp + f.BlockTime 33 | fp = fp + f.QuotaUsed 34 | fp = fp + f.TransactionsRoot 35 | fp = fp + f.StateRoot 36 | fp = fp + f.ReceiptsRoot 37 | 38 | for _, tx := range f.Transactions { 39 | fp = fp + tx.GetEncryptionValue() 40 | } 41 | 42 | return fp 43 | } 44 | 45 | func (f *BlockResData) GetEncryptionValue() string { 46 | 47 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 48 | 49 | } 50 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/node/blockTxResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockTxResData struct { 9 | base.BaseResModel 10 | Body TransactionData `json:"body"` 11 | } 12 | 13 | type TransactionData struct { 14 | TxHash string `json:"txHash"` 15 | BlockHash string `json:"blockHash"` 16 | BlockNumber int64 `json:"blockNumber"` 17 | Data string `json:"data"` 18 | ChainId string `json:"chainId"` 19 | Quota string `json:"quota"` 20 | From string `json:"from"` 21 | To string `json:"to"` 22 | Nonce string `json:"nonce"` 23 | ValidUntilBlock string `json:"validUntilBlock"` 24 | Version string `json:"version"` 25 | } 26 | 27 | func (f *TransactionData) GetEncryptionValue() string { 28 | 29 | fp := "" 30 | 31 | fp = fp + f.TxHash 32 | fp = fp + f.BlockHash 33 | fp = fp + strconv.FormatInt(f.BlockNumber, 10) 34 | fp = fp + f.Data 35 | fp = fp + f.ChainId 36 | fp = fp + f.Quota 37 | fp = fp + f.From 38 | fp = fp + f.To 39 | fp = fp + f.Nonce 40 | fp = fp + f.ValidUntilBlock 41 | fp = fp + f.Version 42 | 43 | return fp 44 | } 45 | 46 | func (f *BlockTxResData) GetEncryptionValue() string { 47 | 48 | return f.GetBaseEncryptionValue() + f.Body.GetEncryptionValue() 49 | 50 | } 51 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_event_test.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/event" 8 | ) 9 | 10 | func TestFabricClient_EventRegister(t *testing.T) { 11 | 12 | fabricClient := getFabricClient(t) 13 | 14 | body := req.RegisterReqDataBody{ 15 | ChainCode: "cc_app0001202012111600499234472_02", 16 | EventKey: "test", 17 | NotifyUrl: "http://192.168.1.172:58011/v1/fabric/test", 18 | AttachArgs: "a=1", 19 | } 20 | 21 | res, _ := fabricClient.EventRegister(body) 22 | 23 | fmt.Println(res) 24 | 25 | } 26 | 27 | func TestFabricClient_BlockEventRegister(t *testing.T) { 28 | 29 | fabricClient := getFabricClient(t) 30 | 31 | body := req.RegisterReqDataBody{ 32 | NotifyUrl: "http://10.0.7.33:58011/v1/fabric/test", 33 | AttachArgs: "a=1", 34 | } 35 | 36 | res, _ := fabricClient.BlockEventRegister(body) 37 | 38 | fmt.Println(res) 39 | 40 | } 41 | 42 | func TestFabricClient_EventQuery(t *testing.T) { 43 | fabricClient := getFabricClient(t) 44 | 45 | res, _ := fabricClient.EventQuery() 46 | 47 | fmt.Println(res) 48 | } 49 | 50 | func TestFabricClient_EventRemove(t *testing.T) { 51 | fabricClient := getFabricClient(t) 52 | body := req.RemoveReqDataBody{ 53 | EventId: "c5d10b8df8f64700a8bccaf46d390dd8", 54 | } 55 | 56 | res, _ := fabricClient.EventRemove(body) 57 | 58 | fmt.Println(res) 59 | } 60 | -------------------------------------------------------------------------------- /pkg/common/cache/cache.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/cache/proc" 5 | "time" 6 | ) 7 | 8 | const ( 9 | Expiration = "0.5h" 10 | Interval = "3s" 11 | ) 12 | 13 | var ca *proc.Cache 14 | 15 | func InitCache() { 16 | // Default expiration time 17 | defaultExpiration, _ := time.ParseDuration(Expiration) 18 | //Recovery time, recovery expired 19 | gcInterval, _ := time.ParseDuration(Interval) 20 | ca = proc.NewCache(defaultExpiration, gcInterval) 21 | 22 | } 23 | 24 | //Set a sliding expiration cashe expiration time 25 | func SetSlideValue(key string, value interface{}, expiration string) { 26 | if ca == nil { 27 | InitCache() 28 | } 29 | dur, _ := time.ParseDuration(expiration) 30 | ca.Set(key, value, dur, true) 31 | } 32 | 33 | //Set a cache with an expiration date 34 | func SetValueByExpiration(key string, value interface{}, expiration string) { 35 | if ca == nil { 36 | InitCache() 37 | } 38 | expi, _ := time.ParseDuration(expiration) 39 | ca.Set(key, value, expi, false) 40 | } 41 | 42 | //Set a cache that never expires 43 | func SetValue(key string, value interface{}) { 44 | if ca == nil { 45 | InitCache() 46 | } 47 | ca.Set(key, value, 0, false) 48 | } 49 | 50 | //Get the configured value 51 | func GetValue(key string) (interface{}, bool) { 52 | if ca == nil { 53 | return nil, false 54 | } 55 | return ca.Get(key) 56 | 57 | } 58 | 59 | func ClearKey(key string) { 60 | ca.Delete(key) 61 | } 62 | -------------------------------------------------------------------------------- /pkg/core/config/fileConfig.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/file" 8 | ) 9 | 10 | const ( 11 | _DefaultConfigPath = "./conf/config.json" 12 | _DefaultMSPPath = "./msp" 13 | ) 14 | 15 | type fileConfig struct { 16 | NodeApi string `json:"nodeApi"` 17 | UserCode string `json:"userCode"` 18 | AppCode string `json:"appCode"` 19 | UserPrivateKey string `json:"userPrivateKey"` 20 | BSNPublicKey string `json:"bsnPublicKey"` 21 | MspPath string `json:"mspPath"` 22 | } 23 | 24 | // NewConfigFormFile get config from file, if path is empty ,use the ./conf/config.json file in the root directory 25 | func NewConfigFormFile(path string) (*Config, error) { 26 | if path == "" { 27 | path = _DefaultConfigPath 28 | } 29 | 30 | fileBytes, err := file.ReadFile(path) 31 | if err != nil { 32 | return nil, errors.New(fmt.Sprintf("read config file faild:%s", err.Error())) 33 | } 34 | 35 | fileConf := &fileConfig{} 36 | err = json.Unmarshal(fileBytes, fileConf) 37 | if err != nil { 38 | return nil, errors.New(fmt.Sprintf("read config file faild:%s", err.Error())) 39 | } 40 | 41 | if fileConf.MspPath == "" { 42 | fileConf.MspPath = _DefaultMSPPath 43 | } 44 | 45 | return NewConfig(fileConf.NodeApi, 46 | fileConf.UserCode, 47 | fileConf.AppCode, 48 | fileConf.UserPrivateKey, 49 | fileConf.MspPath) 50 | } 51 | -------------------------------------------------------------------------------- /pkg/common/http/http.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | "bytes" 5 | "github.com/wonderivan/logger" 6 | "io/ioutil" 7 | "net/http" 8 | "strings" 9 | ) 10 | 11 | func SendPost(dataBytes []byte, url string) ([]byte, error) { 12 | 13 | var client *http.Client 14 | 15 | tr := new(http.Transport) 16 | tr.DisableKeepAlives = true 17 | client = &http.Client{ 18 | //define the mechanism for a single HTTP request 19 | Transport: tr, 20 | } 21 | 22 | //invoke interface 23 | logger.Debug("request message:", string(dataBytes)) 24 | response, err := client.Post(url, "application/json", bytes.NewReader(dataBytes)) 25 | if err != nil { 26 | logger.Error("request failed:", err.Error()) 27 | return nil, err 28 | } 29 | if response != nil && response.Body != nil { 30 | defer response.Body.Close() 31 | } 32 | //Get the response message data from the response object and read it 33 | allBytes := []byte{} 34 | //buffer 35 | bytes := make([]byte, response.ContentLength) 36 | i, err := response.Body.Read(bytes) 37 | allBytes = append(allBytes, bytes[:i]...) 38 | 39 | for { 40 | i, err = response.Body.Read(bytes) 41 | if i == 0 { 42 | break 43 | } 44 | allBytes = append(allBytes, bytes[:i]...) 45 | } 46 | //response.Body.Close() 47 | logger.Debug("response message:", string(allBytes)) 48 | return allBytes, nil 49 | } 50 | 51 | func readCaCert(cert string) ([]byte, error) { 52 | isFile := strings.Contains(cert, ".crt") 53 | if isFile { 54 | return ioutil.ReadFile(cert) 55 | } else { 56 | return []byte(cert), nil 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fabric/node/blockResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockResData struct { 9 | base.BaseResModel 10 | Body *BlockResDataBody `json:"body"` 11 | } 12 | 13 | type BlockResDataBody struct { 14 | BlockHash string `json:"blockHash"` 15 | BlockNumber uint64 `json:"blockNumber"` 16 | PreBlockHash string `json:"preBlockHash"` 17 | BlockSize uint64 `json:"blockSize"` 18 | BlockTxCount int `json:"blockTxCount"` 19 | 20 | Transactions []*TransactionData `json:"transactions"` 21 | } 22 | 23 | type TransactionData struct { 24 | TxId string `json:"txId"` 25 | Status int `json:"status"` 26 | CreateName string `json:"createName"` 27 | TimeSpanSec int64 `json:"timeSpanSec"` 28 | TimeSpanNsec int64 `json:"timeSpanNsec"` 29 | } 30 | 31 | func (f *BlockResData) GetEncryptionValue() string { 32 | if f.Body == nil { 33 | return f.GetBaseEncryptionValue() 34 | } 35 | 36 | fp := f.GetBaseEncryptionValue() 37 | fp = fp + f.Body.BlockHash 38 | fp = fp + strconv.FormatUint(f.Body.BlockNumber, 10) 39 | fp = fp + f.Body.PreBlockHash 40 | fp = fp + strconv.FormatUint(f.Body.BlockSize, 10) 41 | fp = fp + strconv.Itoa(f.Body.BlockTxCount) 42 | 43 | for _, t := range f.Body.Transactions { 44 | 45 | fp = fp + t.TxId 46 | fp = fp + strconv.Itoa(t.Status) 47 | fp = fp + t.CreateName 48 | fp = fp + strconv.FormatInt(t.TimeSpanSec, 10) 49 | fp = fp + strconv.FormatInt(t.TimeSpanNsec, 10) 50 | 51 | } 52 | 53 | return fp 54 | } 55 | -------------------------------------------------------------------------------- /pkg/core/entity/res/fiscobcos/node/transResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type TransResData struct { 9 | base.BaseResModel 10 | Body *TransResDataDataBody `json:"body"` 11 | } 12 | 13 | type TransResDataDataBody struct { 14 | Constant bool `json:"constant"` 15 | 16 | QueryInfo string `json:"queryInfo"` 17 | 18 | TxId string `json:"txId"` 19 | BlockHash string `json:"blockHash"` 20 | BlockNumber int64 `json:"blockNumber"` 21 | 22 | GasUsed int64 `json:"gasUsed"` 23 | 24 | Status string `json:"status"` 25 | 26 | From string `json:"from"` 27 | To string `json:"to"` 28 | 29 | Input string `json:"input"` 30 | Output string `json:"output"` 31 | EventLogs string `json:"logs"` 32 | } 33 | 34 | func (f *TransResData) getBlockValue() string { 35 | 36 | if f.Body == nil { 37 | return "" 38 | } 39 | 40 | fb := "" 41 | if f.Body.Constant { 42 | fb = fb + "true" 43 | } else { 44 | fb = fb + "false" 45 | } 46 | fb = fb + f.Body.QueryInfo 47 | fb = fb + f.Body.TxId 48 | fb = fb + f.Body.BlockHash 49 | fb = fb + strconv.FormatInt(f.Body.BlockNumber, 10) 50 | fb = fb + strconv.FormatInt(f.Body.GasUsed, 10) 51 | fb = fb + f.Body.Status 52 | fb = fb + f.Body.From 53 | fb = fb + f.Body.To 54 | fb = fb + f.Body.Input 55 | fb = fb + f.Body.Output 56 | fb = fb + f.Body.EventLogs 57 | 58 | return fb 59 | } 60 | 61 | func (f *TransResData) GetEncryptionValue() string { 62 | 63 | return f.GetBaseEncryptionValue() + f.getBlockValue() 64 | 65 | } 66 | -------------------------------------------------------------------------------- /pkg/core/entity/req/fabric/node/transReqData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/fabric" 6 | ) 7 | 8 | type TransReqData struct { 9 | base.BaseReqModel 10 | Body TransReqDataBody `json:"body"` 11 | } 12 | 13 | type TransReqDataBody struct { 14 | UserName string `json:"userName"` 15 | 16 | // Nonce 17 | Nonce string `json:"nonce"` 18 | 19 | ChainCode string `json:"chainCode"` 20 | FuncName string `json:"funcName"` 21 | Args []string `json:"args"` 22 | TransientMap map[string]string `json:"transientData"` 23 | } 24 | 25 | func (f *TransReqData) GetEncryptionValue() string { 26 | 27 | fp := f.GetBaseEncryptionValue() 28 | 29 | fp = fp + f.Body.UserName 30 | fp = fp + f.Body.Nonce 31 | fp = fp + f.Body.ChainCode 32 | fp = fp + f.Body.FuncName 33 | 34 | for _, a := range f.Body.Args { 35 | fp = fp + a 36 | } 37 | 38 | for k, v := range f.Body.TransientMap { 39 | fp = fp + k + v 40 | } 41 | 42 | return fp 43 | 44 | } 45 | 46 | func (t *TransReqDataBody) GetTransRequest(channelId string) *fabric.TransRequest { 47 | request := &fabric.TransRequest{ 48 | ChannelId: channelId, 49 | ChaincodeId: t.ChainCode, 50 | Fcn: t.FuncName, 51 | } 52 | 53 | for _, a := range t.Args { 54 | request.Args = append(request.Args, []byte(a)) 55 | } 56 | request.TransientMap = make(map[string][]byte) 57 | for k, v := range t.TransientMap { 58 | request.TransientMap[k] = []byte(v) 59 | } 60 | 61 | return request 62 | } 63 | -------------------------------------------------------------------------------- /pkg/client/fisco-bcos/fiscobcosClient.go: -------------------------------------------------------------------------------- 1 | package fisco_bcos 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/client" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 8 | "github.com/wonderivan/logger" 9 | "math/big" 10 | "strconv" 11 | ) 12 | 13 | func NewFiscoBcosClient(config *config.Config) (*FiscoBcosClient, error) { 14 | 15 | fiscoBcosClient := &FiscoBcosClient{ 16 | Client: client.Client{ 17 | Config: config, 18 | }, 19 | } 20 | 21 | err := fiscoBcosClient.SetAlgorithm(config.GetAppInfo().AlgorithmType, config.GetAppCert().AppPublicCert, config.GetAppCert().UserAppPrivateCert) 22 | 23 | if err != nil { 24 | logger.Error("signHandle initialization failed") 25 | return nil, err 26 | } 27 | 28 | return fiscoBcosClient, nil 29 | } 30 | 31 | type FiscoBcosClient struct { 32 | client.Client 33 | } 34 | 35 | func (f *FiscoBcosClient) isSM() bool { 36 | return f.Config.GetAppInfo().AlgorithmType == enum.AppAlgorithmType_SM2 37 | } 38 | 39 | func (c *FiscoBcosClient) getBlockLimit() (*big.Int, error) { 40 | res, err := c.GetBlockHeight() 41 | if err != nil { 42 | return nil, err 43 | } 44 | if res.Header.Code != 0 { 45 | return nil, errors.New(res.Header.Msg) 46 | } 47 | 48 | height, err := strconv.ParseInt(res.Body.Data, 10, 64) 49 | if err != nil { 50 | return nil, errors.New("ledger height has error") 51 | } 52 | 53 | height = height + 100 54 | return new(big.Int).SetInt64(height), nil 55 | } 56 | 57 | func (c *FiscoBcosClient) getGroupId() (*big.Int, error) { 58 | groupId, err := strconv.ParseInt(c.Config.GetAppInfo().ChannelId, 10, 64) 59 | 60 | if err != nil { 61 | return nil, err 62 | } 63 | return new(big.Int).SetInt64(groupId), nil 64 | } 65 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/common/common.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019. Baidu Inc. All Rights Reserved. 2 | 3 | // package common is related to common variables and utils funcs 4 | package common 5 | 6 | import ( 7 | "bytes" 8 | "encoding/binary" 9 | "fmt" 10 | "log" 11 | "math/rand" 12 | "os" 13 | "strconv" 14 | "time" 15 | 16 | walletRand "github.com/xuperchain/crypto/core/hdwallet/rand" 17 | ) 18 | 19 | const ( 20 | // TxVersion tx version number 21 | TxVersion = 1 22 | ) 23 | 24 | // GetNonce get nonce value 25 | func GetNonce() string { 26 | return fmt.Sprintf("%d%8d", time.Now().Unix(), rand.Intn(100000000)) 27 | } 28 | 29 | // SetSeed set seed 30 | func SetSeed() error { 31 | // 生成加强版的随机熵 32 | seedByte, err := walletRand.GenerateSeedWithStrengthAndKeyLen(walletRand.KeyStrengthHard, walletRand.KeyLengthInt64) 33 | if err != nil { 34 | return err 35 | } 36 | 37 | // 生成大随机数 38 | bytesBuffer := bytes.NewBuffer(seedByte) 39 | var seed int64 40 | binary.Read(bytesBuffer, binary.BigEndian, &seed) 41 | 42 | // 设置随机数生成器的随机源 43 | rand.Seed(seed) 44 | 45 | return nil 46 | } 47 | 48 | // PathExistsAndMkdir judge whether path is existant or not 49 | func PathExistsAndMkdir(path string) error { 50 | _, err := os.Stat(path) 51 | if err == nil { 52 | return nil 53 | } 54 | err = os.Mkdir(path, os.ModePerm) 55 | if err != nil { 56 | return err 57 | } 58 | return nil 59 | } 60 | 61 | // IsValidAmount judge whether the number is legal 62 | func IsValidAmount(amount string) (string, bool) { 63 | if amount == "" { 64 | amount = "0" 65 | return amount, true 66 | } 67 | 68 | amountInt64, err := strconv.ParseInt(amount, 10, 64) 69 | if err != nil { 70 | log.Printf("Transfer amount to int64 err: %v", err) 71 | return "", false 72 | } 73 | 74 | if amountInt64 < 0 { 75 | log.Printf("Transfer amount is negative") 76 | return "", false 77 | } 78 | 79 | return amount, true 80 | } 81 | -------------------------------------------------------------------------------- /pkg/client/client.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/sign" 8 | "github.com/BSNDA/bsn-sdk-crypto/key" 9 | crySign "github.com/BSNDA/bsn-sdk-crypto/sign" 10 | "github.com/pkg/errors" 11 | "github.com/wonderivan/logger" 12 | ) 13 | 14 | type Client struct { 15 | Config *config.Config 16 | sign sign.Crypto 17 | } 18 | 19 | func (c *Client) SetAlgorithm(algorithmType enum.App_AlgorithmType, puk, pri string) error { 20 | 21 | kt := algorithmType.ToKeyType() 22 | 23 | privKey, err := key.NewPrivateKeyProvider(kt, pri) 24 | if err != nil { 25 | return errors.WithMessagef(err, "new [%s] private key provider key has error", kt.String()) 26 | } 27 | 28 | pubKey, err := key.NewPublicProvider(kt, puk) 29 | if err != nil { 30 | return errors.WithMessagef(err, "new [%s] public key provider key has error", kt.String()) 31 | } 32 | 33 | sh, err := crySign.NewSignProvider(crySign.WithPrivateKey(privKey), crySign.WithPublicKey(pubKey)) 34 | if err != nil { 35 | return errors.WithMessagef(err, "new [%s] sign provider has error", kt.String()) 36 | } 37 | 38 | c.sign = sign.NewCrypto(sh) 39 | return nil 40 | 41 | } 42 | 43 | func (c *Client) GetHeader() base.ReqHeader { 44 | return c.Config.GetReqHeader() 45 | } 46 | 47 | func (c *Client) GetURL(url string) string { 48 | return c.Config.GetNodeApi() + url 49 | } 50 | 51 | func (c *Client) Sign(data string) string { 52 | 53 | mac, err := c.sign.Sign(data) 54 | 55 | if err != nil { 56 | logger.Error("Exception in signature : %s", err.Error()) 57 | } 58 | 59 | return mac 60 | } 61 | 62 | func (c *Client) Verify(mac, data string) bool { 63 | if mac == "" { 64 | return true 65 | } 66 | return c.sign.Verify(mac, data) 67 | 68 | } 69 | -------------------------------------------------------------------------------- /pkg/client/cita/citaClient.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/client" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 9 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 10 | "github.com/wonderivan/logger" 11 | ) 12 | 13 | //initialize client requested by cita 14 | func NewCitaClient(config *config.Config) (*CitaClient, error) { 15 | citaClient := &CitaClient{ 16 | Client: client.Client{ 17 | Config: config, 18 | }, 19 | } 20 | 21 | err := citaClient.SetAlgorithm(config.GetAppInfo().AlgorithmType, config.GetAppCert().AppPublicCert, config.GetAppCert().UserAppPrivateCert) 22 | 23 | if err != nil { 24 | logger.Error("signHandle initialization failed") 25 | return nil, err 26 | } 27 | 28 | return citaClient, nil 29 | } 30 | 31 | type CitaClient struct { 32 | client.Client 33 | } 34 | 35 | func (f *CitaClient) isSM() bool { 36 | return f.Config.GetAppInfo().AlgorithmType == enum.AppAlgorithmType_SM2 37 | } 38 | 39 | //get transaction block limit 40 | func (c *CitaClient) getBlockLimit() (uint64, error) { 41 | res, err := c.GetBlockHeight() 42 | if err != nil { 43 | return 0, err 44 | } 45 | if res.Header.Code != 0 { 46 | return 0, errors.New(res.Header.Msg) 47 | } 48 | 49 | height, err := strconv.ParseUint(res.Body.Data, 10, 64) 50 | if err != nil { 51 | return 0, errors.New("ledger height has error") 52 | } 53 | 54 | height = height + 80 55 | return height, nil 56 | } 57 | 58 | //get basic information 59 | func (c *CitaClient) getBaseInfo() (string, uint32, error) { 60 | 61 | chainId := c.Config.GetAppInfo().ChannelId 62 | if !has0xPrefix(chainId) { 63 | chainId = "0x" + chainId 64 | } 65 | 66 | //chainId:="0x675" 67 | version, err := strconv.ParseUint(c.Config.GetAppInfo().Version, 10, 64) 68 | if err != nil { 69 | return "", 0, err 70 | } 71 | return chainId, uint32(version), nil 72 | } 73 | 74 | //check if it starts with 0x 75 | func has0xPrefix(input string) bool { 76 | return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') 77 | } 78 | -------------------------------------------------------------------------------- /pkg/core/config/mockConfig.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | _MspDir = "D:/test/bsn-sdk-go/msp" 5 | _HttpsCert = "D:/github.com/BSNDA/PCNGateway-Go-SDK/test/cert/bsn_gateway_https.crt" 6 | ) 7 | 8 | func NewMockFabricConfig() (*Config, error) { 9 | api := "http://192.168.1.43:17502" 10 | userCode := "USER0001202007101641243516163" 11 | appCode := "app0001202012111600499234472" 12 | 13 | privK := `-----BEGIN PRIVATE KEY----- 14 | MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgfPng3pvsulMoOLNj 15 | LT5IUX0wXZQ7RRIgxQ6VGSDneOKgCgYIKoZIzj0DAQehRANCAAS+iGu+3yofOh0H 16 | 74MQJQRivCXi6LtQGkrBe5NXAwL+8wAy+4iaESnIFsDFC2fr2qMgvd005UdvJeJu 17 | VQTCefws 18 | -----END PRIVATE KEY-----` 19 | SetTest() 20 | return NewConfig(api, userCode, appCode, privK, _MspDir) 21 | } 22 | 23 | func NewMockFiscoConfig() (*Config, error) { 24 | api := "http://beijingnode.bsngate.com:17502" 25 | userCode := "USER0001202007161739119605411" 26 | appCode := "app0001202007291443281737652" 27 | 28 | privK := `-----BEGIN PRIVATE KEY----- 29 | MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg/7RMFXO8U9LyrTJW 30 | EZ3gtdUI5A5K+yPAEb3iiPe7bKegCgYIKoEcz1UBgi2hRANCAASvJdHvty4qiZ2r 31 | xcDYrMrgskyr6vthAy/Tgz/3S6SR/9ERuYVLh+Hzb6ptpIWHo0ek5j05ERh5vSzC 32 | PIXILYkE 33 | -----END PRIVATE KEY-----` 34 | 35 | return NewConfig(api, userCode, appCode, privK, _MspDir) 36 | } 37 | 38 | func NewMockXuperchainConfig() (*Config, error) { 39 | api := "http://192.168.1.43:17502" 40 | userCode := "USER0001202010201539390086090" 41 | appCode := "app0001202010221038364886804" 42 | 43 | privK := `-----BEGIN PRIVATE KEY----- 44 | MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgikcrsA9vRp14VAl0 45 | lhNmOMc7pl0j4xlF9Eno+eJNgSegCgYIKoEcz1UBgi2hRANCAAQuR25rig9+Isir 46 | q7eapxSsDCo8FCdt0qfCa7eGCC7BEdGerbX4qa5j3qljl1/d6I00c7veFAvgGPP8 47 | DFT+md7r 48 | -----END PRIVATE KEY-----` 49 | 50 | return NewConfig(api, userCode, appCode, privK, _MspDir) 51 | } 52 | func NewMockCitaConfig() (*Config, error) { 53 | api := "http://192.168.1.43:17502" 54 | userCode := "xiaoliu" 55 | appCode := "app0001202012111600499234472" 56 | 57 | privK := `-----BEGIN PRIVATE KEY----- 58 | MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgfPng3pvsulMoOLNj 59 | LT5IUX0wXZQ7RRIgxQ6VGSDneOKgCgYIKoZIzj0DAQehRANCAAS+iGu+3yofOh0H 60 | 74MQJQRivCXi6LtQGkrBe5NXAwL+8wAy+4iaESnIFsDFC2fr2qMgvd005UdvJeJu 61 | VQTCefws 62 | -----END PRIVATE KEY-----` 63 | return NewConfig(api, userCode, appCode, privK, _MspDir) 64 | } 65 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_event.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | resBase "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | eventreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/event" 6 | eventres "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/fabric/event" 7 | "github.com/pkg/errors" 8 | ) 9 | 10 | const ( 11 | EventRegister = "chainCode/event/register" 12 | BlockEventRegister = "chainCode/event/blockRegister" 13 | EventQuery = "chainCode/event/query" 14 | EventRemove = "chainCode/event/remove" 15 | ) 16 | 17 | // EventRegister register fabric transaction event listeners 18 | func (c *FabricClient) EventRegister(body eventreq.RegisterReqDataBody) (*eventres.RegisterResData, error) { 19 | 20 | req := &eventreq.RegisterReqData{} 21 | req.Header = c.GetHeader() 22 | req.Body = body 23 | 24 | res := &eventres.RegisterResData{} 25 | 26 | err := c.Call(EventRegister, req, res) 27 | if err != nil { 28 | return nil, errors.WithMessagef(err, "call %s has error", EventRegister) 29 | } 30 | return res, nil 31 | } 32 | 33 | // BlockEventRegister register fabric block event listeners 34 | func (c *FabricClient) BlockEventRegister(body eventreq.RegisterReqDataBody) (*eventres.RegisterResData, error) { 35 | 36 | req := &eventreq.RegisterReqData{} 37 | req.Header = c.GetHeader() 38 | req.Body = body 39 | 40 | res := &eventres.RegisterResData{} 41 | 42 | err := c.Call(BlockEventRegister, req, res) 43 | if err != nil { 44 | return nil, errors.WithMessagef(err, "call %s has error", BlockEventRegister) 45 | } 46 | return res, nil 47 | } 48 | 49 | // EventQuery query fabric event list 50 | func (c *FabricClient) EventQuery() (*eventres.QueryResData, error) { 51 | 52 | req := &eventreq.QueryReqData{} 53 | req.Header = c.GetHeader() 54 | 55 | res := &eventres.QueryResData{} 56 | 57 | err := c.Call(EventQuery, req, res) 58 | if err != nil { 59 | return nil, errors.WithMessagef(err, "call %s has error", EventQuery) 60 | } 61 | return res, nil 62 | } 63 | 64 | // EventRemove remove fabric event 65 | func (c *FabricClient) EventRemove(body eventreq.RemoveReqDataBody) (*resBase.BaseResModel, error) { 66 | 67 | req := &eventreq.RemoveReqData{} 68 | req.Header = c.GetHeader() 69 | req.Body = body 70 | 71 | res := &resBase.BaseResModel{} 72 | 73 | err := c.Call(EventRemove, req, res) 74 | 75 | if err != nil { 76 | return nil, errors.WithMessagef(err, "call %s has error", EventRemove) 77 | } 78 | return res, nil 79 | } 80 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/pb/chainedbft.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package pb; 4 | 5 | // QCState is the phase of hotstuff 6 | enum QCState { 7 | NEW_VIEW = 0; 8 | PREPARE = 1; 9 | PRE_COMMIT = 2; 10 | COMMIT = 3; 11 | DECIDE = 4; 12 | } 13 | 14 | // QuorumCert is a data type that combines a collection of signatures from replicas. 15 | message QuorumCert { 16 | // The id of Proposal this QC certified. 17 | bytes ProposalId = 1; 18 | // The msg of Proposal this QC certified. 19 | bytes ProposalMsg = 2; 20 | // The current type of this QC certified. 21 | // the type contains `NEW_VIEW`, `PREPARE` 22 | QCState Type = 3; 23 | // The view number of this QC certified. 24 | int64 ViewNumber = 4; 25 | // SignInfos is the signs of the leader gathered from replicas 26 | // of a specifically certType. 27 | QCSignInfos SignInfos = 5; 28 | } 29 | 30 | // QCSignInfos is the signs of the leader gathered from replicas of a specifically certType. 31 | // A slice of signs is used at present. 32 | // TODO @qizheng09: It will be change to Threshold-Signatures after 33 | // Crypto lib support Threshold-Signatures. 34 | message QCSignInfos { 35 | // QCSignInfos 36 | repeated SignInfo QCSignInfos = 1; 37 | } 38 | 39 | // SignInfo is the signature information of the 40 | message SignInfo { 41 | string Address = 1; 42 | string PublicKey = 2; 43 | bytes Sign = 3; 44 | } 45 | 46 | // ChainedBftPhaseMessage is the proposal message of the protocal. 47 | // In Hotstuff, there are two kinds of messages, "NEW_VIEW_MESSAGE" and "QC_Message". 48 | // A stable leader can skip this "NEW_VIEW_MESSAGE". 49 | message ChainedBftPhaseMessage { 50 | // Message Type: NEW_VIEW_MESSAGE or QC_MESSAGE 51 | QCState Type = 1; 52 | // ViewNumber the current view number 53 | int64 ViewNumber = 2; 54 | // The new proposal send to other replicas while the 55 | QuorumCert ProposalQC = 3; 56 | // JustifyQC is the QC of the leader gathered, send to next leader, while the message type is "NEW_VIEW_MESSAGE" 57 | QuorumCert JustifyQC = 4; 58 | // MsgDigest is the digest of the msgg 59 | bytes MsgDigest = 5; 60 | // Signature for this msg 61 | SignInfo Signature = 6; 62 | } 63 | 64 | // ChainedBftVoteMessage is the vote message of the protocal. 65 | message ChainedBftVoteMessage { 66 | // The id of this message votes for. 67 | bytes ProposalId = 1; 68 | // Replica will sign the QCMessage if the QuorumCert if valid. 69 | SignInfo Signature = 2; 70 | } -------------------------------------------------------------------------------- /pkg/common/file/file.go: -------------------------------------------------------------------------------- 1 | package file 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 5 | "github.com/wonderivan/logger" 6 | "io/ioutil" 7 | "os" 8 | path2 "path" 9 | "strings" 10 | ) 11 | 12 | func ReadFile(path string) ([]byte, error) { 13 | if _, err1 := os.Stat(path); os.IsNotExist(err1) { 14 | return nil, errors.New("file not found") 15 | } 16 | 17 | bytes, err := ioutil.ReadFile(path) // nolint: gas 18 | if err != nil { 19 | return nil, err 20 | } 21 | if bytes == nil { 22 | return nil, errors.New("file not found") 23 | } 24 | return bytes, nil 25 | 26 | } 27 | 28 | // WriteFile cover true 覆盖文件,false 检查是否已存在 29 | func WriteFile(data []byte, path string, cover bool) error { 30 | 31 | if !cover { 32 | if _, err1 := os.Stat(path); !os.IsNotExist(err1) { 33 | return errors.New("file is exist") 34 | } 35 | } 36 | 37 | err := os.MkdirAll(path2.Dir(path), 0700) 38 | if err != nil { 39 | return err 40 | } 41 | return ioutil.WriteFile(path, data, 0600) 42 | 43 | } 44 | 45 | //获取指定目录下的所有文件和目录 46 | func GetFilesAndDirs(dirPth string) (files []string, dirs []string, err error) { 47 | dir, err := ioutil.ReadDir(dirPth) 48 | if err != nil { 49 | return nil, nil, err 50 | } 51 | 52 | PthSep := string(os.PathSeparator) 53 | //suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写 54 | 55 | for _, fi := range dir { 56 | if fi.IsDir() { // 目录, 递归遍历 57 | dirs = append(dirs, dirPth+PthSep+fi.Name()) 58 | GetFilesAndDirs(dirPth + PthSep + fi.Name()) 59 | } else { 60 | // 过滤指定格式 61 | ok := strings.HasSuffix(fi.Name(), ".go") 62 | if ok { 63 | files = append(files, dirPth+PthSep+fi.Name()) 64 | } 65 | } 66 | } 67 | 68 | return files, dirs, nil 69 | } 70 | 71 | //获取指定目录下的指定后缀的文件,不包含子目录下的文件 72 | func GetAllFiles(dirPth, fix string) (files []string, err error) { 73 | dir, err := ioutil.ReadDir(dirPth) 74 | if err != nil { 75 | return nil, err 76 | } 77 | 78 | PthSep := string(os.PathListSeparator) 79 | //suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写 80 | 81 | for _, fi := range dir { 82 | if !fi.IsDir() { 83 | // 过滤指定格式 84 | ok := strings.HasSuffix(fi.Name(), fix) 85 | if ok { 86 | files = append(files, dirPth+PthSep+fi.Name()) 87 | } 88 | } 89 | } 90 | 91 | return files, nil 92 | } 93 | 94 | func CheckDir(path string) { 95 | if _, err1 := os.Stat(path); !os.IsNotExist(err1) { 96 | return 97 | } 98 | 99 | err := os.MkdirAll(path, os.ModePerm) 100 | if err != nil { 101 | logger.Warn("path [%s] create failed : %s", path, err.Error()) 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /pkg/client/cita/citaClient_event.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 7 | eventreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/cita/event" 8 | eventres "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/cita/event" 9 | "github.com/wonderivan/logger" 10 | ) 11 | 12 | //register cita event listeners 13 | func (c *CitaClient) EventRegister(body eventreq.RegisterReqDataBody) (*eventres.RegisterEventResData, error) { 14 | url := c.GetURL("/api/cita/v1/event/register") 15 | 16 | data := &eventreq.RegisterReqData{} 17 | data.Header = c.GetHeader() 18 | data.Body = body 19 | data.Mac = c.Sign(data.GetEncryptionValue()) 20 | 21 | reqBytes, _ := json.Marshal(data) 22 | 23 | resBytes, err := http.SendPost(reqBytes, url) 24 | if err != nil { 25 | logger.Error("gateway interface call failed:", err) 26 | return nil, err 27 | } 28 | res := &eventres.RegisterEventResData{} 29 | 30 | err = json.Unmarshal(resBytes, res) 31 | 32 | if err != nil { 33 | logger.Error("return parameter serialization failed:", err) 34 | return nil, err 35 | } 36 | 37 | return res, nil 38 | } 39 | 40 | //query event list 41 | func (c *CitaClient) EventQuery() (*eventres.QueryEventResData, error) { 42 | url := c.GetURL("/api/cita/v1/event/query") 43 | 44 | data := &eventreq.QueryReqData{} 45 | data.Header = c.GetHeader() 46 | 47 | data.Mac = c.Sign(data.GetEncryptionValue()) 48 | 49 | reqBytes, _ := json.Marshal(data) 50 | 51 | resBytes, err := http.SendPost(reqBytes, url) 52 | if err != nil { 53 | logger.Error("gateway interface call failed:", err) 54 | return nil, err 55 | } 56 | res := &eventres.QueryEventResData{} 57 | 58 | err = json.Unmarshal(resBytes, res) 59 | 60 | if err != nil { 61 | logger.Error("return parameter serialization failed:", err) 62 | return nil, err 63 | } 64 | 65 | return res, nil 66 | } 67 | 68 | //remove event 69 | func (c *CitaClient) EventRemove(body eventreq.RemoveReqDataBody) (*eventres.RemoveEventResData, error) { 70 | url := c.GetURL("/api/cita/v1/event/remove") 71 | 72 | data := &eventreq.RemoveReqData{} 73 | data.Header = c.GetHeader() 74 | data.Body = body 75 | data.Mac = c.Sign(data.GetEncryptionValue()) 76 | 77 | reqBytes, _ := json.Marshal(data) 78 | 79 | resBytes, err := http.SendPost(reqBytes, url) 80 | if err != nil { 81 | logger.Error("gateway interface call failed:", err) 82 | return nil, err 83 | } 84 | res := &eventres.RemoveEventResData{} 85 | 86 | err = json.Unmarshal(resBytes, res) 87 | 88 | if err != nil { 89 | logger.Error("return parameter serialization failed:", err) 90 | return nil, err 91 | } 92 | 93 | return res, nil 94 | } 95 | -------------------------------------------------------------------------------- /pkg/util/keystore/fileusercertstore.go: -------------------------------------------------------------------------------- 1 | package keystore 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/file" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/msp" 7 | "io/ioutil" 8 | "os" 9 | path2 "path" 10 | "strings" 11 | ) 12 | 13 | func NewUserCertStore(path string) UserCertStore { 14 | 15 | file.CheckDir(path) 16 | 17 | us := &FileUserCertStore{ 18 | FilePath: path, 19 | } 20 | 21 | return us 22 | } 23 | 24 | type FileUserCertStore struct { 25 | FilePath string 26 | } 27 | 28 | func (f *FileUserCertStore) Load(user *msp.UserData) error { 29 | key := storeKeyName(user) 30 | filePath := path2.Join(f.FilePath, key) 31 | 32 | if _, err1 := os.Stat(filePath); os.IsNotExist(err1) { 33 | return errors.New("user not found") 34 | } 35 | 36 | bytes, err := ioutil.ReadFile(filePath) // nolint: gas 37 | if err != nil { 38 | return err 39 | } 40 | if bytes == nil { 41 | return errors.New("user not found") 42 | } 43 | user.EnrollmentCertificate = bytes 44 | return nil 45 | 46 | } 47 | 48 | func (f *FileUserCertStore) Store(user *msp.UserData) error { 49 | key := storeKeyName(user) 50 | 51 | path := path2.Join(f.FilePath, key) 52 | 53 | valueBytes := user.EnrollmentCertificate 54 | 55 | err := os.MkdirAll(path2.Dir(path), 0700) 56 | if err != nil { 57 | return err 58 | } 59 | return ioutil.WriteFile(path, valueBytes, 0600) 60 | 61 | } 62 | 63 | func (f *FileUserCertStore) LoadAll(appCode string) []*msp.UserData { 64 | 65 | var users []*msp.UserData 66 | 67 | //Traverse files under the folder 68 | files, err := ioutil.ReadDir(f.FilePath) 69 | if err != nil { 70 | return users 71 | } 72 | 73 | for _, file := range files { 74 | filePath := path2.Join(f.FilePath, file.Name()) 75 | 76 | //get the file name 77 | name := getPemName(file.Name(), appCode) 78 | if name != "" { 79 | //get 80 | user := &msp.UserData{} 81 | bytes, err := ioutil.ReadFile(filePath) // nolint: gas 82 | if err == nil && bytes != nil { 83 | user.EnrollmentCertificate = bytes 84 | user.UserName = name 85 | user.AppCode = appCode 86 | users = append(users, user) 87 | } 88 | } 89 | } 90 | 91 | return users 92 | 93 | } 94 | 95 | func getPemName(name, appCode string) string { 96 | 97 | ext := "@" + appCode + "-cert.pem" 98 | 99 | i := strings.Index(name, ext) 100 | if i != -1 { 101 | return name[:i] 102 | } else { 103 | return "" 104 | } 105 | } 106 | 107 | func storeKeyName(user *msp.UserData) string { 108 | return user.UserName + "@" + user.AppCode + "-cert.pem" 109 | } 110 | -------------------------------------------------------------------------------- /pkg/client/fisco-bcos/fiscobcosClient_event.go: -------------------------------------------------------------------------------- 1 | package fisco_bcos 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 6 | eventreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fiscobcos/event" 7 | eventres "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/fiscobcos/event" 8 | "github.com/wonderivan/logger" 9 | ) 10 | 11 | // EventRegister register fisco bcos transaction or block event listeners 12 | func (c *FiscoBcosClient) EventRegister(body eventreq.RegisterReqDataBody) (*eventres.RegisterEventResData, error) { 13 | url := c.GetURL("/api/fiscobcos/v1/event/register") 14 | 15 | data := &eventreq.RegisterReqData{} 16 | data.Header = c.GetHeader() 17 | data.Body = body 18 | data.Mac = c.Sign(data.GetEncryptionValue()) 19 | 20 | reqBytes, _ := json.Marshal(data) 21 | 22 | resBytes, err := http.SendPost(reqBytes, url) 23 | if err != nil { 24 | logger.Error("gateway interface call failed:", err) 25 | return nil, err 26 | } 27 | res := &eventres.RegisterEventResData{} 28 | 29 | err = json.Unmarshal(resBytes, res) 30 | 31 | if err != nil { 32 | logger.Error("return parameter serialization failed:", err) 33 | return nil, err 34 | } 35 | 36 | return res, nil 37 | } 38 | 39 | // EventQuery query fisco bcos event list 40 | func (c *FiscoBcosClient) EventQuery() (*eventres.QueryEventResData, error) { 41 | url := c.GetURL("/api/fiscobcos/v1/event/query") 42 | 43 | data := &eventreq.QueryReqData{} 44 | data.Header = c.GetHeader() 45 | 46 | data.Mac = c.Sign(data.GetEncryptionValue()) 47 | 48 | reqBytes, _ := json.Marshal(data) 49 | 50 | resBytes, err := http.SendPost(reqBytes, url) 51 | if err != nil { 52 | logger.Error("gateway interface call failed:", err) 53 | return nil, err 54 | } 55 | res := &eventres.QueryEventResData{} 56 | 57 | err = json.Unmarshal(resBytes, res) 58 | 59 | if err != nil { 60 | logger.Error("return parameter serialization failed:", err) 61 | return nil, err 62 | } 63 | 64 | return res, nil 65 | } 66 | 67 | // EventRemove remove fisco bcos event 68 | func (c *FiscoBcosClient) EventRemove(body eventreq.RemoveReqDataBody) (*eventres.RemoveEventResData, error) { 69 | url := c.GetURL("/api/fiscobcos/v1/event/remove") 70 | 71 | data := &eventreq.RemoveReqData{} 72 | data.Header = c.GetHeader() 73 | data.Body = body 74 | data.Mac = c.Sign(data.GetEncryptionValue()) 75 | 76 | reqBytes, _ := json.Marshal(data) 77 | 78 | resBytes, err := http.SendPost(reqBytes, url) 79 | if err != nil { 80 | logger.Error("gateway interface call failed:", err) 81 | return nil, err 82 | } 83 | res := &eventres.RemoveEventResData{} 84 | 85 | err = json.Unmarshal(resBytes, res) 86 | 87 | if err != nil { 88 | logger.Error("return parameter serialization failed:", err) 89 | return nil, err 90 | } 91 | 92 | return res, nil 93 | } 94 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchain_event.go: -------------------------------------------------------------------------------- 1 | package xuperchain 2 | 3 | import ( 4 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/xuperchain/event" 5 | res "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/xuperchain/event" 6 | 7 | "encoding/json" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 9 | "github.com/wonderivan/logger" 10 | ) 11 | 12 | //register event 13 | func (c *XuperChainClient) RegisterEvent(body req.RegisterEventReqDataBody) (*res.QueryEventResData, error) { 14 | 15 | url := c.GetURL("/api/xuperchain/v1/event/register") 16 | 17 | data := &req.RegisterEventReqData{} 18 | data.Header = c.GetHeader() 19 | data.Body = body 20 | data.Mac = c.Sign(data.GetEncryptionValue()) 21 | 22 | reqBytes, _ := json.Marshal(data) 23 | 24 | resBytes, err := http.SendPost(reqBytes, url) 25 | 26 | if err != nil { 27 | logger.Error("gateway interface call failed:", err) 28 | return nil, err 29 | } 30 | 31 | res := &res.QueryEventResData{} 32 | 33 | err = json.Unmarshal(resBytes, res) 34 | if err != nil { 35 | logger.Error("return parameter serialization failed:", err) 36 | return nil, err 37 | } 38 | 39 | return res, nil 40 | } 41 | 42 | //query event list 43 | func (c *XuperChainClient) QueryEvent() (*res.QueryEventResData, error) { 44 | 45 | url := c.GetURL("/api/xuperchain/v1/event/query") 46 | 47 | data := &req.QueryEventReqData{} 48 | data.Header = c.GetHeader() 49 | //data.Body = body 50 | data.Mac = c.Sign(data.GetEncryptionValue()) 51 | 52 | reqBytes, _ := json.Marshal(data) 53 | 54 | resBytes, err := http.SendPost(reqBytes, url) 55 | 56 | if err != nil { 57 | logger.Error("gateway interface call failed:", err) 58 | return nil, err 59 | } 60 | 61 | res := &res.QueryEventResData{} 62 | 63 | err = json.Unmarshal(resBytes, res) 64 | 65 | if err != nil { 66 | logger.Error("return parameter serialization failed:", err) 67 | return nil, err 68 | } 69 | 70 | return res, nil 71 | } 72 | 73 | //remove event 74 | func (c *XuperChainClient) RemoveEvent(body req.RemoveEventReqDataBody) (*res.RemoveEventResData, error) { 75 | 76 | url := c.GetURL("/api/xuperchain/v1/event/remove") 77 | 78 | data := &req.RemoveEventReqData{} 79 | data.Header = c.GetHeader() 80 | data.Body = body 81 | data.Mac = c.Sign(data.GetEncryptionValue()) 82 | 83 | reqBytes, _ := json.Marshal(data) 84 | 85 | resBytes, err := http.SendPost(reqBytes, url) 86 | 87 | if err != nil { 88 | logger.Error("gateway interface call failed:", err) 89 | return nil, err 90 | } 91 | 92 | res := &res.RemoveEventResData{} 93 | 94 | err = json.Unmarshal(resBytes, res) 95 | 96 | if err != nil { 97 | logger.Error("return parameter serialization failed:", err) 98 | return nil, err 99 | } 100 | 101 | return res, nil 102 | } 103 | -------------------------------------------------------------------------------- /pkg/core/trans/cita/pb/blockchain.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package pb; 3 | enum ProofType { 4 | AuthorityRound = 0; 5 | Raft = 1; 6 | Bft = 2; 7 | } 8 | 9 | message Proof { 10 | bytes content = 1; 11 | ProofType type = 2; 12 | } 13 | 14 | message BlockHeader { 15 | bytes prevhash = 1; 16 | uint64 timestamp = 2; 17 | uint64 height = 3; 18 | bytes state_root = 4; 19 | bytes transactions_root = 5; 20 | bytes receipts_root = 6; 21 | uint64 quota_used = 7; 22 | uint64 quota_limit = 8; 23 | Proof proof = 9; 24 | bytes proposer = 10; 25 | } 26 | 27 | message Status { 28 | bytes hash = 1; 29 | uint64 height = 2; 30 | } 31 | 32 | message AccountGasLimit { 33 | uint64 common_quota_limit = 1; 34 | map specific_quota_limit = 2; 35 | } 36 | 37 | message RichStatus { 38 | bytes hash = 1; 39 | uint64 height = 2; 40 | repeated bytes nodes = 3; 41 | uint64 interval = 4; 42 | uint32 version = 5; 43 | repeated bytes validators = 6; 44 | } 45 | 46 | enum Crypto { 47 | DEFAULT = 0; 48 | RESERVED = 1; 49 | } 50 | 51 | message Transaction { 52 | string to = 1; 53 | string nonce = 2; 54 | uint64 quota = 3; 55 | uint64 valid_until_block = 4; 56 | bytes data = 5; 57 | bytes value = 6; 58 | uint32 chain_id = 7; 59 | uint32 version = 8; 60 | bytes to_v1 = 9; 61 | bytes chain_id_v1 = 10; 62 | } 63 | 64 | message UnverifiedTransaction { 65 | Transaction transaction = 1; 66 | bytes signature = 2; 67 | Crypto crypto = 3; 68 | } 69 | 70 | message SignedTransaction { 71 | UnverifiedTransaction transaction_with_sig = 1; 72 | // SignedTransaction hash 73 | bytes tx_hash = 2; 74 | // public key 75 | bytes signer = 3; 76 | } 77 | 78 | // data precompile API 79 | 80 | message BlockBody { 81 | repeated SignedTransaction transactions = 1; 82 | } 83 | 84 | message CompactBlockBody { 85 | repeated bytes tx_hashes = 1; 86 | } 87 | 88 | message Block { 89 | uint32 version = 1; 90 | BlockHeader header = 2; 91 | BlockBody body = 3; 92 | } 93 | 94 | message CompactBlock { 95 | uint32 version = 1; 96 | BlockHeader header = 2; 97 | CompactBlockBody body = 3; 98 | } 99 | 100 | message BlockWithProof { 101 | Block blk = 1; 102 | Proof proof = 2; 103 | } 104 | 105 | message BlockTxs { 106 | uint64 height = 1; 107 | BlockBody body = 3; 108 | } 109 | 110 | message BlackList { 111 | // black list of address, the account that sent the transaction does not have enough gas 112 | repeated bytes black_list = 1; 113 | // clear list of address 114 | repeated bytes clear_list = 2; 115 | } 116 | 117 | // State positioning signal 118 | message StateSignal { 119 | uint64 height = 1; 120 | } -------------------------------------------------------------------------------- /pkg/client/cita/citaClient_user.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/BSNDA/bsn-sdk-crypto/key" 7 | "io/ioutil" 8 | "os" 9 | "path" 10 | 11 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 12 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 13 | userReq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/cita/user" 14 | userRes "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/cita/user" 15 | "github.com/wonderivan/logger" 16 | ) 17 | 18 | //register user 19 | func (c *CitaClient) RegisterUser(body userReq.RegisterReqDataBody) (*userRes.RegisterResData, error) { 20 | 21 | url := c.GetURL("/api/cita/v1/user/register") 22 | 23 | data := &userReq.RegisterReqData{} 24 | data.Header = c.GetHeader() 25 | data.Body = body 26 | data.Mac = c.Sign(data.GetEncryptionValue()) 27 | 28 | reqBytes, _ := json.Marshal(data) 29 | 30 | resBytes, err := http.SendPost(reqBytes, url) 31 | 32 | if err != nil { 33 | logger.Error("gateway interface call failed:", err) 34 | return nil, err 35 | } 36 | 37 | res := &userRes.RegisterResData{} 38 | 39 | err = json.Unmarshal(resBytes, res) 40 | if err != nil { 41 | logger.Error("return parameter serialization failed:", err) 42 | return nil, err 43 | } 44 | //if !c.Verify(res.Mac, res.GetEncryptionValue()) { 45 | // return nil, errors.New("sign has error") 46 | //} 47 | 48 | return res, nil 49 | } 50 | 51 | func (c *CitaClient) getUser(userName string) (key.PrivateKeyProvider, error) { 52 | userPath := c.Config.GetKSPath() 53 | 54 | fileName := getKeyFileName(userName, c.Config.GetAppInfo().AppCode) 55 | 56 | filePath := path.Join(userPath, fileName) 57 | 58 | if _, err1 := os.Stat(filePath); os.IsNotExist(err1) { 59 | //create key 60 | key, err := key.NewPrivateKeyByGen(c.Config.GetAppInfo().AlgorithmType.ToKeyType()) 61 | if err != nil { 62 | return nil, err 63 | } 64 | 65 | ketBytes, err := key.KeyPEM() 66 | if err != nil { 67 | return nil, err 68 | } 69 | err = storeKey(ketBytes, filePath) 70 | if err != nil { 71 | return nil, err 72 | } 73 | return key, nil 74 | 75 | } else { 76 | bytes, err := ioutil.ReadFile(filePath) // nolint: gas 77 | if err != nil { 78 | return nil, err 79 | } 80 | if bytes == nil { 81 | return nil, errors.New("user key error") 82 | } 83 | 84 | k, err := key.NewPrivateKeyProvider(c.Config.GetAppInfo().AlgorithmType.ToKeyType(), string(bytes)) 85 | 86 | return k, err 87 | 88 | } 89 | 90 | } 91 | 92 | func storeKey(keyBytes []byte, filePath string) error { 93 | 94 | err := os.MkdirAll(path.Dir(filePath), 0700) 95 | if err != nil { 96 | return err 97 | } 98 | return ioutil.WriteFile(filePath, keyBytes, 0600) 99 | } 100 | 101 | func getKeyFileName(name string, appCode string) string { 102 | return fmt.Sprintf("%s@%s_pk", name, appCode) 103 | } 104 | -------------------------------------------------------------------------------- /pkg/client/fisco-bcos/fiscobcosClient_user.go: -------------------------------------------------------------------------------- 1 | package fisco_bcos 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 8 | userReq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fiscobcos/user" 9 | userRes "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/fiscobcos/user" 10 | "github.com/BSNDA/bsn-sdk-crypto/key" 11 | "github.com/wonderivan/logger" 12 | "io/ioutil" 13 | "os" 14 | "path" 15 | ) 16 | 17 | // RegisterUser register sub user 18 | func (c *FiscoBcosClient) RegisterUser(body userReq.RegisterReqDataBody) (*userRes.RegisterResData, error) { 19 | 20 | url := c.GetURL("/api/fiscobcos/v1/user/register") 21 | 22 | data := &userReq.RegisterReqData{} 23 | data.Header = c.GetHeader() 24 | data.Body = body 25 | data.Mac = c.Sign(data.GetEncryptionValue()) 26 | 27 | reqBytes, _ := json.Marshal(data) 28 | 29 | resBytes, err := http.SendPost(reqBytes, url) 30 | 31 | if err != nil { 32 | logger.Error("gateway interface call failed:", err) 33 | return nil, err 34 | } 35 | 36 | res := &userRes.RegisterResData{} 37 | 38 | err = json.Unmarshal(resBytes, res) 39 | if err != nil { 40 | logger.Error("return parameter serialization failed:", err) 41 | return nil, err 42 | } 43 | if !c.Verify(res.Mac, res.GetEncryptionValue()) { 44 | return nil, errors.New("sign has error") 45 | } 46 | 47 | return res, nil 48 | } 49 | 50 | func (c *FiscoBcosClient) getUser(userName string) (key.PrivateKeyProvider, error) { 51 | userPath := c.Config.GetKSPath() 52 | 53 | fileName := getKeyFileName(userName, c.Config.GetAppInfo().AppCode) 54 | 55 | filePath := path.Join(userPath, fileName) 56 | 57 | if _, err1 := os.Stat(filePath); os.IsNotExist(err1) { 58 | //create key 59 | 60 | privKey, err := key.NewPrivateKeyByGen(c.Config.GetAppInfo().AlgorithmType.ToKeyType()) 61 | 62 | if err != nil { 63 | return nil, err 64 | } 65 | keyBytes, err := privKey.KeyPEM() 66 | if err != nil { 67 | return nil, err 68 | } 69 | err = storeKey(keyBytes, filePath) 70 | if err != nil { 71 | return nil, err 72 | } 73 | return privKey, nil 74 | 75 | } else { 76 | bytes, err := ioutil.ReadFile(filePath) // nolint: gas 77 | if err != nil { 78 | return nil, err 79 | } 80 | if bytes == nil { 81 | return nil, errors.New("user key error") 82 | } 83 | 84 | return key.NewPrivateKeyProvider(c.Config.GetAppInfo().AlgorithmType.ToKeyType(), string(bytes)) 85 | 86 | } 87 | 88 | } 89 | 90 | func storeKey(keyBytes []byte, filePath string) error { 91 | 92 | err := os.MkdirAll(path.Dir(filePath), 0700) 93 | if err != nil { 94 | return err 95 | } 96 | return ioutil.WriteFile(filePath, keyBytes, 0600) 97 | } 98 | 99 | func getKeyFileName(name string, appCode string) string { 100 | return fmt.Sprintf("%s@%s_pk", name, appCode) 101 | } 102 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/utils/utils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. 2016 All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | /* 17 | Notice: This file has been modified for Hyperledger Fabric SDK Go usage. 18 | Please review third_party pinning scripts and patches for more details. 19 | */ 20 | 21 | package utils 22 | 23 | import ( 24 | "crypto/rand" 25 | "fmt" 26 | "io" 27 | "math/big" 28 | "time" 29 | 30 | "github.com/golang/protobuf/ptypes/timestamp" 31 | ) 32 | 33 | const defaultAlg = "sha256" 34 | 35 | // GenerateBytesUUID returns a UUID based on RFC 4122 returning the generated bytes 36 | func GenerateBytesUUID() []byte { 37 | uuid := make([]byte, 16) 38 | _, err := io.ReadFull(rand.Reader, uuid) 39 | if err != nil { 40 | panic(fmt.Sprintf("Error generating UUID: %s", err)) 41 | } 42 | 43 | // variant bits; see section 4.1.1 44 | uuid[8] = uuid[8]&^0xc0 | 0x80 45 | 46 | // version 4 (pseudo-random); see section 4.1.3 47 | uuid[6] = uuid[6]&^0xf0 | 0x40 48 | 49 | return uuid 50 | } 51 | 52 | // GenerateIntUUID returns a UUID based on RFC 4122 returning a big.Int 53 | func GenerateIntUUID() *big.Int { 54 | uuid := GenerateBytesUUID() 55 | z := big.NewInt(0) 56 | return z.SetBytes(uuid) 57 | } 58 | 59 | // GenerateUUID returns a UUID based on RFC 4122 60 | func GenerateUUID() string { 61 | uuid := GenerateBytesUUID() 62 | return idBytesToStr(uuid) 63 | } 64 | 65 | // CreateUtcTimestamp returns a google/protobuf/Timestamp in UTC 66 | func CreateUtcTimestamp() *timestamp.Timestamp { 67 | now := time.Now().UTC() 68 | secs := now.Unix() 69 | nanos := int32(now.UnixNano() - (secs * 1000000000)) 70 | return &(timestamp.Timestamp{Seconds: secs, Nanos: nanos}) 71 | } 72 | 73 | func idBytesToStr(id []byte) string { 74 | return fmt.Sprintf("%x-%x-%x-%x-%x", id[0:4], id[4:6], id[6:8], id[8:10], id[10:]) 75 | } 76 | 77 | const testchainid = "testchainid" 78 | const testorgid = "**TEST_ORGID**" 79 | 80 | // ConcatenateBytes is useful for combining multiple arrays of bytes, especially for 81 | // signatures or digests over multiple fields 82 | func ConcatenateBytes(data ...[]byte) []byte { 83 | finalLength := 0 84 | for _, slice := range data { 85 | finalLength += len(slice) 86 | } 87 | result := make([]byte, finalLength) 88 | last := 0 89 | for _, slice := range data { 90 | for i := range slice { 91 | result[i+last] = slice[i] 92 | } 93 | last += len(slice) 94 | } 95 | return result 96 | } 97 | 98 | const DELIMITER = "." 99 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/fab/proposer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package fab 8 | 9 | import ( 10 | reqContext "context" 11 | 12 | pb "github.com/hyperledger/fabric-protos-go/peer" 13 | ) 14 | 15 | // ProposalProcessor simulates transaction proposal, so that a client can submit the result for ordering. 16 | type ProposalProcessor interface { 17 | ProcessTransactionProposal(reqContext.Context, ProcessProposalRequest) (*TransactionProposalResponse, error) 18 | } 19 | 20 | // TxnHeaderOptions contains options for creating a Transaction Header 21 | type TxnHeaderOptions struct { 22 | Nonce []byte 23 | Creator []byte 24 | } 25 | 26 | // TxnHeaderOpt is a Transaction Header option 27 | type TxnHeaderOpt func(*TxnHeaderOptions) 28 | 29 | // WithNonce specifies the nonce to use when creating the Transaction Header 30 | func WithNonce(nonce []byte) TxnHeaderOpt { 31 | return func(options *TxnHeaderOptions) { 32 | options.Nonce = nonce 33 | } 34 | } 35 | 36 | // WithCreator specifies the creator to use when creating the Transaction Header 37 | func WithCreator(creator []byte) TxnHeaderOpt { 38 | return func(options *TxnHeaderOptions) { 39 | options.Creator = creator 40 | } 41 | } 42 | 43 | // ProposalSender provides the ability for a transaction proposal to be created and sent. 44 | type ProposalSender interface { 45 | CreateTransactionHeader(opts ...TxnHeaderOpt) (TransactionHeader, error) 46 | SendTransactionProposal(*TransactionProposal, []ProposalProcessor) ([]*TransactionProposalResponse, error) 47 | } 48 | 49 | // TransactionID provides the identifier of a Fabric transaction proposal. 50 | type TransactionID string 51 | 52 | // EmptyTransactionID represents a non-existing transaction (usually due to error). 53 | const EmptyTransactionID = TransactionID("") 54 | 55 | // SystemChannel is the Fabric channel for managaing resources. 56 | const SystemChannel = "" 57 | 58 | // TransactionHeader provides a handle to transaction metadata. 59 | type TransactionHeader interface { 60 | TransactionID() TransactionID 61 | Creator() []byte 62 | Nonce() []byte 63 | ChannelID() string 64 | } 65 | 66 | // ChaincodeInvokeRequest contains the parameters for sending a transaction proposal. 67 | type ChaincodeInvokeRequest struct { 68 | ChaincodeID string 69 | TransientMap map[string][]byte 70 | Fcn string 71 | Args [][]byte 72 | } 73 | 74 | // TransactionProposal contains a marashalled transaction proposal. 75 | type TransactionProposal struct { 76 | TxnID TransactionID 77 | *pb.Proposal 78 | } 79 | 80 | // ProcessProposalRequest requests simulation of a proposed transaction from transaction processors. 81 | type ProcessProposalRequest struct { 82 | SignedProposal *pb.SignedProposal 83 | } 84 | 85 | // TransactionProposalResponse respresents the result of transaction proposal processing. 86 | type TransactionProposalResponse struct { 87 | Endorser string 88 | // Status is the EndorserStatus 89 | Status int32 90 | // ChaincodeStatus is the status returned by Chaincode 91 | ChaincodeStatus int32 92 | *pb.ProposalResponse 93 | } 94 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/utils/txutils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | /* 7 | Notice: This file has been modified for Hyperledger Fabric SDK Go usage. 8 | Please review third_party pinning scripts and patches for more details. 9 | */ 10 | 11 | package utils 12 | 13 | import ( 14 | "github.com/golang/protobuf/proto" 15 | "github.com/hyperledger/fabric-protos-go/common" 16 | "github.com/hyperledger/fabric-protos-go/peer" 17 | "github.com/pkg/errors" 18 | ) 19 | 20 | // GetPayloads gets the underlying payload objects in a TransactionAction 21 | func GetPayloads(txActions *peer.TransactionAction) (*peer.ChaincodeActionPayload, *peer.ChaincodeAction, error) { 22 | // TODO: pass in the tx type (in what follows we're assuming the 23 | // type is ENDORSER_TRANSACTION) 24 | ccPayload, err := GetChaincodeActionPayload(txActions.Payload) 25 | if err != nil { 26 | return nil, nil, err 27 | } 28 | 29 | if ccPayload.Action == nil || ccPayload.Action.ProposalResponsePayload == nil { 30 | return nil, nil, errors.New("no payload in ChaincodeActionPayload") 31 | } 32 | pRespPayload, err := GetProposalResponsePayload(ccPayload.Action.ProposalResponsePayload) 33 | if err != nil { 34 | return nil, nil, err 35 | } 36 | 37 | if pRespPayload.Extension == nil { 38 | return nil, nil, errors.New("response payload is missing extension") 39 | } 40 | 41 | respPayload, err := GetChaincodeAction(pRespPayload.Extension) 42 | if err != nil { 43 | return ccPayload, nil, err 44 | } 45 | return ccPayload, respPayload, nil 46 | } 47 | 48 | // GetEnvelopeFromBlock gets an envelope from a block's Data field. 49 | func GetEnvelopeFromBlock(data []byte) (*common.Envelope, error) { 50 | // Block always begins with an envelope 51 | var err error 52 | env := &common.Envelope{} 53 | if err = proto.Unmarshal(data, env); err != nil { 54 | return nil, errors.Wrap(err, "error unmarshaling Envelope") 55 | } 56 | 57 | return env, nil 58 | } 59 | 60 | // GetBytesProposalPayloadForTx takes a ChaincodeProposalPayload and returns 61 | // its serialized version according to the visibility field 62 | func GetBytesProposalPayloadForTx(payload *peer.ChaincodeProposalPayload, visibility []byte) ([]byte, error) { 63 | // check for nil argument 64 | if payload == nil { 65 | return nil, errors.New("nil arguments") 66 | } 67 | 68 | // strip the transient bytes off the payload - this needs to be done no 69 | // matter the visibility mode 70 | cppNoTransient := &peer.ChaincodeProposalPayload{Input: payload.Input, TransientMap: nil} 71 | cppBytes, err := GetBytesChaincodeProposalPayload(cppNoTransient) 72 | if err != nil { 73 | return nil, err 74 | } 75 | 76 | // currently the fabric only supports full visibility: this means that 77 | // there are no restrictions on which parts of the proposal payload will 78 | // be visible in the final transaction; this default approach requires 79 | // no additional instructions in the PayloadVisibility field; however 80 | // the fabric may be extended to encode more elaborate visibility 81 | // mechanisms that shall be encoded in this field (and handled 82 | // appropriately by the peer) 83 | 84 | return cppBytes, nil 85 | } 86 | -------------------------------------------------------------------------------- /pkg/core/trans/cita/trans.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/uuid" 6 | "github.com/BSNDA/bsn-sdk-crypto/key" 7 | "github.com/ethereum/go-ethereum/accounts/abi" 8 | "github.com/ethereum/go-ethereum/common" 9 | 10 | "bytes" 11 | "strings" 12 | ) 13 | 14 | var ( 15 | QUOTA = uint64(10000000) 16 | Value = []byte{0x0} 17 | ) 18 | 19 | func TransData(contractabi, contractAddress string, funcName string, args []interface{}, blockLimit uint64, chainId string, version uint32, smcrypto bool, privKey key.PrivateKeyProvider) (string, bool, error) { 20 | 21 | abi, err := abi.JSON(strings.NewReader(contractabi)) 22 | if err != nil { 23 | return "", false, err 24 | } 25 | 26 | _, ok := abi.Methods[funcName] 27 | if !ok { 28 | return "", false, errors.New("contract not has function") 29 | } 30 | 31 | funcData, err := pack(&abi, funcName, args, false) 32 | if err != nil { 33 | return "", false, err 34 | } 35 | 36 | //if method.IsConstant() { 37 | // return hexutil.Encode(funcData), true, nil 38 | //} 39 | toAddress := common.HexToAddress(contractAddress) 40 | 41 | nonce := uuid.GetUUID() 42 | 43 | tx := NewTransaction(nonce, toAddress, QUOTA, blockLimit, Value, chainId, funcData, version) 44 | 45 | dataByte, err := SignData(tx, privKey, smcrypto) 46 | 47 | if err != nil { 48 | return "", false, err 49 | } 50 | 51 | trans, err := serializeUnverifiedTransaction(tx, dataByte) 52 | if err != nil { 53 | return "", false, err 54 | } 55 | return trans, false, nil 56 | 57 | } 58 | 59 | func pack(abi *abi.ABI, funcName string, args []interface{}, sm bool) ([]byte, error) { 60 | if sm { 61 | 62 | if funcName == "" { 63 | // constructor 64 | arguments, err := abi.Constructor.Inputs.Pack(args...) 65 | if err != nil { 66 | return nil, err 67 | } 68 | return arguments, nil 69 | } 70 | 71 | method, ok := abi.Methods[funcName] 72 | 73 | if !ok { 74 | return nil, errors.New("contract not has function") 75 | } 76 | 77 | id := getMethodId(method) 78 | 79 | arguments, err := method.Inputs.Pack(args...) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | return append(id, arguments...), nil 85 | 86 | } else { 87 | return abi.Pack(funcName, args...) 88 | } 89 | 90 | } 91 | 92 | func getMethodId(method abi.Method) []byte { 93 | digest := []byte(method.Sig) 94 | h := &key.SM3Hash{} 95 | hash := h.Hash(digest) 96 | return hash[:4] 97 | } 98 | 99 | func ParseMethod(data []byte, contractabi string, sm bool) (funcName string, constant bool, err error) { 100 | abiObj, err := abi.JSON(strings.NewReader(contractabi)) 101 | if err != nil { 102 | return 103 | } 104 | 105 | if sm { 106 | sig := data[:4] 107 | for _, method := range abiObj.Methods { 108 | id := getMethodId(method) 109 | if bytes.Equal(id, sig) { 110 | 111 | funcName = method.Name 112 | constant = method.IsConstant() 113 | return 114 | 115 | } 116 | } 117 | 118 | } else { 119 | var method *abi.Method 120 | method, err = abiObj.MethodById(data) 121 | if err != nil { 122 | return 123 | } 124 | 125 | funcName = method.Name 126 | constant = method.IsConstant() 127 | return 128 | 129 | } 130 | 131 | err = errors.New("func is not found") 132 | return 133 | 134 | } 135 | -------------------------------------------------------------------------------- /pkg/client/fabric/node/client.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/BSNDA/bsn-sdk-crypto/key" 7 | crySign "github.com/BSNDA/bsn-sdk-crypto/sign" 8 | 9 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 10 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 11 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 12 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 13 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/sign" 14 | "github.com/pkg/errors" 15 | "github.com/wonderivan/logger" 16 | ) 17 | 18 | const ( 19 | fabricApiVersion = "v1" 20 | fabricApiFormat = "%s/api/fabric/%s/%s" 21 | ) 22 | 23 | func NewNodeCli(url string, algorithmType enum.App_AlgorithmType, pri string) (*NodeClient, error) { 24 | 25 | cli := &NodeClient{gateWayURL: url} 26 | err := cli.SetAlgorithm(algorithmType, pri) 27 | if err != nil { 28 | return nil, err 29 | } 30 | return cli, nil 31 | 32 | } 33 | 34 | type NodeClient struct { 35 | gateWayURL string 36 | sign sign.Crypto 37 | mspId string 38 | } 39 | 40 | func (n *NodeClient) URL() string { 41 | 42 | return n.gateWayURL 43 | } 44 | 45 | func (c *NodeClient) SetAlgorithm(algorithmType enum.App_AlgorithmType, pri string) error { 46 | 47 | kt := algorithmType.ToKeyType() 48 | 49 | privKey, err := key.NewPrivateKeyProvider(kt, pri) 50 | if err != nil { 51 | return errors.WithMessagef(err, "new [%s] private key provider key has error", kt.String()) 52 | } 53 | 54 | puk := config.GetGatewayPublicKey(algorithmType) 55 | 56 | pubKey, err := key.NewPublicProvider(kt, puk) 57 | if err != nil { 58 | return errors.WithMessagef(err, "new [%s] public key provider key has error", kt.String()) 59 | } 60 | 61 | sh, err := crySign.NewSignProvider(crySign.WithPrivateKey(privKey), crySign.WithPublicKey(pubKey)) 62 | if err != nil { 63 | return errors.WithMessagef(err, "new [%s] sign provider has error", kt.String()) 64 | } 65 | 66 | c.sign = sign.NewCrypto(sh) 67 | return nil 68 | 69 | } 70 | 71 | func (c *NodeClient) Sign(data string) (string, error) { 72 | mac, err := c.sign.Sign(data) 73 | if err != nil { 74 | return "", errors.WithMessage(err, "Exception in signature") 75 | } 76 | return mac, nil 77 | } 78 | 79 | func (c *NodeClient) Verify(mac, data string) bool { 80 | if mac == "" { 81 | return true 82 | } 83 | return c.sign.Verify(mac, data) 84 | 85 | } 86 | 87 | func (c *NodeClient) methodUrl(method string) string { 88 | return fmt.Sprintf(fabricApiFormat, c.gateWayURL, fabricApiVersion, method) 89 | } 90 | 91 | func (c *NodeClient) Call(method string, req base.ReqInterface, res base.ResInterface) error { 92 | url := c.methodUrl(method) 93 | mac, err := c.Sign(req.GetEncryptionValue()) 94 | if err != nil { 95 | return err 96 | } 97 | req.SetMac(mac) 98 | 99 | reqBytes, err := json.Marshal(req) 100 | if err != nil { 101 | logger.Error("request parameter serialization failed:", err) 102 | return errors.WithMessage(err, "request parameter serialization failed") 103 | } 104 | 105 | resBytes, err := http.SendPost(reqBytes, url) 106 | if err != nil { 107 | logger.Error("gateway interface call failed:", err) 108 | return errors.WithMessage(err, "send post has error") 109 | } 110 | 111 | err = json.Unmarshal(resBytes, res) 112 | if err != nil { 113 | logger.Error("return parameter serialization failed:", err) 114 | return errors.WithMessage(err, "return parameter serialization failed") 115 | } 116 | 117 | //v :=c.Verify(res.GetMac(),res.GetEncryptionValue()) 118 | 119 | //fmt.Println(v) 120 | 121 | return nil 122 | } 123 | -------------------------------------------------------------------------------- /pkg/core/trans/fabric/utils/commonutils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright IBM Corp. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | /* 7 | Notice: This file has been modified for Hyperledger Fabric SDK Go usage. 8 | Please review third_party pinning scripts and patches for more details. 9 | */ 10 | 11 | package utils 12 | 13 | import ( 14 | "fmt" 15 | "time" 16 | 17 | "github.com/golang/protobuf/proto" 18 | "github.com/golang/protobuf/ptypes/timestamp" 19 | cb "github.com/hyperledger/fabric-protos-go/common" 20 | "github.com/pkg/errors" 21 | ) 22 | 23 | // MarshalOrPanic serializes a protobuf message and panics if this 24 | // operation fails 25 | func MarshalOrPanic(pb proto.Message) []byte { 26 | data, err := proto.Marshal(pb) 27 | if err != nil { 28 | panic(err) 29 | } 30 | return data 31 | } 32 | 33 | // Marshal serializes a protobuf message. 34 | func Marshal(pb proto.Message) ([]byte, error) { 35 | return proto.Marshal(pb) 36 | } 37 | 38 | // ExtractEnvelopeOrPanic retrieves the requested envelope from a given block 39 | // and unmarshals it -- it panics if either of these operations fail 40 | func ExtractEnvelopeOrPanic(block *cb.Block, index int) *cb.Envelope { 41 | envelope, err := ExtractEnvelope(block, index) 42 | if err != nil { 43 | panic(err) 44 | } 45 | return envelope 46 | } 47 | 48 | // ExtractEnvelope retrieves the requested envelope from a given block and 49 | // unmarshals it 50 | func ExtractEnvelope(block *cb.Block, index int) (*cb.Envelope, error) { 51 | if block.Data == nil { 52 | return nil, errors.New("block data is nil") 53 | } 54 | 55 | envelopeCount := len(block.Data.Data) 56 | if index < 0 || index >= envelopeCount { 57 | return nil, errors.New("envelope index out of bounds") 58 | } 59 | marshaledEnvelope := block.Data.Data[index] 60 | envelope, err := GetEnvelopeFromBlock(marshaledEnvelope) 61 | err = errors.WithMessage(err, fmt.Sprintf("block data does not carry an envelope at index %d", index)) 62 | return envelope, err 63 | } 64 | 65 | // ExtractPayloadOrPanic retrieves the payload of a given envelope and 66 | // unmarshals it -- it panics if either of these operations fail 67 | func ExtractPayloadOrPanic(envelope *cb.Envelope) *cb.Payload { 68 | payload, err := ExtractPayload(envelope) 69 | if err != nil { 70 | panic(err) 71 | } 72 | return payload 73 | } 74 | 75 | // ExtractPayload retrieves the payload of a given envelope and unmarshals it. 76 | func ExtractPayload(envelope *cb.Envelope) (*cb.Payload, error) { 77 | payload := &cb.Payload{} 78 | err := proto.Unmarshal(envelope.Payload, payload) 79 | err = errors.Wrap(err, "no payload in envelope") 80 | return payload, err 81 | } 82 | 83 | // MakeChannelHeader creates a ChannelHeader. 84 | func MakeChannelHeader(headerType cb.HeaderType, version int32, chainID string, epoch uint64) *cb.ChannelHeader { 85 | return &cb.ChannelHeader{ 86 | Type: int32(headerType), 87 | Version: version, 88 | Timestamp: ×tamp.Timestamp{ 89 | Seconds: time.Now().Unix(), 90 | Nanos: 0, 91 | }, 92 | ChannelId: chainID, 93 | Epoch: epoch, 94 | } 95 | } 96 | 97 | // MakePayloadHeader creates a Payload Header. 98 | func MakePayloadHeader(ch *cb.ChannelHeader, sh *cb.SignatureHeader) *cb.Header { 99 | return &cb.Header{ 100 | ChannelHeader: MarshalOrPanic(ch), 101 | SignatureHeader: MarshalOrPanic(sh), 102 | } 103 | } 104 | 105 | // UnmarshalChannelHeader returns a ChannelHeader from bytes 106 | func UnmarshalChannelHeader(bytes []byte) (*cb.ChannelHeader, error) { 107 | chdr := &cb.ChannelHeader{} 108 | err := proto.Unmarshal(bytes, chdr) 109 | return chdr, errors.Wrap(err, "error unmarshaling ChannelHeader") 110 | } 111 | -------------------------------------------------------------------------------- /pkg/core/trans/cita/txdata.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "fmt" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/cita/pb" 9 | "github.com/BSNDA/bsn-sdk-crypto/key" 10 | "github.com/ethereum/go-ethereum/common" 11 | "github.com/ethereum/go-ethereum/common/hexutil" 12 | "github.com/golang/protobuf/proto" 13 | "math/big" 14 | "strconv" 15 | ) 16 | 17 | func NewTransaction(nonce string, to common.Address, quota uint64, validUntilBlock uint64, value []byte, chainId string, data []byte, version uint32) *pb.Transaction { 18 | return newTransaction(nonce, to, quota, validUntilBlock, value, chainId, data, version) 19 | } 20 | func newTransaction(nonce string, to common.Address, quota uint64, validUntilBlock uint64, value []byte, chainId string, data []byte, version uint32) *pb.Transaction { 21 | if len(data) > 0 { 22 | data = common.CopyBytes(data) 23 | } 24 | d := pb.Transaction{ 25 | Nonce: nonce, 26 | Quota: quota, 27 | ValidUntilBlock: validUntilBlock, 28 | Data: data, 29 | Version: version, 30 | } 31 | valuebyte, err := ToBytes32(value) 32 | if err != nil { 33 | return nil 34 | } 35 | d.Value = valuebyte 36 | 37 | if version == 0 { 38 | chain, _ := strconv.ParseUint(chainId, 10, 64) 39 | d.ChainId = uint32(chain) 40 | d.To = string(to[:]) 41 | 42 | } else { 43 | 44 | bigchainId, _ := hexutil.DecodeBig(chainId) 45 | chainidbyte, err := ToBytes32(bigchainId.Bytes()) 46 | if err != nil { 47 | return nil 48 | } 49 | d.ChainIdV1 = chainidbyte 50 | d.ToV1 = to.Bytes() 51 | } 52 | return &d 53 | } 54 | 55 | func ToBytes32(b []byte) ([]byte, error) { 56 | bl := len(b) 57 | if bl > 32 { 58 | return nil, errors.New("len out of limit") 59 | } else if bl == 32 { 60 | return b, nil 61 | } else { 62 | var a [32]byte 63 | for i := 0; i < bl; i++ { 64 | a[32-(bl-i)] = b[i] 65 | } 66 | var bb []byte 67 | for i := 0; i < len(a); i++ { 68 | bb = append(bb, a[i]) 69 | } 70 | return bb, nil 71 | } 72 | } 73 | 74 | func SignData(tx *pb.Transaction, priKey key.PrivateKeyProvider, isSM bool) ([]byte, error) { 75 | 76 | txb, err := proto.Marshal(tx) 77 | if err != nil { 78 | return nil, err 79 | } 80 | if isSM { 81 | 82 | //pk := priKey.Key().(*sm2.PrivateKey) 83 | 84 | h := priKey.Hash(txb) 85 | 86 | r, s, _, err := priKey.SignTx(h) 87 | 88 | if err != nil { 89 | return nil, err 90 | } 91 | //publicKeyStr := fmt.Sprintf("%s%s", fillStr64(String16(pk.X)), fillStr64(String16(pk.Y))) 92 | sign := fmt.Sprintf("%s%s", fillStr64(String16(r)), fillStr64(String16(s))) 93 | signBytes, err := hex.DecodeString(sign) 94 | if err != nil { 95 | return nil, err 96 | } 97 | publicKeyBytes := priKey.PublicKey().Bytes()[1:] 98 | //if err != nil { 99 | // return nil, err 100 | //} 101 | return BytesCombine(signBytes, publicKeyBytes), nil 102 | } 103 | 104 | return nil, nil 105 | 106 | } 107 | func BytesCombine(pBytes ...[]byte) []byte { 108 | return bytes.Join(pBytes, []byte("")) 109 | } 110 | func fillStr64(str string) string { 111 | if len(str) >= 64 { 112 | return str 113 | } else { 114 | s := fmt.Sprintf("%064s", str) 115 | return s 116 | } 117 | } 118 | func String16(x *big.Int) string { 119 | return x.Text(16) 120 | } 121 | func serializeUnverifiedTransaction(tx *pb.Transaction, sig []byte) (string, error) { 122 | trans := pb.UnverifiedTransaction{ 123 | Signature: sig, 124 | Transaction: tx, 125 | Crypto: pb.Crypto_DEFAULT, 126 | } 127 | t, err := proto.Marshal(&trans) 128 | if err != nil { 129 | return "", err 130 | } 131 | return hexutil.Encode(t), nil 132 | } 133 | -------------------------------------------------------------------------------- /pkg/core/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/client/app" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req" 9 | "github.com/BSNDA/bsn-sdk-crypto/key" 10 | "path" 11 | ) 12 | 13 | const ( 14 | _KeyStore = "keystore" 15 | ) 16 | 17 | //Create a profile information 18 | // api: address of the node gateway 19 | // userCode: user's code 20 | // appCode: DApp code 21 | // prk : private key of DApp cert 22 | func NewConfig(api, userCode, appCode, prk, mspDir string) (*Config, error) { 23 | 24 | config := &Config{ 25 | nodeApi: api, 26 | mspDir: mspDir, 27 | appCert: CertInfo{AppPublicCert: "", UserAppPrivateCert: prk}, 28 | user: userInfo{UserCode: userCode}, 29 | app: AppInfo{AppCode: appCode}, 30 | } 31 | err := config.Init() 32 | return config, err 33 | } 34 | 35 | type Config struct { 36 | nodeApi string 37 | mspDir string 38 | 39 | user userInfo 40 | app AppInfo 41 | 42 | //DApp cert【public key of bsn node gateway and private key of user's DApp】 43 | appCert CertInfo 44 | 45 | isInit bool 46 | } 47 | 48 | func (c *Config) GetAppInfo() AppInfo { 49 | return c.app 50 | } 51 | 52 | func (c *Config) GetUserCode() string { 53 | return c.user.UserCode 54 | } 55 | 56 | func (c *Config) GetAppCert() CertInfo { 57 | return c.appCert 58 | } 59 | 60 | func (c *Config) GetKSPath() string { 61 | return path.Join(c.mspDir, _KeyStore) 62 | } 63 | 64 | func (c *Config) GetUSPath() string { 65 | return c.mspDir 66 | } 67 | 68 | func (c *Config) GetNodeApi() string { 69 | return c.nodeApi 70 | } 71 | 72 | func (c *Config) GetReqHeader() base.ReqHeader { 73 | header := base.ReqHeader{ 74 | UserCode: c.user.UserCode, 75 | AppCode: c.app.AppCode, 76 | } 77 | 78 | return header 79 | } 80 | 81 | func (c *Config) Init() error { 82 | if !c.isInit { 83 | reqData := req.AppInfoReqData{} 84 | 85 | reqData.Header = c.GetReqHeader() 86 | 87 | //reqData.Body = req.AppInfoReqDataBody{} 88 | res, err := app.GetAppInfo(&reqData, c.nodeApi, "") 89 | 90 | if err != nil { 91 | return err 92 | } 93 | 94 | if res.Header.Code != 0 { 95 | return errors.New("get app info failed :" + res.Header.Msg) 96 | } 97 | 98 | c.app.AppType = res.Body.AppType 99 | 100 | c.app.CAType = enum.App_CaType(res.Body.CaType) 101 | c.app.AlgorithmType = enum.App_AlgorithmType(res.Body.AlgorithmType) 102 | 103 | if c.appCert.AppPublicCert == "" { 104 | c.appCert.AppPublicCert = GetGatewayPublicKey(c.app.AlgorithmType) 105 | } 106 | 107 | if c.appCert.AppPublicCert == "" { 108 | return errors.New("gateway public key not setting") 109 | } 110 | 111 | c.app.MspId = res.Body.MspId 112 | 113 | c.app.ChannelId = res.Body.ChannelId 114 | c.app.Version = res.Body.FabricVersion 115 | c.isInit = true 116 | } 117 | 118 | return nil 119 | } 120 | 121 | type CertInfo struct { 122 | //public key cert of DApp 123 | AppPublicCert string 124 | 125 | autoPublicKey bool 126 | 127 | //Private key cert of user 128 | UserAppPrivateCert string 129 | } 130 | 131 | type AppInfo struct { 132 | AppCode string 133 | AppType string 134 | 135 | CAType enum.App_CaType 136 | AlgorithmType enum.App_AlgorithmType 137 | 138 | //AppCertPuk string 139 | 140 | MspId string 141 | ChannelId string 142 | Version string 143 | } 144 | 145 | func (a *AppInfo) TxHash() key.HashProvider { 146 | if a.AlgorithmType == enum.AppAlgorithmType_SM2 && a.Version == "2.2.1" { 147 | return &key.SM3Hash{} 148 | } else { 149 | return &key.SHA256Hash{} 150 | } 151 | } 152 | 153 | type userInfo struct { 154 | UserCode string 155 | } 156 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/client/fabric/node" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/msp" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/util/keystore" 9 | "github.com/pkg/errors" 10 | "github.com/wonderivan/logger" 11 | ) 12 | 13 | //initialize client requested by fabric 14 | func InitFabricClient(config *config.Config, opts ...ClientOpts) (*FabricClient, error) { 15 | 16 | //initialize configuration information 17 | if err := config.Init(); err != nil { 18 | logger.Error("Configuration initialization failed") 19 | return nil, err 20 | } 21 | 22 | defCli, err := node.NewNodeCli(config.GetNodeApi(), config.GetAppInfo().AlgorithmType, config.GetAppCert().UserAppPrivateCert) 23 | if err != nil { 24 | return nil, err 25 | } 26 | 27 | fabricClient := &FabricClient{ 28 | appInfo: config.GetAppInfo(), 29 | userCode: config.GetUserCode(), 30 | nodeClients: make(map[string]*node.NodeClient), 31 | users: make(map[string]*msp.UserData), 32 | } 33 | 34 | for _, option := range opts { 35 | err := option(fabricClient) 36 | if err != nil { 37 | return nil, err 38 | } 39 | } 40 | 41 | if fabricClient.keyOpts == nil { 42 | fabricClient.keyOpts = keystore.NewFileKeyStore(config.GetKSPath()) 43 | } 44 | 45 | if fabricClient.userOpts == nil { 46 | fabricClient.userOpts = keystore.NewUserCertStore(config.GetUSPath()) 47 | } 48 | 49 | if fabricClient.defaultNodeName == "" { 50 | fabricClient.defaultNodeName = fabricClient.appInfo.MspId 51 | } 52 | fabricClient.nodeClients[fabricClient.defaultNodeName] = defCli 53 | 54 | return fabricClient, nil 55 | } 56 | 57 | type FabricClient struct { 58 | appInfo config.AppInfo 59 | userCode string 60 | 61 | nodeClients map[string]*node.NodeClient 62 | defaultNodeName string 63 | keyOpts keystore.KeyStore 64 | userOpts keystore.UserCertStore 65 | 66 | users map[string]*msp.UserData 67 | } 68 | 69 | type ClientOpts func(*FabricClient) error 70 | 71 | // WithUserOpts 指定的用户证书存储对象,可由调用者自己按照接口 keystore.UserCertStore 实现 72 | func WithUserOpts(userOpts keystore.UserCertStore) ClientOpts { 73 | return func(client *FabricClient) error { 74 | client.userOpts = userOpts 75 | return nil 76 | } 77 | } 78 | 79 | // WithUserOpts 指定的用户私钥存储对象,可由调用者自己按照接口 keystore.KeyStore 实现 80 | func WithKeyOpts(keyOpts keystore.KeyStore) ClientOpts { 81 | return func(client *FabricClient) error { 82 | client.keyOpts = keyOpts 83 | return nil 84 | } 85 | } 86 | 87 | // WithDefaultNodeName 默认的客户端配置的城市名称,如果不指定,则为默认配置城市的MSPID 88 | func WithDefaultNodeName(nodeName string) ClientOpts { 89 | return func(client *FabricClient) error { 90 | client.defaultNodeName = nodeName 91 | return nil 92 | } 93 | } 94 | 95 | // AddCityNode 增加一个城市接入配置 96 | // - nodeName 指定的城市名称标识,可以在执行多节点背书交易时,按照nodeName指定背书的城市列表 97 | // - gateWayUrl 网关地址 98 | // - privateKey 应用在该城市的接入私钥 99 | func (c *FabricClient) AddCityNode(nodeName, gateWayUrl, privateKey string) error { 100 | 101 | _, ok := c.nodeClients[nodeName] 102 | if ok { 103 | return errors.New("node already exists") 104 | } 105 | 106 | Cli, err := node.NewNodeCli(gateWayUrl, c.appInfo.AlgorithmType, privateKey) 107 | if err != nil { 108 | return err 109 | } 110 | 111 | c.nodeClients[nodeName] = Cli 112 | 113 | return nil 114 | } 115 | 116 | func (c *FabricClient) GetHeader() base.ReqHeader { 117 | header := base.ReqHeader{ 118 | UserCode: c.userCode, 119 | AppCode: c.appInfo.AppCode, 120 | } 121 | 122 | return header 123 | } 124 | 125 | // subUserCertName sub user name in certificate 126 | func (c *FabricClient) subUserCertName(name string) string { 127 | return name + "@" + c.appInfo.AppCode 128 | } 129 | 130 | func (c *FabricClient) Call(method string, req base.ReqInterface, res base.ResInterface) error { 131 | //todo random Call 132 | 133 | return c.nodeClients[c.defaultNodeName].Call(method, req, res) 134 | } 135 | -------------------------------------------------------------------------------- /pkg/core/config/pukConfig.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 4 | 5 | const ( 6 | PubK_SM = `-----BEGIN PUBLIC KEY----- 7 | MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEIlh1C0iWAdcKnM/yAaZZT/42NVzT 8 | Vyr31H9MDhHbPkp+/B3gsp5iZOr6OTAGO9jpN10/YMIrxt2IMg5auIEvMA== 9 | -----END PUBLIC KEY-----` 10 | 11 | PubK_R1 = `-----BEGIN CERTIFICATE----- 12 | MIIC+zCCAqGgAwIBAgIUARhAfFSyhzcx9q4LdiYKl2UHo1YwCgYIKoZIzj0EAwIw 13 | TjELMAkGA1UEBhMCQ04xEDAOBgNVBAgTB0JlaWppbmcxDDAKBgNVBAoTA0JTTjEP 14 | MA0GA1UECxMGY2xpZW50MQ4wDAYDVQQDEwVic25jYTAgFw0xOTA5MjYxMDI0MDBa 15 | GA8yMDk5MDkwNTAyMDQwMFowgZYxCzAJBgNVBAYTAkNOMREwDwYDVQQIEwhDaGFu 16 | Z3NoYTEOMAwGA1UEChMFQ21QYXkxPTALBgNVBAsTBHVzZXIwEgYDVQQLEwtob25n 17 | emFvbm9kZTAOBgNVBAsTB2JzbmJhc2UwCgYDVQQLEwNjb20xJTAjBgNVBAMMHG5v 18 | ZGVAaG9uZ3phb25vZGUuYnNuYmFzZS5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMB 19 | BwNCAAQ/X2w5+pJoZXNCO81T4xMR+TxmFoYk6eG1kYML8HBPrUT6QflxtDXYsE9h 20 | SzVAovq5DHww3vD8Xft/mxwsAXyuo4IBEDCCAQwwDgYDVR0PAQH/BAQDAgeAMAwG 21 | A1UdEwEB/wQCMAAwHQYDVR0OBBYEFDPVPRqPANJavkNOg/WhPkUkH6wqMB8GA1Ud 22 | IwQYMBaAFJuwcYba1G07p1ySkpzyes8L79OPMCUGA1UdEQQeMByCGmNhLmhvbmd6 23 | YW9ub2RlLmJzbmJhc2UuY29tMIGEBggqAwQFBgcIAQR4eyJhdHRycyI6eyJoZi5B 24 | ZmZpbGlhdGlvbiI6Imhvbmd6YW9ub2RlLmJzbmJhc2UuY29tIiwiaGYuRW5yb2xs 25 | bWVudElEIjoibm9kZUBob25nemFvbm9kZS5ic25iYXNlLmNvbSIsImhmLlR5cGUi 26 | OiJ1c2VyIn19MAoGCCqGSM49BAMCA0gAMEUCIQD7FBAQJsgS0uhaL4mjJgILdFfY 27 | RKXvNutyKz/MqJ54RQIgNS67sSUCbOZRx1rWDqYEcBF1zypEFik25fNgY3zk5gM= 28 | -----END CERTIFICATE-----` 29 | 30 | Pubk_K1 = `-----BEGIN PUBLIC KEY----- 31 | MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAETXyl2gs9ChpfEIpJqgNj6ob6GrNp5Zax 32 | TRpgP7zigIEEwAUEQNL8cQoMS+yzPXTFrWlZubE4GFWFoi/Nxk2jdA== 33 | -----END PUBLIC KEY-----` 34 | 35 | PubK_SM_test = `-----BEGIN PUBLIC KEY----- 36 | MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAECwJ5ftuqndO9H3ks1hD8cB6IA9lx 37 | /b0Z2hnFZ77rgRm9Q4lY1aqIhkM63Lh6X7uwPsoRC1xkS0PMp5x/jnRWcw== 38 | -----END PUBLIC KEY-----` 39 | 40 | PubK_R1_test = `-----BEGIN CERTIFICATE----- 41 | MIIC+zCCAqGgAwIBAgIUARhAfFSyhzcx9q4LdiYKl2UHo1YwCgYIKoZIzj0EAwIw 42 | TjELMAkGA1UEBhMCQ04xEDAOBgNVBAgTB0JlaWppbmcxDDAKBgNVBAoTA0JTTjEP 43 | MA0GA1UECxMGY2xpZW50MQ4wDAYDVQQDEwVic25jYTAgFw0xOTA5MjYxMDI0MDBa 44 | GA8yMDk5MDkwNTAyMDQwMFowgZYxCzAJBgNVBAYTAkNOMREwDwYDVQQIEwhDaGFu 45 | Z3NoYTEOMAwGA1UEChMFQ21QYXkxPTALBgNVBAsTBHVzZXIwEgYDVQQLEwtob25n 46 | emFvbm9kZTAOBgNVBAsTB2JzbmJhc2UwCgYDVQQLEwNjb20xJTAjBgNVBAMMHG5v 47 | ZGVAaG9uZ3phb25vZGUuYnNuYmFzZS5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMB 48 | BwNCAAQ/X2w5+pJoZXNCO81T4xMR+TxmFoYk6eG1kYML8HBPrUT6QflxtDXYsE9h 49 | SzVAovq5DHww3vD8Xft/mxwsAXyuo4IBEDCCAQwwDgYDVR0PAQH/BAQDAgeAMAwG 50 | A1UdEwEB/wQCMAAwHQYDVR0OBBYEFDPVPRqPANJavkNOg/WhPkUkH6wqMB8GA1Ud 51 | IwQYMBaAFJuwcYba1G07p1ySkpzyes8L79OPMCUGA1UdEQQeMByCGmNhLmhvbmd6 52 | YW9ub2RlLmJzbmJhc2UuY29tMIGEBggqAwQFBgcIAQR4eyJhdHRycyI6eyJoZi5B 53 | ZmZpbGlhdGlvbiI6Imhvbmd6YW9ub2RlLmJzbmJhc2UuY29tIiwiaGYuRW5yb2xs 54 | bWVudElEIjoibm9kZUBob25nemFvbm9kZS5ic25iYXNlLmNvbSIsImhmLlR5cGUi 55 | OiJ1c2VyIn19MAoGCCqGSM49BAMCA0gAMEUCIQD7FBAQJsgS0uhaL4mjJgILdFfY 56 | RKXvNutyKz/MqJ54RQIgNS67sSUCbOZRx1rWDqYEcBF1zypEFik25fNgY3zk5gM= 57 | -----END CERTIFICATE-----` 58 | 59 | Pubk_K1_test = `-----BEGIN PUBLIC KEY----- 60 | MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEh4WlY4pCv814i3WY5aRhtR3PoiIXOM1I 61 | 5xBGylyQTedo6DzJUdLfYZSZLs4py70D8FJtNICMVQCfezA7whHzUw== 62 | -----END PUBLIC KEY-----` 63 | ) 64 | 65 | var test = false 66 | 67 | //Enable test net parameters 68 | //set test gateway public key 69 | func SetTest() { 70 | test = true 71 | } 72 | 73 | func getSmKey() string { 74 | if test { 75 | return PubK_SM_test 76 | } else { 77 | return PubK_SM 78 | } 79 | 80 | } 81 | 82 | func getR1Key() string { 83 | if test { 84 | return PubK_R1_test 85 | } else { 86 | return PubK_R1 87 | } 88 | 89 | } 90 | 91 | func getK1Key() string { 92 | if test { 93 | return Pubk_K1_test 94 | } else { 95 | return Pubk_K1 96 | } 97 | 98 | } 99 | 100 | func GetGatewayPublicKey(algorithmType enum.App_AlgorithmType) string { 101 | switch algorithmType { 102 | case enum.AppAlgorithmType_SM2: 103 | return getSmKey() 104 | case enum.AppAlgorithmType_R1: 105 | return getR1Key() 106 | case enum.AppAlgorithmType_K1: 107 | return getK1Key() 108 | } 109 | 110 | return "" 111 | } 112 | -------------------------------------------------------------------------------- /pkg/core/entity/res/cita/node/blockTxReceiptResData.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 5 | "strconv" 6 | ) 7 | 8 | type BlockTxReceiptResData struct { 9 | base.BaseResModel 10 | Body *TxReceiptData `json:"body"` 11 | } 12 | 13 | type TxReceiptData struct { 14 | TransactionHash string `json:"transactionHash"` 15 | TransactionIndex int64 `json:"transactionIndex"` 16 | BlockHash string `json:"blockHash"` 17 | BlockNumber uint64 `json:"blockNumber"` 18 | CumulativeGasUsed string `json:"cumulativeGasUsed"` 19 | CumulativeQuotaUsed uint64 `json:"cumulativeQuotaUsed"` 20 | GasUsed string `json:"gasUsed"` 21 | QuotaUsed uint64 `json:"quotaUsed"` 22 | ContractAddress string `json:"contractAddress"` 23 | Root string `json:"root"` 24 | Status string `json:"status"` 25 | From string `json:"from"` 26 | To string `json:"to"` 27 | LogsBloom string `json:"logsBloom"` 28 | ErrorMessage string `json:"errorMessage"` 29 | TransactionIndexRaw string `json:"transactionIndexRaw"` 30 | BlockNumberRaw string `json:"blockNumberRaw"` 31 | CumulativeGasUsedRaw string `json:"cumulativeGasUsedRaw"` 32 | CumulativeQuotaUsedRaw string `json:"cumulativeQuotaUsedRaw"` 33 | GasUsedRaw string `json:"gasUsedRaw"` 34 | QuotaUsedRaw string `json:"quotaUsedRaw"` 35 | Logs []TranReceiptLogData `json:"logs"` 36 | } 37 | type TranReceiptLogData struct { 38 | Removed bool `json:"removed"` 39 | LogIndex uint64 `json:"logIndex"` 40 | TransactionIndex uint64 `json:"transactionIndex"` 41 | TransactionHash string `json:"transactionHash"` 42 | BlockHash string `json:"blockHash"` 43 | BlockNumber uint64 `json:"blockNumber"` 44 | Address string `json:"address"` 45 | Data string `json:"data"` 46 | TransactionLogIndex string `json:"transactionLogIndex"` 47 | TransactionIndexRaw string `json:"transactionIndexRaw"` 48 | BlockNumberRaw string `json:"blockNumberRaw"` 49 | LogIndexRaw string `json:"logIndexRaw"` 50 | Topics []string `json:"topics"` 51 | } 52 | 53 | func (f *TxReceiptData) GetEncryptionValue() string { 54 | 55 | if f == nil { 56 | return "" 57 | } 58 | 59 | fb := "" 60 | 61 | fb = fb + f.TransactionHash 62 | fb = fb + strconv.FormatInt(f.TransactionIndex, 10) 63 | fb = fb + f.BlockHash 64 | fb = fb + strconv.FormatUint(f.BlockNumber, 10) 65 | fb = fb + f.CumulativeGasUsed 66 | fb = fb + strconv.FormatUint(f.CumulativeQuotaUsed, 10) 67 | fb = fb + f.GasUsed 68 | fb = fb + strconv.FormatUint(f.QuotaUsed, 10) 69 | fb = fb + f.ContractAddress 70 | fb = fb + f.Root 71 | fb = fb + f.Status 72 | fb = fb + f.From 73 | fb = fb + f.To 74 | fb = fb + f.LogsBloom 75 | fb = fb + f.ErrorMessage 76 | fb = fb + f.TransactionIndexRaw 77 | fb = fb + f.BlockNumberRaw 78 | fb = fb + f.CumulativeGasUsedRaw 79 | fb = fb + f.CumulativeQuotaUsedRaw 80 | fb = fb + f.GasUsedRaw 81 | fb = fb + f.QuotaUsedRaw 82 | for _, t := range f.Logs { 83 | fb = fb + strconv.FormatBool(t.Removed) 84 | fb = fb + strconv.FormatUint(t.LogIndex, 10) 85 | fb = fb + strconv.FormatUint(t.TransactionIndex, 10) 86 | fb = fb + t.TransactionHash 87 | fb = fb + t.BlockHash 88 | fb = fb + strconv.FormatUint(t.BlockNumber, 10) 89 | fb = fb + t.Address 90 | fb = fb + t.Data 91 | fb = fb + t.TransactionLogIndex 92 | fb = fb + t.TransactionIndexRaw 93 | fb = fb + t.BlockNumberRaw 94 | fb = fb + t.LogIndexRaw 95 | for _, s := range t.Topics { 96 | fb = fb + s 97 | } 98 | } 99 | 100 | return fb 101 | } 102 | 103 | func (f *BlockTxReceiptResData) GetEncryptionValue() string { 104 | 105 | return f.GetBaseEncryptionValue() + f.GetEncryptionValue() 106 | 107 | } 108 | -------------------------------------------------------------------------------- /pkg/client/xuperchain/xuperchain_node.go: -------------------------------------------------------------------------------- 1 | // @Title xuperchain_node 2 | // @Description 3 | // @Author zxl 2020/7/22 19:32 4 | // @Version 1.0.0 5 | // @Update 2020/7/22 19:32 6 | package xuperchain 7 | 8 | import ( 9 | "encoding/json" 10 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 11 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 12 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/xuperchain/node" 13 | res "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/xuperchain/node" 14 | "github.com/wonderivan/logger" 15 | ) 16 | 17 | //DApp transaction in public key upload mode 18 | func (c *XuperChainClient) SdkTran(body req.UPukCallContractReqDataReqDataBody) (*res.UPukCallContractResData, error) { 19 | url := c.GetURL("/api/xuperchain/v1/node/trans") 20 | 21 | data := &req.UPukCallContractReqData{} 22 | data.Header = c.GetHeader() 23 | data.Body = body 24 | data.Mac = c.Sign(data.GetEncryptionValue()) 25 | 26 | reqBytes, _ := json.Marshal(data) 27 | 28 | resBytes, err := http.SendPost(reqBytes, url) 29 | 30 | if err != nil { 31 | logger.Error("gateway interface call failed:", err) 32 | return nil, err 33 | } 34 | 35 | resData := &res.UPukCallContractResData{} 36 | 37 | err = json.Unmarshal(resBytes, resData) 38 | if err != nil { 39 | logger.Error("return parameter serialization failed:", err) 40 | return nil, err 41 | } 42 | if !c.Verify(resData.Mac, resData.GetEncryptionValue()) { 43 | return nil, errors.New("sign has error") 44 | } 45 | 46 | return resData, nil 47 | } 48 | 49 | //DApp transaction in public key trust mode 50 | func (c *XuperChainClient) ReqChainCode(body req.CallContractReqDataReqDataBody) (*res.CallContractResData, error) { 51 | url := c.GetURL("/api/xuperchain/v1/node/reqChainCode") 52 | 53 | data := &req.CallContractReqData{} 54 | data.Header = c.GetHeader() 55 | data.Body = body 56 | data.Mac = c.Sign(data.GetEncryptionValue()) 57 | 58 | reqBytes, _ := json.Marshal(data) 59 | 60 | resBytes, err := http.SendPost(reqBytes, url) 61 | 62 | if err != nil { 63 | logger.Error("gateway interface call failed:", err) 64 | return nil, err 65 | } 66 | 67 | resData := &res.CallContractResData{} 68 | 69 | err = json.Unmarshal(resBytes, resData) 70 | if err != nil { 71 | logger.Error("return parameter serialization failed:", err) 72 | return nil, err 73 | } 74 | if !c.Verify(resData.Mac, resData.GetEncryptionValue()) { 75 | return nil, errors.New("sign has error") 76 | } 77 | 78 | return resData, nil 79 | } 80 | 81 | //get transaction information 82 | func (c *XuperChainClient) GetTxInfo(body req.GetTxInfoReqDataBody) (*res.GetTxInfoResData, error) { 83 | url := c.GetURL("/api/xuperchain/v1/node/getTxInfoByTxHash") 84 | 85 | data := &req.GetTxInfoReqData{} 86 | data.Header = c.GetHeader() 87 | data.Body = body 88 | data.Mac = c.Sign(data.GetEncryptionValue()) 89 | 90 | reqBytes, _ := json.Marshal(data) 91 | 92 | resBytes, err := http.SendPost(reqBytes, url) 93 | 94 | if err != nil { 95 | logger.Error("gateway interface call failed:", err) 96 | return nil, err 97 | } 98 | 99 | resData := &res.GetTxInfoResData{} 100 | 101 | err = json.Unmarshal(resBytes, resData) 102 | if err != nil { 103 | logger.Error("return parameter serialization failed:", err) 104 | return nil, err 105 | } 106 | if !c.Verify(resData.Mac, resData.GetEncryptionValue()) { 107 | return nil, errors.New("sign has error") 108 | } 109 | return resData, nil 110 | } 111 | 112 | //get block information 113 | func (c *XuperChainClient) GetBlockInfo(body req.GetBlockInfoReqDataBody) (*res.GetBlockInfoResData, error) { 114 | url := c.GetURL("/api/xuperchain/v1/node/getBlockInfo") 115 | 116 | data := &req.GetBlockInfoReqData{} 117 | data.Header = c.GetHeader() 118 | data.Body = body 119 | data.Mac = c.Sign(data.GetEncryptionValue()) 120 | 121 | reqBytes, _ := json.Marshal(data) 122 | 123 | resBytes, err := http.SendPost(reqBytes, url) 124 | 125 | if err != nil { 126 | logger.Error("gateway interface call failed:", err) 127 | return nil, err 128 | } 129 | 130 | resData := &res.GetBlockInfoResData{} 131 | 132 | err = json.Unmarshal(resBytes, resData) 133 | if err != nil { 134 | logger.Error("return parameter serialization failed:", err) 135 | return nil, err 136 | } 137 | if !c.Verify(resData.Mac, resData.GetEncryptionValue()) { 138 | return nil, errors.New("sign has error") 139 | } 140 | return resData, nil 141 | } 142 | -------------------------------------------------------------------------------- /pkg/core/trans/fiscobcos/trans.go: -------------------------------------------------------------------------------- 1 | package fiscobcos 2 | 3 | import ( 4 | "bytes" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 6 | cryptocomm "github.com/BSNDA/bsn-sdk-crypto/common" 7 | "github.com/BSNDA/bsn-sdk-crypto/key" 8 | "github.com/ethereum/go-ethereum/accounts/abi" 9 | "github.com/ethereum/go-ethereum/common" 10 | "github.com/ethereum/go-ethereum/common/hexutil" 11 | "github.com/ethereum/go-ethereum/rlp" 12 | "math/big" 13 | "strings" 14 | ) 15 | 16 | var ( 17 | GAS_PRICE = new(big.Int).SetInt64(22000000000) 18 | GAS_LIMIT = new(big.Int).SetInt64(4300000) 19 | 20 | ChainId = new(big.Int).SetInt64(1) 21 | ) 22 | 23 | func ParesData(contractabi, funcName string, args []interface{}, smcrypto bool) (string, error) { 24 | abi, err := abi.JSON(strings.NewReader(contractabi)) 25 | if err != nil { 26 | return "", err 27 | } 28 | 29 | funcData, err := pack(&abi, funcName, args, smcrypto) 30 | if err != nil { 31 | return "", err 32 | } 33 | 34 | return hexutil.Encode(funcData), nil 35 | 36 | } 37 | 38 | func TransData(contractabi, contractAddress string, funcName string, args []interface{}, groupId, blockLimit *big.Int, extraData []byte, smcrypto bool, privKey key.PrivateKeyProvider) (string, bool, error) { 39 | 40 | abi, err := abi.JSON(strings.NewReader(contractabi)) 41 | if err != nil { 42 | return "", false, err 43 | } 44 | 45 | method, ok := abi.Methods[funcName] 46 | if !ok { 47 | return "", false, errors.New("contract not has function") 48 | } 49 | 50 | funcData, err := pack(&abi, funcName, args, smcrypto) 51 | if err != nil { 52 | return "", false, err 53 | } 54 | 55 | if method.IsConstant() { 56 | return hexutil.Encode(funcData), true, nil 57 | } 58 | toAddress := common.HexToAddress(contractAddress) 59 | 60 | nonce, _ := cryptocomm.GetRandomBigInt() 61 | 62 | if err != nil { 63 | return "", false, err 64 | } 65 | 66 | tx := NewTransaction(nonce, toAddress, nil, GAS_LIMIT, GAS_PRICE, blockLimit, funcData, ChainId, groupId, extraData, smcrypto) 67 | 68 | dataByte, err := tx.SignData(privKey) 69 | 70 | if err != nil { 71 | return "", false, err 72 | } 73 | 74 | return hexutil.Encode(dataByte), false, nil 75 | 76 | } 77 | 78 | func pack(abi *abi.ABI, funcName string, args []interface{}, sm bool) ([]byte, error) { 79 | if sm { 80 | 81 | if funcName == "" { 82 | // constructor 83 | arguments, err := abi.Constructor.Inputs.Pack(args...) 84 | if err != nil { 85 | return nil, err 86 | } 87 | return arguments, nil 88 | } 89 | 90 | method, ok := abi.Methods[funcName] 91 | 92 | if !ok { 93 | return nil, errors.New("contract not has function") 94 | } 95 | 96 | id := getMethodId(method) 97 | 98 | arguments, err := method.Inputs.Pack(args...) 99 | if err != nil { 100 | return nil, err 101 | } 102 | 103 | return append(id, arguments...), nil 104 | 105 | } else { 106 | return abi.Pack(funcName, args...) 107 | } 108 | 109 | } 110 | 111 | func getMethodId(method abi.Method) []byte { 112 | digest := []byte(method.Sig) 113 | 114 | h := key.SM3Hash{} 115 | hash := h.Hash(digest) 116 | return hash[:4] 117 | } 118 | 119 | func ParseTrans(data string, contractAbi string, sm bool) (contractAddress, funcName string, constant bool, err error) { 120 | 121 | err = nil 122 | 123 | dataByte, err := hexutil.Decode(data) 124 | if err != nil { 125 | return 126 | } 127 | 128 | sign := &txdata{} 129 | 130 | err = rlp.DecodeBytes(dataByte, sign) 131 | if err != nil { 132 | funcName, constant, err = ParseMethod(dataByte, contractAbi, sm) 133 | return 134 | } 135 | 136 | contractAddress = strings.ToLower(sign.Recipient.String()) 137 | funcName, constant, err = ParseMethod(sign.Payload, contractAbi, sm) 138 | 139 | return 140 | 141 | } 142 | 143 | func ParseMethod(data []byte, contractabi string, sm bool) (funcName string, constant bool, err error) { 144 | abiObj, err := abi.JSON(strings.NewReader(contractabi)) 145 | if err != nil { 146 | return 147 | } 148 | 149 | if sm { 150 | sig := data[:4] 151 | for _, method := range abiObj.Methods { 152 | id := getMethodId(method) 153 | if bytes.Equal(id, sig) { 154 | 155 | funcName = method.Name 156 | constant = method.IsConstant() 157 | return 158 | 159 | } 160 | } 161 | 162 | } else { 163 | var method *abi.Method 164 | method, err = abiObj.MethodById(data) 165 | if err != nil { 166 | return 167 | } 168 | 169 | funcName = method.Name 170 | constant = method.IsConstant() 171 | return 172 | 173 | } 174 | 175 | err = errors.New("func is not found") 176 | return 177 | 178 | } 179 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_user.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "encoding/hex" 5 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/base" 6 | 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/msp" 8 | "github.com/BSNDA/bsn-sdk-crypto/key" 9 | "github.com/pkg/errors" 10 | "github.com/wonderivan/logger" 11 | 12 | userreq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/user" 13 | userres "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/fabric/user" 14 | ) 15 | 16 | const ( 17 | RegisterUser = "user/register" 18 | EnrollUser = "user/enroll" 19 | ) 20 | 21 | // RegisterUser register sub user 22 | func (c *FabricClient) RegisterUser(body userreq.RegisterReqDataBody) (*userres.RegisterResData, error) { 23 | 24 | req := &userreq.RegisterReqData{} 25 | req.Header = c.GetHeader() 26 | req.Body = body 27 | res := &userres.RegisterResData{} 28 | 29 | err := c.Call(RegisterUser, req, res) 30 | if err != nil { 31 | return nil, errors.WithMessagef(err, "call %s has error", RegisterUser) 32 | } 33 | return res, nil 34 | } 35 | 36 | // EnrollUser enroll sub user certificate and store to local folder and FabricClient.Users 37 | func (c *FabricClient) EnrollUser(body userreq.RegisterReqDataBody) (*userres.EnrollResData, error) { 38 | 39 | enrollBody := userreq.EnrollReqDataBody{ 40 | Name: body.Name, 41 | Secret: body.Secret, 42 | } 43 | 44 | privKey, err := key.NewPrivateKeyByGen(c.appInfo.AlgorithmType.ToKeyType()) 45 | if err != nil { 46 | return nil, errors.WithMessage(err, "Generate private key has error") 47 | } 48 | 49 | csrReq := key.NewCertificateRequest(c.subUserCertName(enrollBody.Name)) 50 | 51 | csrBytes, err := privKey.GenCSR(csrReq) 52 | if err != nil { 53 | return nil, errors.WithMessage(err, "Generate csr has error") 54 | } 55 | 56 | rawKey, err := privKey.KeyPEM() 57 | if err != nil { 58 | return nil, errors.WithMessage(err, "privateKey to PEM has error") 59 | } 60 | 61 | // save key 62 | err = c.keyOpts.StoreKey(rawKey, hex.EncodeToString(privKey.SKI())) 63 | if err != nil { 64 | return nil, errors.WithMessage(err, "save privateKey has error") 65 | } 66 | 67 | user := c.newUser(body.Name) 68 | user.PrivateKey = privKey 69 | 70 | enrollBody.CsrPem = string(csrBytes) 71 | res, err := c.enroll(enrollBody) 72 | if err != nil { 73 | return nil, err 74 | } 75 | 76 | if res.Header.Code == base.Header_error_code { 77 | return nil, errors.New(res.Header.Msg) 78 | } 79 | 80 | user.EnrollmentCertificate = []byte(res.Body.Cert) 81 | err = c.userOpts.Store(user) 82 | if err != nil { 83 | logger.Warn("user [%s] cert store has error : %s", user.UserName, err.Error()) 84 | } 85 | 86 | c.users[body.Name] = user 87 | 88 | return res, nil 89 | } 90 | 91 | // enroll enroll sub user certificate 92 | func (c *FabricClient) enroll(body userreq.EnrollReqDataBody) (*userres.EnrollResData, error) { 93 | 94 | req := &userreq.EnrollReqData{} 95 | req.Header = c.GetHeader() 96 | req.Body = body 97 | 98 | res := &userres.EnrollResData{} 99 | 100 | err := c.Call(EnrollUser, req, res) 101 | if err != nil { 102 | return nil, errors.WithMessagef(err, "call %s has error", EnrollUser) 103 | } 104 | return res, nil 105 | 106 | } 107 | 108 | func (c *FabricClient) newUser(userName string) *msp.UserData { 109 | user := &msp.UserData{ 110 | UserName: userName, 111 | AppCode: c.appInfo.AppCode, 112 | MspId: c.appInfo.MspId, 113 | TxHash: c.appInfo.TxHash(), 114 | } 115 | 116 | return user 117 | } 118 | 119 | // LoadUser load user from local store , before, the cache is checked from the client users 120 | func (c *FabricClient) LoadUser(userName string) (*msp.UserData, error) { 121 | if userName == "" { 122 | return nil, errors.New("userName can not be empty") 123 | } 124 | user, ok := c.users[userName] 125 | if ok { 126 | return user, nil 127 | } 128 | 129 | user = c.newUser(userName) 130 | err := c.userOpts.Load(user) 131 | if err != nil { 132 | return nil, err 133 | } 134 | 135 | puk, err := key.NewPublicProvider(c.appInfo.AlgorithmType.ToKeyType(), string(user.EnrollmentCertificate)) 136 | if err != nil { 137 | return nil, errors.WithMessage(err, "cert pem load has error") 138 | } 139 | 140 | alias := hex.EncodeToString(puk.SKI()) 141 | 142 | rawkey, err := c.keyOpts.LoadKey(alias) 143 | if err != nil { 144 | return nil, errors.WithMessage(err, "load private key has error") 145 | } 146 | 147 | k, err := key.NewPrivateKeyProvider(c.appInfo.AlgorithmType.ToKeyType(), string(rawkey)) 148 | if err != nil { 149 | return nil, errors.WithMessage(err, "new private key provider has error") 150 | } 151 | 152 | user.PrivateKey = k 153 | c.users[userName] = user 154 | return user, nil 155 | } 156 | -------------------------------------------------------------------------------- /pkg/core/trans/fiscobcos/txdata.go: -------------------------------------------------------------------------------- 1 | package fiscobcos 2 | 3 | import ( 4 | "bytes" 5 | "github.com/BSNDA/bsn-sdk-crypto/key" 6 | "golang.org/x/crypto/sha3" 7 | 8 | "github.com/ethereum/go-ethereum/common" 9 | "github.com/ethereum/go-ethereum/rlp" 10 | "io" 11 | "math/big" 12 | "sync/atomic" 13 | ) 14 | 15 | type Transaction struct { 16 | data txdata 17 | 18 | //sign txsign 19 | 20 | // caches 21 | hash atomic.Value 22 | size atomic.Value 23 | from atomic.Value 24 | smcrypto bool 25 | } 26 | 27 | type txdata struct { 28 | AccountNonce *big.Int `json:"nonce" gencodec:"required"` 29 | Price *big.Int `json:"gasPrice" gencodec:"required"` 30 | GasLimit *big.Int `json:"gas" gencodec:"required"` 31 | BlockLimit *big.Int `json:"blocklimit" gencodec:"required"` 32 | Recipient *common.Address `json:"to" rlp:"nil"` // nil means contract creation 33 | Amount *big.Int `json:"value" gencodec:"required"` 34 | Payload []byte `json:"input" gencodec:"required"` 35 | // for fisco bcos 2.0 36 | ChainID *big.Int `json:"chainId" gencodec:"required"` 37 | GroupID *big.Int `json:"groupId" gencodec:"required"` 38 | ExtraData []byte `json:"extraData" gencodec:"required"` // rlp:"nil" 39 | 40 | V *big.Int `json:"v" gencodec:"required"` 41 | R *big.Int `json:"r" gencodec:"required"` 42 | S *big.Int `json:"s" gencodec:"required"` 43 | } 44 | 45 | // NewTransaction returns a new transaction 46 | func NewTransaction(nonce *big.Int, to common.Address, amount *big.Int, gasLimit *big.Int, gasPrice *big.Int, blockLimit *big.Int, data []byte, chainId *big.Int, groupId *big.Int, extraData []byte, smcrypto bool) *Transaction { 47 | return newTransaction(nonce, &to, amount, gasLimit, gasPrice, blockLimit, data, chainId, groupId, extraData, smcrypto) 48 | } 49 | func newTransaction(nonce *big.Int, to *common.Address, amount *big.Int, gasLimit *big.Int, gasPrice *big.Int, blockLimit *big.Int, data []byte, chainId *big.Int, groupId *big.Int, extraData []byte, smcrypto bool) *Transaction { 50 | if len(data) > 0 { 51 | data = common.CopyBytes(data) 52 | } 53 | d := txdata{ 54 | AccountNonce: nonce, 55 | Recipient: to, 56 | Payload: data, 57 | Amount: new(big.Int), 58 | GasLimit: gasLimit, 59 | BlockLimit: blockLimit, 60 | Price: new(big.Int), 61 | ChainID: new(big.Int), 62 | GroupID: new(big.Int), 63 | ExtraData: extraData, 64 | 65 | V: new(big.Int), 66 | R: new(big.Int), 67 | S: new(big.Int), 68 | } 69 | if amount != nil { 70 | d.Amount.Set(amount) 71 | } 72 | if gasPrice != nil { 73 | d.Price.Set(gasPrice) 74 | } 75 | if chainId != nil { 76 | d.ChainID.Set(chainId) 77 | } 78 | if groupId != nil { 79 | d.GroupID.Set(groupId) 80 | } 81 | if extraData != nil { 82 | d.ExtraData = extraData 83 | } 84 | 85 | return &Transaction{data: d, smcrypto: smcrypto} 86 | } 87 | 88 | // EncodeRLP implements rlp.Encoder 89 | func (tx *Transaction) EncodeRLP(w io.Writer) error { 90 | return rlp.Encode(w, &tx.data) 91 | } 92 | 93 | // DecodeRLP implements rlp.Decoder 94 | func (tx *Transaction) DecodeRLP(s *rlp.Stream) error { 95 | _, size, _ := s.Kind() 96 | err := s.Decode(&tx.data) 97 | if err == nil { 98 | tx.size.Store(common.StorageSize(rlp.ListSize(size))) 99 | } 100 | 101 | return err 102 | } 103 | 104 | func (tx *Transaction) SignData(priKey key.PrivateKeyProvider) ([]byte, error) { 105 | //txb, _ := rlp.EncodeToBytes(tx.data) 106 | 107 | if tx.smcrypto { 108 | 109 | txb := priKey.Hash(SM3HashNonSig(tx)) 110 | 111 | r, s, pub, err := priKey.SignTx(txb) 112 | if err != nil { 113 | return nil, err 114 | } 115 | 116 | tx.data.V = pub 117 | tx.data.R = r 118 | tx.data.S = s 119 | } else { 120 | txb := Hash(tx).Bytes() 121 | r, s, v, err := priKey.SignTx(txb) 122 | if err != nil { 123 | return nil, err 124 | } 125 | tx.data.V = v 126 | tx.data.R = r 127 | tx.data.S = s 128 | } 129 | 130 | txd, _ := rlp.EncodeToBytes(tx.data) 131 | return txd, nil 132 | 133 | } 134 | 135 | func rlpHash(x interface{}) (h common.Hash) { 136 | hw := sha3.NewLegacyKeccak256() 137 | rlp.Encode(hw, x) 138 | hw.Sum(h[:0]) 139 | return h 140 | } 141 | 142 | func Hash(tx *Transaction) common.Hash { 143 | return rlpHash([]interface{}{ 144 | tx.data.AccountNonce, 145 | tx.data.Price, 146 | tx.data.GasLimit, 147 | tx.data.BlockLimit, 148 | tx.data.Recipient, 149 | tx.data.Amount, 150 | tx.data.Payload, 151 | tx.data.ChainID, 152 | tx.data.GroupID, 153 | tx.data.ExtraData, 154 | }) 155 | } 156 | 157 | func SM3HashNonSig(tx *Transaction) []byte { 158 | var src []byte 159 | buf := bytes.NewBuffer(src) 160 | rlp.Encode(buf, []interface{}{ 161 | tx.data.AccountNonce, 162 | tx.data.Price, 163 | tx.data.GasLimit, 164 | tx.data.BlockLimit, 165 | tx.data.Recipient, 166 | tx.data.Amount, 167 | tx.data.Payload, 168 | tx.data.ChainID, 169 | tx.data.GroupID, 170 | tx.data.ExtraData, 171 | }) 172 | 173 | return buf.Bytes() 174 | } 175 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_node_test.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | config2 "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/config" 7 | req "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/node" 8 | "github.com/BSNDA/bsn-sdk-crypto/common" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func getFabricClient(t *testing.T) *FabricClient { 14 | 15 | //if Call test net 16 | //Uncomment code 17 | //config2.SetTest() 18 | 19 | api := "http://192.168.1.61:17512" 20 | userCode := "USER0001202108171423128315082" 21 | appCode := "app0001202204251015286226029" 22 | 23 | privK := `-----BEGIN PRIVATE KEY----- 24 | MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQglETKLei6cn/6KwEU 25 | IPINz6tOMWE/eJGNZVtTu65xtjOgCgYIKoEcz1UBgi2hRANCAATnpj8cIMAWCVZM 26 | QpCKmYv2FBF+6Q0mQvPGfySWQn95CSt9xSL/0FIF7H7qQtn5D5PWhatLPurAo1z1 27 | ye9gfY6d 28 | -----END PRIVATE KEY-----` 29 | config2.SetTest() 30 | 31 | config, err := config2.NewConfig(api, userCode, appCode, privK, "E:\\test") 32 | 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | 37 | fabricClient, err := InitFabricClient(config, WithDefaultNodeName("a")) 38 | 39 | if err != nil { 40 | t.Fatal(err) 41 | } 42 | return fabricClient 43 | } 44 | 45 | func TestFabricClient_SdkTran(t *testing.T) { 46 | 47 | fabricClient := getFabricClient(t) 48 | 49 | name := "user20220421" 50 | 51 | user, _ := fabricClient.LoadUser(name) 52 | 53 | var args []string 54 | args = append(args, "{\"baseKey\":\"test202110333\",\"baseValue\":\"this is string \"}") 55 | //args = append(args,"key1","value") 56 | body := req.TransReqDataBody{ 57 | UserName: name, 58 | ChainCode: "cc_app0001202204201700217624980_01", 59 | FuncName: "set", 60 | Args: args, 61 | TransientMap: make(map[string]string), 62 | } 63 | 64 | res, err := fabricClient.SdkTran(body, user) 65 | if err != nil { 66 | t.Fatal(err) 67 | } 68 | fmt.Println(res) 69 | 70 | } 71 | 72 | func TestFabricClient_SdkTranQ(t *testing.T) { 73 | 74 | fabricClient := getFabricClient(t) 75 | 76 | name := "user20220421" 77 | var args []string 78 | args = append(args, "test202110333") 79 | //args = append(args,"key1","value") 80 | body := req.TransReqDataBody{ 81 | UserName: name, 82 | ChainCode: "cc_app0001202204201700217624980_01", 83 | FuncName: "get", 84 | Args: args, 85 | TransientMap: make(map[string]string), 86 | } 87 | 88 | res, err := fabricClient.SdkTran(body, nil) 89 | if err != nil { 90 | t.Fatal(err) 91 | } 92 | fmt.Println(res) 93 | 94 | } 95 | 96 | func TestFabricClient_ReqChainCode(t *testing.T) { 97 | 98 | fabricClient := getFabricClient(t) 99 | 100 | name := "" 101 | 102 | var args []string 103 | //args = append(args, "test2020104") 104 | args = append(args, "{\"baseKey\":\"test20210926\",\"baseValue\":\"this is string11 \"}") 105 | //args = append(args, "key1", "value") 106 | nonce, _ := common.GetRandomNonce() 107 | 108 | body := req.TransReqDataBody{ 109 | UserName: name, 110 | Nonce: base64.StdEncoding.EncodeToString(nonce), 111 | ChainCode: "cc_app0001202111121647396153631_01", 112 | FuncName: "set", 113 | Args: args, 114 | TransientMap: make(map[string]string), 115 | } 116 | 117 | res, _ := fabricClient.ReqChainCode(body) 118 | 119 | fmt.Println(res) 120 | 121 | } 122 | 123 | func TestFabricClient_GetTransInfo(t *testing.T) { 124 | fabricClient := getFabricClient(t) 125 | 126 | tx := req.TxTransReqDataBody{ 127 | TxId: "623edd1185c1cdc32b54904eba107fee2f10938b6c446ca829642a2e10101aa9", 128 | } 129 | 130 | res, _ := fabricClient.GetTransInfo(tx) 131 | 132 | fmt.Println(res) 133 | if res.Header.Code == 0 { 134 | tm := time.Unix(res.Body.TimeSpanSec, res.Body.TimeSpanNsec) 135 | 136 | fmt.Println(tm.Format("2006-01-02 15:04:05.000 -0700 MST")) 137 | } 138 | 139 | } 140 | func TestFabricClient_GetTransDataInfo(t *testing.T) { 141 | fabricClient := getFabricClient(t) 142 | 143 | tx := req.TxTransReqDataBody{ 144 | TxId: "55fcfe1e48fb96ffd2cf63501e7fd3e5460a456239c8b3956a8ef71305886822", 145 | } 146 | 147 | res, trans, _ := fabricClient.GetTransData(tx) 148 | 149 | fmt.Println(trans) 150 | fmt.Println(res) 151 | 152 | } 153 | 154 | func TestFabricClient_GetBlockInfo(t *testing.T) { 155 | 156 | fabricClient := getFabricClient(t) 157 | 158 | tx := req.BlockReqDataBody{ 159 | BlockNumber: 1, 160 | //BlockHash: "f66e68e0ca0e45f092ec55aeb1a503afda35ab234d6da527bfb7d8abbc004d2a", 161 | //TxId: "d3715eac4e4af04e2662da21461e04887ebbde1aafd70d283e1900ced3b1a0fd", 162 | } 163 | 164 | res, _ := fabricClient.GetBlockInfo(tx) 165 | 166 | fmt.Println(res) 167 | 168 | } 169 | 170 | func TestFabricClient_GetLedgerInfo(t *testing.T) { 171 | 172 | fabricClient := getFabricClient(t) 173 | 174 | res, _ := fabricClient.GetLedgerInfo() 175 | 176 | fmt.Println(res.Mac) 177 | fmt.Println(res.GetEncryptionValue()) 178 | 179 | } 180 | 181 | func TestFabricClient_GetBlockDataInfo(t *testing.T) { 182 | 183 | fabricClient := getFabricClient(t) 184 | 185 | tx := req.BlockReqDataBody{ 186 | //BlockHash: "f66e68e0ca0e45f092ec55aeb1a503afda35ab234d6da527bfb7d8abbc004d2a", 187 | BlockNumber: 1, 188 | //TxId: "d3715eac4e4af04e2662da21461e04887ebbde1aafd70d283e1900ced3b1a0fd", 189 | } 190 | 191 | _, block, _ := fabricClient.GetBlockData(tx) 192 | 193 | fmt.Println(block) 194 | 195 | } 196 | -------------------------------------------------------------------------------- /pkg/client/fabric/fabricClient_node.go: -------------------------------------------------------------------------------- 1 | package fabric 2 | 3 | import ( 4 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/msp" 5 | nodereq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/fabric/node" 6 | noderes "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/fabric/node" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/fabric" 8 | "github.com/hyperledger/fabric-protos-go/common" 9 | pb "github.com/hyperledger/fabric-protos-go/peer" 10 | "github.com/pkg/errors" 11 | "github.com/wonderivan/logger" 12 | 13 | blockconvert "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/fabric" 14 | ) 15 | 16 | const ( 17 | ReqChainCode = "node/reqChainCode" 18 | SDKTran = "node/trans" 19 | GetTransInfo = "node/getTransaction" 20 | GetTransData = "node/getTransdata" 21 | GetBlockInfo = "node/getBlockInfo" 22 | GetBlockData = "node/getBlockData" 23 | GetLedgerInfo = "node/getLedgerInfo" 24 | ) 25 | 26 | // SdkTran Dapp transaction in key upload mode 27 | func (c *FabricClient) SdkTran(body nodereq.TransReqDataBody, user *msp.UserData) (*noderes.TranResData, error) { 28 | 29 | var err error 30 | if user == nil { 31 | user, err = c.LoadUser(body.UserName) 32 | if err != nil { 33 | return nil, errors.WithMessagef(err, "user [%s] load failed", body.UserName) 34 | } 35 | } 36 | 37 | request := body.GetTransRequest(c.appInfo.ChannelId) 38 | transData, _, err := fabric.CreateRequest(user, request) 39 | 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | data := &nodereq.SdkTransReqData{} 45 | data.Header = c.GetHeader() 46 | data.Body = nodereq.SdkTransReqDataBody{ 47 | TransData: transData, 48 | } 49 | res := &noderes.TranResData{} 50 | err = c.Call(SDKTran, data, res) 51 | 52 | if err != nil { 53 | logger.Error("return parameter serialization failed:", err) 54 | return nil, err 55 | } 56 | 57 | return res, nil 58 | 59 | } 60 | 61 | // ReqChainCode Dapp transaction in public key trust mode 62 | func (c *FabricClient) ReqChainCode(body nodereq.TransReqDataBody) (*noderes.TranResData, error) { 63 | 64 | req := &nodereq.TransReqData{} 65 | req.Header = c.GetHeader() 66 | req.Body = body 67 | 68 | res := &noderes.TranResData{} 69 | 70 | err := c.Call(ReqChainCode, req, res) 71 | if err != nil { 72 | return nil, errors.WithMessagef(err, "call %s has error", ReqChainCode) 73 | } 74 | return res, nil 75 | } 76 | 77 | // GetTransInfo query fabric transaction 78 | func (c *FabricClient) GetTransInfo(body nodereq.TxTransReqDataBody) (*noderes.TransactionResData, error) { 79 | 80 | req := &nodereq.TxTransReqData{} 81 | req.Header = c.GetHeader() 82 | req.Body = body 83 | 84 | res := &noderes.TransactionResData{} 85 | 86 | err := c.Call(GetTransInfo, req, res) 87 | if err != nil { 88 | return nil, errors.WithMessagef(err, "call %s has error", GetTransInfo) 89 | } 90 | return res, nil 91 | } 92 | 93 | // GetTransData query fabric transaction, 94 | // but the return data is "peer.ProcessedTransaction" serialized bytes after Base64 encoding . 95 | func (c *FabricClient) GetTransData(body nodereq.TxTransReqDataBody) (*noderes.TranDataRes, *pb.ProcessedTransaction, error) { 96 | 97 | req := &nodereq.TxTransReqData{} 98 | req.Header = c.GetHeader() 99 | req.Body = body 100 | 101 | res := &noderes.TranDataRes{} 102 | 103 | err := c.Call(GetTransData, req, res) 104 | if err != nil { 105 | return nil, nil, errors.WithMessagef(err, "call %s has error", GetTransData) 106 | } 107 | 108 | trans := &pb.ProcessedTransaction{} 109 | trans, err = blockconvert.ConvertToTran(res.Body.TransData) 110 | if err != nil { 111 | logger.Error("convertTrans failed,errmessage:", err) 112 | return res, nil, err 113 | } 114 | return res, trans, nil 115 | } 116 | 117 | // GetBlockInfo query fabric block data 118 | func (c *FabricClient) GetBlockInfo(body nodereq.BlockReqDataBody) (*noderes.BlockResData, error) { 119 | 120 | req := &nodereq.BlockReqData{} 121 | req.Header = c.GetHeader() 122 | req.Body = body 123 | 124 | res := &noderes.BlockResData{} 125 | 126 | err := c.Call(GetBlockInfo, req, res) 127 | if err != nil { 128 | return nil, errors.WithMessagef(err, "call %s has error", GetBlockInfo) 129 | } 130 | return res, nil 131 | } 132 | 133 | // GetBlockData query fabric block data 134 | // but the return data is "common.Block" serialized bytes after Base64 encoding . 135 | func (c *FabricClient) GetBlockData(body nodereq.BlockReqDataBody) (*noderes.BlockDataRes, *common.Block, error) { 136 | 137 | req := &nodereq.BlockReqData{} 138 | req.Header = c.GetHeader() 139 | req.Body = body 140 | 141 | res := &noderes.BlockDataRes{} 142 | 143 | err := c.Call(GetBlockData, req, res) 144 | if err != nil { 145 | return nil, nil, errors.WithMessagef(err, "call %s has error", GetBlockData) 146 | } 147 | 148 | block := &common.Block{} 149 | if len(res.Body.BlockData) > 0 { 150 | block, err = blockconvert.ConvertToBlock(res.Body.BlockData) 151 | if err != nil { 152 | logger.Error("convertBlock failed,errmessage:", err) 153 | return res, nil, err 154 | } 155 | } 156 | 157 | return res, block, nil 158 | } 159 | 160 | // GetBlockData query fabric ledger data 161 | func (c *FabricClient) GetLedgerInfo() (*noderes.LedgerResData, error) { 162 | 163 | req := &nodereq.LedgerReqData{} 164 | req.Header = c.GetHeader() 165 | 166 | res := &noderes.LedgerResData{} 167 | 168 | err := c.Call(GetLedgerInfo, req, res) 169 | if err != nil { 170 | return nil, errors.WithMessagef(err, "call %s has error", GetLedgerInfo) 171 | } 172 | 173 | return res, nil 174 | } 175 | -------------------------------------------------------------------------------- /pkg/core/trans/xuperchain/trans.go: -------------------------------------------------------------------------------- 1 | package xuperchain 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/xuperchain/account" 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/xuperchain/common" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/xuperchain/crypto" 9 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/xuperchain/pb" 10 | "time" 11 | ) 12 | 13 | //GenerateInvokeIR 14 | func GenerateInvokeIR(contractName, methodName string, args map[string][]byte) *pb.InvokeRequest { 15 | return &pb.InvokeRequest{ 16 | ModuleName: "wasm", 17 | MethodName: methodName, 18 | ContractName: contractName, 19 | Args: args, 20 | } 21 | } 22 | 23 | //GenerateTransaction 24 | func GenerateTransaction(initiator string, response *pb.InvokeResponse, privatekey, publickey string) (*pb.Transaction, error) { 25 | var err error 26 | tx := &pb.Transaction{ 27 | Desc: []byte("sdk contract transaction"), 28 | Version: common.TxVersion, 29 | Coinbase: false, 30 | Timestamp: time.Now().UnixNano(), 31 | Initiator: initiator, 32 | } 33 | tx.TxInputsExt = response.GetInputs() 34 | tx.TxOutputsExt = response.GetOutputs() 35 | tx.ContractRequests = response.GetRequests() 36 | 37 | err = common.SetSeed() 38 | if err != nil { 39 | return nil, err 40 | } 41 | tx.Nonce = common.GetNonce() 42 | 43 | digestHash, err := makeTxDigestHash(tx) 44 | if err != nil { 45 | return nil, err 46 | } 47 | pKey, err := account.GetEcdsaPrivateKey(privatekey) 48 | if err != nil { 49 | return nil, err 50 | } 51 | cryptoClient := crypto.GetGmCryptoClient() 52 | sign, err := cryptoClient.SignECDSA(pKey, digestHash) 53 | if err != nil { 54 | return nil, err 55 | } 56 | pukJsonStr, err := account.GetEcdsaPublicKeyJsonFormatFromPublicKey(publickey) 57 | if err != nil { 58 | return nil, err 59 | } 60 | signatureInfo := &pb.SignatureInfo{ 61 | PublicKey: pukJsonStr, 62 | Sign: sign, 63 | } 64 | var signatureInfos []*pb.SignatureInfo 65 | signatureInfos = append(signatureInfos, signatureInfo) 66 | tx.InitiatorSigns = signatureInfos 67 | tx.Txid, _ = makeTransactionID(tx) 68 | return tx, nil 69 | } 70 | 71 | // makeTxDigestHash 72 | func makeTxDigestHash(tx *pb.Transaction) ([]byte, error) { 73 | coreData, err := encodeTxData(tx, false) 74 | if err != nil { 75 | return nil, err 76 | } 77 | 78 | cryptoClient := crypto.GetXchainCryptoClient() 79 | txHash := cryptoClient.HashUsingDoubleSha256(coreData) 80 | 81 | return txHash, nil 82 | } 83 | 84 | // makeTransactionID 85 | func makeTransactionID(tx *pb.Transaction) ([]byte, error) { 86 | coreData, err := encodeTxData(tx, true) 87 | if err != nil { 88 | return nil, err 89 | } 90 | 91 | cryptoClient := crypto.GetXchainCryptoClient() 92 | txid := cryptoClient.HashUsingDoubleSha256(coreData) 93 | 94 | return txid, nil 95 | } 96 | 97 | // encodeTxData 98 | func encodeTxData(tx *pb.Transaction, includeSigns bool) ([]byte, error) { 99 | var buf bytes.Buffer 100 | encoder := json.NewEncoder(&buf) 101 | for _, txInput := range tx.TxInputs { 102 | if len(txInput.RefTxid) > 0 { 103 | err := encoder.Encode(txInput.RefTxid) 104 | if err != nil { 105 | return nil, err 106 | } 107 | } 108 | err := encoder.Encode(txInput.RefOffset) 109 | if err != nil { 110 | return nil, err 111 | } 112 | if len(txInput.FromAddr) > 0 { 113 | err = encoder.Encode(txInput.FromAddr) 114 | if err != nil { 115 | return nil, err 116 | } 117 | } 118 | if len(txInput.Amount) > 0 { 119 | err = encoder.Encode(txInput.Amount) 120 | if err != nil { 121 | return nil, err 122 | } 123 | } 124 | err = encoder.Encode(txInput.FrozenHeight) 125 | if err != nil { 126 | return nil, err 127 | } 128 | } 129 | err := encoder.Encode(tx.TxOutputs) 130 | if err != nil { 131 | return nil, err 132 | } 133 | if len(tx.Desc) > 0 { 134 | err = encoder.Encode(tx.Desc) 135 | if err != nil { 136 | return nil, err 137 | } 138 | } 139 | err = encoder.Encode(tx.Nonce) 140 | if err != nil { 141 | return nil, err 142 | } 143 | err = encoder.Encode(tx.Timestamp) 144 | if err != nil { 145 | return nil, err 146 | } 147 | err = encoder.Encode(tx.Version) 148 | if err != nil { 149 | return nil, err 150 | } 151 | for _, txInputExt := range tx.TxInputsExt { 152 | if err = encoder.Encode(txInputExt.Bucket); err != nil { 153 | return nil, err 154 | } 155 | if len(txInputExt.Key) > 0 { 156 | if err = encoder.Encode(txInputExt.Key); err != nil { 157 | return nil, err 158 | } 159 | } 160 | if len(txInputExt.RefTxid) > 0 { 161 | if err = encoder.Encode(txInputExt.RefTxid); err != nil { 162 | return nil, err 163 | } 164 | } 165 | if err = encoder.Encode(txInputExt.RefOffset); err != nil { 166 | return nil, err 167 | } 168 | } 169 | for _, txOutputExt := range tx.TxOutputsExt { 170 | if err = encoder.Encode(txOutputExt.Bucket); err != nil { 171 | return nil, err 172 | } 173 | if len(txOutputExt.Key) > 0 { 174 | if err = encoder.Encode(txOutputExt.Key); err != nil { 175 | return nil, err 176 | } 177 | } 178 | if len(txOutputExt.Value) > 0 { 179 | if err = encoder.Encode(txOutputExt.Value); err != nil { 180 | return nil, err 181 | } 182 | } 183 | } 184 | if err = encoder.Encode(tx.ContractRequests); err != nil { 185 | return nil, err 186 | } 187 | if err = encoder.Encode(tx.Initiator); err != nil { 188 | return nil, err 189 | } 190 | if err = encoder.Encode(tx.AuthRequire); err != nil { 191 | return nil, err 192 | } 193 | if includeSigns { 194 | if err = encoder.Encode(tx.InitiatorSigns); err != nil { 195 | return nil, err 196 | } 197 | if err = encoder.Encode(tx.AuthRequireSigns); err != nil { 198 | return nil, err 199 | } 200 | if tx.GetXuperSign() != nil { 201 | err = encoder.Encode(tx.AuthRequireSigns) 202 | if err != nil { 203 | return nil, err 204 | } 205 | } 206 | } 207 | if err = encoder.Encode(tx.Coinbase); err != nil { 208 | return nil, err 209 | } 210 | if err = encoder.Encode(tx.Autogen); err != nil { 211 | return nil, err 212 | } 213 | 214 | if tx.Version >= 2 { 215 | if err = encoder.Encode(tx.HDInfo); err != nil { 216 | return nil, err 217 | } 218 | } 219 | return buf.Bytes(), nil 220 | } 221 | -------------------------------------------------------------------------------- /pkg/common/cache/proc/proc.go: -------------------------------------------------------------------------------- 1 | package proc 2 | 3 | import ( 4 | "encoding/gob" 5 | "fmt" 6 | "io" 7 | "os" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | const ( 13 | NoExpiration time.Duration = -1 //No expiration mark 14 | defaultExpiration time.Duration = 0 // default non-expired (expiration time in ns) 15 | ) 16 | 17 | type Item struct { 18 | Object interface{} //data item 19 | Expiration int64 //expiration time of data item (0 never expires) 20 | IsSlide bool // slide out of date or not 21 | Dur time.Duration //duration 22 | } 23 | 24 | type Cache struct { 25 | defaultExpiration time.Duration //use if the data item is not specified to expire 26 | items map[string]Item 27 | mu sync.RWMutex //read-write lock 28 | gcInterval time.Duration //gc cycle 29 | stopGc chan bool // stop gc channel ID 30 | } 31 | 32 | func (item Item) IsExpired() bool { 33 | if item.Expiration == 0 { 34 | return false 35 | } 36 | return time.Now().UnixNano() > item.Expiration //expire if it exceeds the time 37 | } 38 | 39 | //repeat gc 40 | func (c *Cache) gcLoop() { 41 | ticker := time.NewTicker(c.gcInterval) //initialize a timer 42 | for { 43 | select { 44 | case <-ticker.C: 45 | c.DeleteExpired() 46 | case <-c.stopGc: 47 | ticker.Stop() 48 | return 49 | } 50 | } 51 | } 52 | 53 | //delete expired cache 54 | func (c *Cache) DeleteExpired() { 55 | now := time.Now().UnixNano() 56 | c.mu.Lock() 57 | defer c.mu.Unlock() 58 | for k, v := range c.items { 59 | if v.Expiration > 0 && now > v.Expiration { 60 | c.delete(k) 61 | } 62 | } 63 | } 64 | 65 | //delete 66 | func (c *Cache) delete(k string) { 67 | delete(c.items, k) 68 | } 69 | 70 | //operate deletion 71 | func (c *Cache) Delete(k string) { 72 | c.mu.Lock() 73 | c.delete(k) 74 | defer c.mu.Unlock() 75 | } 76 | 77 | //set the data item of cache, overwrite it if it is set, isSlide expired or not when d expires 78 | func (c *Cache) Set(k string, v interface{}, d time.Duration, isSlide bool) { 79 | var e int64 80 | if d == defaultExpiration { 81 | d = c.defaultExpiration 82 | } 83 | if d > 0 { 84 | e = time.Now().Add(d).UnixNano() 85 | } 86 | c.mu.Lock() 87 | defer c.mu.Unlock() 88 | c.items[k] = Item{ 89 | Object: v, 90 | Expiration: e, 91 | IsSlide: isSlide, 92 | Dur: d, 93 | } 94 | } 95 | 96 | //set data item, lock-free operation 97 | func (c *Cache) set(k string, v interface{}, d time.Duration) { 98 | var e int64 99 | if d == defaultExpiration { 100 | d = c.defaultExpiration 101 | } 102 | if d > 0 { 103 | e = time.Now().Add(d).UnixNano() 104 | } 105 | c.items[k] = Item{ 106 | Object: v, 107 | Expiration: e, 108 | } 109 | } 110 | 111 | //Get the data item, to see if expired 112 | func (c *Cache) get(k string) (interface{}, bool) { 113 | item, found := c.items[k] 114 | if !found || item.IsExpired() { 115 | return nil, false 116 | } 117 | 118 | if item.IsSlide { 119 | c.Set(k, item.Object, item.Dur, true) 120 | } 121 | 122 | return item.Object, true 123 | } 124 | 125 | //add new operations, if data item exists, then error 126 | func (c *Cache) Add(k string, v interface{}, d time.Duration) error { 127 | c.mu.Lock() 128 | _, found := c.get(k) 129 | if found { 130 | c.mu.Unlock() 131 | return fmt.Errorf("Item %s already exists", k) 132 | } 133 | c.set(k, v, d) 134 | c.mu.Unlock() 135 | return nil 136 | } 137 | 138 | //Get cache 139 | func (c *Cache) Get(k string) (interface{}, bool) { 140 | c.mu.RLock() 141 | item, found := c.items[k] 142 | if !found || item.IsExpired() { 143 | c.mu.RUnlock() 144 | return nil, false 145 | } 146 | c.mu.RUnlock() 147 | 148 | if item.IsSlide { 149 | c.Set(k, item.Object, item.Dur, true) 150 | } 151 | 152 | return item.Object, true 153 | } 154 | 155 | //replace 156 | func (c *Cache) Replace(k string, v interface{}, d time.Duration) error { 157 | c.mu.Lock() 158 | _, found := c.get(k) 159 | if !found { 160 | c.mu.Unlock() 161 | return fmt.Errorf("Item %s does't exists", k) 162 | } 163 | c.set(k, v, d) 164 | c.mu.Unlock() 165 | return nil 166 | } 167 | 168 | // input cache data to io.Writer 169 | func (c *Cache) Save(w io.Writer) (err error) { 170 | enc := gob.NewEncoder(w) 171 | defer func() { 172 | if x := recover(); x != nil { 173 | err = fmt.Errorf("Error Registering item types with gob library") 174 | } 175 | }() 176 | c.mu.RLock() 177 | defer c.mu.RUnlock() 178 | for _, v := range c.items { 179 | gob.Register(v.Object) 180 | } 181 | err = enc.Encode(&c.items) 182 | return 183 | } 184 | 185 | //serialize to file 186 | func (c *Cache) SaveToFile(filename string) error { 187 | f, err := os.Create(filename) 188 | if err != nil { 189 | return err 190 | } 191 | if err = c.Save(f); err != nil { 192 | f.Close() 193 | return err 194 | } 195 | return f.Close() 196 | } 197 | 198 | //load from io.Reader 199 | func (c *Cache) Load(r io.Reader) error { 200 | dec := gob.NewDecoder(r) 201 | items := make(map[string]Item, 0) 202 | err := dec.Decode(&items) 203 | if err != nil { 204 | return err 205 | } 206 | c.mu.Lock() 207 | defer c.mu.Unlock() 208 | for k, v := range items { 209 | obj, ok := c.items[k] 210 | if !ok || obj.IsExpired() { 211 | c.items[k] = v 212 | } 213 | } 214 | return nil 215 | } 216 | 217 | //load from file 218 | func (c *Cache) LoadFromFile(filename string) error { 219 | f, err := os.Open(filename) 220 | if err != nil { 221 | return err 222 | } 223 | if err = c.Load(f); err != nil { 224 | f.Close() 225 | return err 226 | } 227 | return f.Close() 228 | } 229 | 230 | //number of data items in the return cache 231 | func (c *Cache) Count() int { 232 | c.mu.RLock() 233 | defer c.mu.RUnlock() 234 | return len(c.items) 235 | } 236 | 237 | //clear the cache 238 | func (c *Cache) Flush() { 239 | c.mu.Lock() 240 | defer c.mu.Unlock() 241 | c.items = map[string]Item{} 242 | } 243 | 244 | //stop gc 245 | func (c *Cache) StopGc() { 246 | c.stopGc <- true 247 | } 248 | 249 | //create a new cache system 250 | func NewCache(defaultExpiration, gcInterval time.Duration) (c *Cache) { 251 | c = &Cache{ 252 | defaultExpiration: defaultExpiration, 253 | gcInterval: gcInterval, 254 | items: map[string]Item{}, 255 | stopGc: make(chan bool), 256 | } 257 | go c.gcLoop() 258 | return 259 | } 260 | -------------------------------------------------------------------------------- /pkg/client/cita/citaClient_node.go: -------------------------------------------------------------------------------- 1 | package cita 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | 7 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/errors" 8 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/common/http" 9 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/enum" 10 | nodereq "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/req/cita/node" 11 | noderes "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/entity/res/cita/node" 12 | "github.com/BSNDA/PCNGateway-Go-SDK/pkg/core/trans/cita" 13 | "github.com/wonderivan/logger" 14 | ) 15 | 16 | //DApp transaction in public key trust mode 17 | func (c *CitaClient) ReqChainCode(body nodereq.TransReqDataBody) (*noderes.TransResData, error) { 18 | url := c.GetURL("/api/cita/v1/node/reqChainCode") 19 | 20 | data := &nodereq.TransReqData{} 21 | data.Header = c.GetHeader() 22 | data.Body = body 23 | data.Mac = c.Sign(data.GetEncryptionValue()) 24 | 25 | reqBytes, _ := json.Marshal(data) 26 | 27 | resBytes, err := http.SendPost(reqBytes, url) 28 | if err != nil { 29 | logger.Error("gateway interface call failed:", err) 30 | return nil, err 31 | } 32 | res := &noderes.TransResData{} 33 | 34 | err = json.Unmarshal(resBytes, res) 35 | 36 | if err != nil { 37 | logger.Error("return parameter serialization failed:", err) 38 | return nil, err 39 | } 40 | 41 | return res, nil 42 | } 43 | 44 | //get block information 45 | func (c *CitaClient) GetBlockInfo(body nodereq.BlockReqDataBody) (*noderes.BlockResData, error) { 46 | 47 | url := c.GetURL("/api/cita/v1/node/getBlockInfo") 48 | data := &nodereq.BlockReqData{} 49 | data.Header = c.GetHeader() 50 | data.Body = body 51 | data.Mac = c.Sign(data.GetEncryptionValue()) 52 | 53 | reqBytes, _ := json.Marshal(data) 54 | 55 | resBytes, err := http.SendPost(reqBytes, url) 56 | if err != nil { 57 | logger.Error("gateway interface call failed:", err) 58 | return nil, err 59 | } 60 | res := &noderes.BlockResData{} 61 | 62 | err = json.Unmarshal(resBytes, res) 63 | 64 | if err != nil { 65 | logger.Error("return parameter serialization failed:", err) 66 | return nil, err 67 | } 68 | 69 | return res, nil 70 | } 71 | 72 | //get block height 73 | func (c *CitaClient) GetBlockHeight() (*noderes.BlockHeightResData, error) { 74 | 75 | url := c.GetURL("/api/cita/v1/node/getBlockHeight") 76 | data := &nodereq.BlockReqData{} 77 | data.Header = c.GetHeader() 78 | 79 | data.Mac = c.Sign(data.GetEncryptionValue()) 80 | 81 | reqBytes, _ := json.Marshal(data) 82 | 83 | resBytes, err := http.SendPost(reqBytes, url) 84 | if err != nil { 85 | logger.Error("gateway interface call failed:", err) 86 | return nil, err 87 | } 88 | res := &noderes.BlockHeightResData{} 89 | 90 | err = json.Unmarshal(resBytes, res) 91 | 92 | if err != nil { 93 | logger.Error("return parameter serialization failed:", err) 94 | return nil, err 95 | } 96 | 97 | return res, nil 98 | } 99 | 100 | //get transaction Receipt 101 | func (c *CitaClient) GetTxReceiptByTxHash(body nodereq.TxTransReqDataBody) (*noderes.BlockTxReceiptResData, error) { 102 | 103 | url := c.GetURL("/api/cita/v1/node/getTxReceiptByTxHash") 104 | 105 | data := &nodereq.TxTransReqData{} 106 | data.Header = c.GetHeader() 107 | data.Body = body 108 | data.Mac = c.Sign(data.GetEncryptionValue()) 109 | 110 | reqBytes, _ := json.Marshal(data) 111 | 112 | resBytes, err := http.SendPost(reqBytes, url) 113 | 114 | if err != nil { 115 | logger.Error("gateway interface call failed:", err) 116 | return nil, err 117 | } 118 | 119 | res := &noderes.BlockTxReceiptResData{} 120 | 121 | err = json.Unmarshal(resBytes, res) 122 | 123 | if err != nil { 124 | logger.Error("return parameter serialization failed:", err) 125 | return nil, err 126 | } 127 | 128 | return res, nil 129 | } 130 | 131 | //get transaction information 132 | func (c *CitaClient) GetTxInfoByTxHash(body nodereq.TxTransReqDataBody) (*noderes.BlockTxResData, error) { 133 | 134 | url := c.GetURL("/api/cita/v1/node/getTxInfoByTxHash") 135 | 136 | data := &nodereq.TxTransReqData{} 137 | data.Header = c.GetHeader() 138 | data.Body = body 139 | data.Mac = c.Sign(data.GetEncryptionValue()) 140 | 141 | reqBytes, _ := json.Marshal(data) 142 | 143 | resBytes, err := http.SendPost(reqBytes, url) 144 | 145 | if err != nil { 146 | logger.Error("gateway interface call failed:", err) 147 | return nil, err 148 | } 149 | 150 | res := &noderes.BlockTxResData{} 151 | 152 | err = json.Unmarshal(resBytes, res) 153 | 154 | if err != nil { 155 | logger.Error("return parameter serialization failed:", err) 156 | return nil, err 157 | } 158 | 159 | return res, nil 160 | } 161 | 162 | //DApp transaction in public key upload mode 163 | func (c *CitaClient) Trans(data nodereq.TransData) (*noderes.TransResData, error) { 164 | if c.Config.GetAppInfo().CAType == enum.AppCaType_Trust { 165 | return nil, errors.New("the trusteeship application cannot call the api") 166 | } 167 | url := c.GetURL("/api/cita/v1/node/trans") 168 | 169 | tx, err := c.getTransData(data) 170 | if err != nil { 171 | return nil, err 172 | } 173 | 174 | reqData := &nodereq.KeyTransReqData{} 175 | reqData.Header = c.GetHeader() 176 | reqData.Body = nodereq.KeyTransReqDataBody{ 177 | ContractName: data.Contract.ContractName, 178 | TransData: tx, 179 | } 180 | reqData.Mac = c.Sign(reqData.GetEncryptionValue()) 181 | 182 | reqBytes, _ := json.Marshal(reqData) 183 | 184 | resBytes, err := http.SendPost(reqBytes, url) 185 | if err != nil { 186 | logger.Error("gateway interface call failed:", err) 187 | return nil, err 188 | } 189 | res := &noderes.TransResData{} 190 | 191 | err = json.Unmarshal(resBytes, res) 192 | 193 | fmt.Println(c.Verify(res.Mac, res.GetEncryptionValue())) 194 | 195 | if err != nil { 196 | logger.Error("return parameter serialization failed:", err) 197 | return nil, err 198 | } 199 | 200 | return res, nil 201 | } 202 | 203 | //splicing key upload mode transaction string 204 | func (c *CitaClient) getTransData(data nodereq.TransData) (string, error) { 205 | blockLimit, err := c.getBlockLimit() 206 | if err != nil { 207 | return "", err 208 | } 209 | chainId, version, err := c.getBaseInfo() 210 | if err != nil { 211 | return "", err 212 | } 213 | 214 | key, err := c.getUser(data.UserName) 215 | if err != nil { 216 | return "", err 217 | } 218 | 219 | tx, _, err := cita.TransData(data.Contract.ContractAbi, data.Contract.ContractAddress, data.FuncName, data.Args, blockLimit, chainId, version, c.isSM(), key) 220 | 221 | if err != nil { 222 | return "", err 223 | } else { 224 | return tx, nil 225 | } 226 | 227 | } 228 | --------------------------------------------------------------------------------