Commit 502e5138 authored by harrylee's avatar harrylee

update chain33-sdk-go

parent c29f9964
package client
const (
Chain33_Lock = "Chain33.Lock"
Chain33_UnLock = "Chain33.UnLock"
Chain33_SetPasswd = "Chain33.SetPasswd"
Chain33_SetLabel = "Chain33.SetLabel"
Chain33_NewAccount = "Chain33.NewAccount"
Chain33_GetAccounts = "Chain33.GetAccounts"
Chain33_MergeBalance = "Chain33.MergeBalance"
Chain33_SetTxFee = "Chain33.SetTxFee"
Chain33_SendToAddress = "Chain33.SendToAddress"
Chain33_ImportPrivKey = "Chain33.ImportPrivKey"
Chain33_WalletTransactionList = "Chain33.WalletTransactionList"
Chain33_GetTicketCount = "Chain33.GetTicketCount"
Chain33_DumpPrivkey = "Chain33.DumpPrivkey"
Chain33_SignRawTx = "Chain33.SignRawTx"
Chain33_GetMempool = "Chain33.GetMempool"
Chain33_SendTransaction = "Chain33.SendTransaction"
Chain33_CreateRawTransaction = "Chain33.CreateRawTransaction"
Chain33_SendRawTransaction = "Chain33.SendRawTransaction"
Chain33_QueryTransaction = "Chain33.QueryTransaction"
Chain33_GetTxByAddr = "Chain33.GetTxByAddr"
Chain33_GetTxByHashes = "Chain33.GetTxByHashes"
Chain33_GetHexTxByHash = "Chain33.GetHexTxByHash"
Chain33_GetAddrOverview = "Chain33.GetAddrOverview"
Chain33_Version = "Chain33.Version"
Chain33_GetBlocks = "Chain33.GetBlocks"
Chain33_GetLastHeader = "Chain33.GetLastHeader"
Chain33_GetHeaders = "Chain33.GetHeaders"
Chain33_GetBlockHash = "Chain33.GetBlockHash"
Chain33_GetBlockOverview = "Chain33.GetBlockOverview"
Chain33_GetPeerInfo = "Chain33.GetPeerInfo"
Chain33_GetNetInfo = "Chain33.GetNetInfo"
Chain33_GenSeed = "Chain33.GenSeed"
Chain33_SaveSeed = "Chain33.SaveSeed"
Chain33_GetSeed = "Chain33.GetSeed"
Chain33_GetWalletStatus = "Chain33.GetWalletStatus"
Chain33_GetBalance = "Chain33.GetBalance"
Chain33_GetTokenBalance = "Chain33.GetTokenBalance"
Chain33_Query = "Chain33.Query"
Para_IsSync = "paracross.IsSync"
Chain33_IsSync = "Chain33.IsSync"
)
\ No newline at end of file
...@@ -11,7 +11,14 @@ import ( ...@@ -11,7 +11,14 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
sdk "github.com/33cn/chain33-sdk-go"
"github.com/33cn/chain33-sdk-go/crypto"
"github.com/33cn/chain33-sdk-go/dapp/broker"
"github.com/33cn/chain33-sdk-go/dapp/storage"
"github.com/33cn/chain33-sdk-go/event"
"github.com/33cn/chain33-sdk-go/types"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"time"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
...@@ -120,9 +127,10 @@ func (client *JSONClient) Call(method string, params, resp interface{}) error { ...@@ -120,9 +127,10 @@ func (client *JSONClient) Call(method string, params, resp interface{}) error {
return json.Unmarshal(*cresp.Result, resp) return json.Unmarshal(*cresp.Result, resp)
} }
type ParseFunc func(result json.RawMessage) (interface{},error) type ParseFunc func(result json.RawMessage) (interface{}, error)
//回调函数,用于自定义解析返回得result数据 //回调函数,用于自定义解析返回得result数据
func (client *JSONClient) CallBack(method string, params interface{},parseFunc ParseFunc) (interface{}, error) { func (client *JSONClient) CallBack(method string, params interface{}, parseFunc ParseFunc) (interface{}, error) {
method = addPrefix(client.prefix, method) method = addPrefix(client.prefix, method)
req := &clientRequest{} req := &clientRequest{}
req.Method = method req.Method = method
...@@ -176,16 +184,334 @@ func (client *JSONClient) SendTransaction(signedTx string) (string, error) { ...@@ -176,16 +184,334 @@ func (client *JSONClient) SendTransaction(signedTx string) (string, error) {
return res, nil return res, nil
} }
//SendTransactionSync
func (client *JSONClient) SendTransactionSync(privkey string,tx *types.Transaction) (*Response, error) {
//签名
hexbytes, _ := types.FromHex(privkey)
sdk.Sign(tx, hexbytes, crypto.SECP256K1, nil)
signedTx := types.ToHexPrefix(types.Encode(tx))
var res string
send := &RawParm{
Token: "BTY",
Data: signedTx,
}
err := client.Call("Chain33.SendTransactionSync", send, &res)
if err != nil {
return nil, err
}
return &Response{OK:true,Message:res,Data:types.Encode(tx)}, nil
}
// 查询交易 // 查询交易
func (client *JSONClient) QueryTransaction(hash string) (*TransactionDetail, error) { func (client *JSONClient) QueryTransaction(hash string) (*TransactionDetail, error) {
query := QueryParm{ query := QueryParm{
Hash: hash, Hash: hash,
} }
var detail TransactionDetail var detail TransactionDetail
err := client.Call("Chain33.QueryTransaction", query, &detail) err := client.Call(Chain33_QueryTransaction, query, &detail)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &detail, nil return &detail, nil
} }
func (client *JSONClient) QueryLastHeader() (*Header, error) {
var res Header
err := client.Call(Chain33_GetLastHeader, nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (client *JSONClient) QueryBlockHash(height int64) (*ReplyHash, error) {
var res ReplyHash
params := types.ReqInt{
Height: height,
}
err := client.Call(Chain33_GetBlockHash, params, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (client *JSONClient) QueryHeadersByHeight(height int64) (*Headers, error) {
var res Headers
params := BlockParam{
Start: height - 1,
End: height - 1,
Isdetail: false,
}
err := client.Call(Chain33_GetHeaders, params, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (client *JSONClient) QueryIsSync() (bool, error) {
var res bool
err := client.Call(Para_IsSync, nil, &res)
if err != nil {
return false, err
}
return res, nil
}
func (client *JSONClient) QueryMainNetIsSync() (bool, error) {
var res bool
err := client.Call(Chain33_IsSync, nil, &res)
if err != nil {
return false, err
}
return res, nil
}
func (client *JSONClient) QueryNetInfo() (*NodeNetinfo, error) {
var res NodeNetinfo
params := types.ReqNil{}
err := client.Call(Chain33_GetNetInfo, params, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (client *JSONClient) QueryMempool(jrpcURl string) (*ReplyTxList, error) {
var res ReplyTxList
params := types.ReqNil{}
err := client.Call(Chain33_GetMempool, params, &res)
if err != nil {
return nil, err
}
return &res, nil
}
//获取区块信息
func (client *JSONClient) QueryBlockInfo(start, end int64, isDetail bool) (*BlockDetails, error) {
var res BlockDetails
params := BlockParam{Start: start, End: end, Isdetail: isDetail}
err := client.Call(Chain33_GetBlocks, params, &res)
if err != nil {
return nil, err
}
return &res, nil
}
//调用chaincode
func (client *JSONClient) Invoke(requst *Request,privateKey string) (*Response, error) {
//FIXME 这里需完善
if requst.Exec == storage.StorageX{
switch requst.Fcn {
case "set","ContentStorage":
tx,err:=storage.CreateContentStorageTx(client.prefix,0,string(requst.Args[0]),nil,string(requst.Args[1]))
if err!=nil {
return nil,err
}
return client.SendTransactionSync(privateKey,tx)
}
}
return nil, fmt.Errorf("not matching execution or method!")
}
// TODO 执行请求
func (client *JSONClient) Execute(requst *Request) (*Response, error) {
//err := client.Call(Chain33_QueryTransaction, query, &detail)
//if err != nil {
// return nil, err
//}
//
//return &detail, nil
return nil, nil
}
// 简单实现交易时间监听功能,后面换成grpc长链接方式监听
func (client *JSONClient) RegisterTxEvent(start int64, ccID, eventFilter string) (chan<- event.Registration, <-chan *event.CCEvent, <-chan error) {
ch := make(chan *event.CCEvent)
resCh := make(chan event.Registration)
errCh := make(chan error)
//FIXME 这里实现是以联盟链方式,联盟链没有回滚,所以这里暂时按高度拉去处理
go func(ch chan<- *event.CCEvent, closeCh <-chan event.Registration, errCh chan<- error) {
height := start
HERE:
header, err := client.QueryLastHeader()
if err != nil {
errCh <- err
return
}
lastHeight := header.Height
if lastHeight <= height {
time.Sleep(time.Second)
goto HERE
}
ticket := time.After(100 * time.Millisecond)
for {
select {
case <-ticket:
blockInfo, err := client.QueryBlockInfo(height, height, true)
if err != nil {
errCh <- err
return
}
for _, item := range blockInfo.Items {
for i, tx := range item.Block.Txs {
if tx.Execer == ccID && item.Receipts[i].Ty == types.ExecOk {
//todo 这里需要重新弄成通用处理
if tx.Execer == broker.BrokerX {
var brokerAction types.BrokerAction
err := types.Decode(tx.Payload, &brokerAction)
if err != nil {
errCh <- err
return
}
if brokerAction.Ty == broker.ActionMap[eventFilter] {
ccEvent := &event.CCEvent{Payload: types.Encode(brokerAction.GetEmitInterchainEvent()), CCID: tx.Execer, TxID: tx.Hash, EventName: eventFilter, BlockNumber: uint64(item.Block.Height)}
ch <- ccEvent
}
}
}
}
}
height++
goto HERE
case <-closeCh:
break
}
}
}(ch, resCh, errCh)
return resCh, ch, nil
}
func (client *JSONClient) PollingEvent(meta *types.Meta) (*types.InterChainEventList, error) {
jsonraw, err := json.Marshal(&types.PollingEvent{Meta: meta})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNamePollingEvent,
Payload: jsonraw,
}
var eventList types.InterChainEventList
err = client.Call("Chain33.Query", query, &eventList)
if err != nil {
return nil, err
}
return &eventList, nil
}
func (client *JSONClient) QueryInnerMeta() (*types.Meta, error) {
jsonraw, err := json.Marshal(&types.QueryInnerMeta{})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryInnerMeta,
Payload: jsonraw,
}
var meta types.Meta
err = client.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func (client *JSONClient) QueryOutterMeta() (*types.Meta, error) {
jsonraw, err := json.Marshal(&types.QueryOutterMeta{})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryOutterMeta,
Payload: jsonraw,
}
var meta types.Meta
err = client.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func (client *JSONClient) QueryCallBackMeta() (*types.Meta, error) {
jsonraw, err := json.Marshal(&types.QueryNilParam{})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryCallBackMeta,
Payload: jsonraw,
}
var meta types.Meta
err = client.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func (client *JSONClient) QueryOutMessage(inServicePair string, index uint64) (*types.Response, error) {
jsonraw, err := json.Marshal(&types.QueryOutMessage{InServicePair: inServicePair, SequenceNum: index})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryOutMessage,
Payload: jsonraw,
}
var resp types.Response
err = client.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func (client *JSONClient) QueryInMessage(inServicePair string, index uint64) (*types.Response, error) {
jsonraw, err := json.Marshal(&types.QueryInMessage{InServicePair: inServicePair, SequenceNum: index})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryInMessage,
Payload: jsonraw,
}
var resp types.Response
err = client.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func (client *JSONClient) QueryBrokerInfo() (*types.BrokerInfo, error) {
jsonraw, err := json.Marshal(&types.QueryNilParam{})
if err != nil {
return nil, err
}
query := Query4Jrpc{
Execer: client.prefix + broker.BrokerX,
FuncName: broker.FuncNameQueryBrokerInfo,
Payload: jsonraw,
}
var resp types.BrokerInfo
err = client.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
...@@ -76,7 +76,65 @@ type TxProof struct { ...@@ -76,7 +76,65 @@ type TxProof struct {
RootHash string `json:"rootHash"` RootHash string `json:"rootHash"`
} }
// TransactionDetail transaction detail type TransParm struct {
Execer string `json:"execer"`
Payload string `json:"payload"`
Signature *Signature `json:"signature"`
Fee int64 `json:"fee"`
}
type SignedTx struct {
Unsign string `json:"unsignTx"`
Sign string `json:"sign"`
Pubkey string `json:"pubkey"`
Ty int32 `json:"ty"`
}
type BlockParam struct {
Start int64 `json:"start"`
End int64 `json:"end"`
Isdetail bool `json:"isDetail"`
}
type Header struct {
Version int64 `json:"version"`
ParentHash string `json:"parentHash"`
TxHash string `json:"txHash"`
StateHash string `json:"stateHash"`
Height int64 `json:"height"`
BlockTime int64 `json:"blockTime"`
TxCount int64 `json:"txCount"`
Hash string `json:"hash"`
}
type ReceiptLog struct {
Ty int32 `json:"ty"`
Log string `json:"log"`
}
type ReceiptData struct {
Ty int32 `json:"ty"`
Logs []*ReceiptLog `json:"logs"`
}
type Block struct {
Version int64 `json:"version"`
ParentHash string `json:"parentHash"`
TxHash string `json:"txHash"`
StateHash string `json:"stateHash"`
Height int64 `json:"height"`
BlockTime int64 `json:"blockTime"`
Txs []*Transaction `json:"txs"`
}
type BlockDetail struct {
Block *Block `json:"block"`
Receipts []*ReceiptDataResult `json:"recipts"`
}
type BlockDetails struct {
Items []*BlockDetail `json:"items"`
}
type TransactionDetail struct { type TransactionDetail struct {
Tx *Transaction `json:"tx"` Tx *Transaction `json:"tx"`
Receipt *ReceiptDataResult `json:"receipt"` Receipt *ReceiptDataResult `json:"receipt"`
...@@ -87,14 +145,209 @@ type TransactionDetail struct { ...@@ -87,14 +145,209 @@ type TransactionDetail struct {
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
Fromaddr string `json:"fromAddr"` Fromaddr string `json:"fromAddr"`
ActionName string `json:"actionName"` ActionName string `json:"actionName"`
Assets []*Asset `json:"assets"`
TxProofs []*TxProof `json:"txProofs"`
FullHash string `json:"fullHash"`
} }
// Query4Jrpc query jrpc type ReplyTxInfos struct {
TxInfos []*ReplyTxInfo `protobuf:"bytes,1,rep,name=txInfos" json:"txInfos"`
}
type ReplyTxInfo struct {
Hash string `json:"hash"`
Height int64 `json:"height"`
Index int64 `json:"index"`
}
type TransactionDetails struct {
//Txs []*Transaction `json:"txs"`
Txs []*TransactionDetail `protobuf:"bytes,1,rep,name=txs" json:"txs"`
}
type ReplyTxList struct {
Txs []*Transaction `json:"txs"`
}
type ReplyHash struct {
Hash string `json:"hash"`
}
type ReplyHashes struct {
Hashes []string `json:"hashes"`
}
type PeerList struct {
Peers []*Peer `json:"peers"`
}
type Peer struct {
Addr string `json:"addr"`
Port int32 `json:"port"`
Name string `json:"name"`
MempoolSize int32 `json:"mempoolSize"`
Self bool `json:"self"`
Header *Header `json:"header"`
}
// Wallet Module
type WalletAccounts struct {
Wallets []*WalletAccount `protobuf:"bytes,1,rep,name=wallets" json:"wallets"`
}
type WalletAccount struct {
Acc *Account `protobuf:"bytes,1,opt,name=acc" json:"acc"`
Label string `protobuf:"bytes,2,opt,name=label" json:"label"`
}
type Account struct {
Currency int32 `protobuf:"varint,1,opt,name=currency" json:"currency"`
Balance int64 `protobuf:"varint,2,opt,name=balance" json:"balance"`
Frozen int64 `protobuf:"varint,3,opt,name=frozen" json:"frozen"`
Addr string `protobuf:"bytes,4,opt,name=addr" json:"addr"`
}
type Reply struct {
IsOk bool `protobuf:"varint,1,opt,name=isOk" json:"isOK"`
Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg"`
}
type Headers struct {
Items []*Header `protobuf:"bytes,1,rep,name=items" json:"items"`
}
type ReqAddr struct {
Addr string `json:"addr"`
}
type ReqHashes struct {
Hashes []string `json:"hashes"`
DisableDetail bool `json:"disableDetail"`
}
type ReqWalletTransactionList struct {
FromTx string `json:"fromTx"`
Count int32 `json:"count"`
Direction int32 `json:"direction"`
}
type WalletTxDetails struct {
TxDetails []*WalletTxDetail `protobuf:"bytes,1,rep,name=txDetails" json:"txDetails"`
}
type WalletTxDetail struct {
Tx *Transaction `protobuf:"bytes,1,opt,name=tx" json:"tx"`
Receipt *ReceiptDataResult `protobuf:"bytes,2,opt,name=receipt" json:"receipt"`
Height int64 `protobuf:"varint,3,opt,name=height" json:"height"`
Index int64 `protobuf:"varint,4,opt,name=index" json:"index"`
BlockTime int64 `json:"blockTime"`
Amount int64 `json:"amount"`
FromAddr string `json:"fromAddr"`
TxHash string `json:"txHash"`
ActionName string `json:"actionName"`
}
type BlockOverview struct {
Head *Header `protobuf:"bytes,1,opt,name=head" json:"head"`
TxCount int64 `protobuf:"varint,2,opt,name=txCount" json:"txCount"`
TxHashes []string `protobuf:"bytes,3,rep,name=txHashes,proto3" json:"txHashes"`
}
type Query4Cli struct {
Execer string `protobuf:"bytes,1,opt,name=execer,proto3" json:"execer"`
FuncName string `protobuf:"bytes,2,opt,name=funcName" json:"funcName"`
Payload interface{} `protobuf:"bytes,3,opt,name=payload" json:"payload"`
}
type Query4Jrpc struct { type Query4Jrpc struct {
Execer string `json:"execer"` Execer string `protobuf:"bytes,1,opt,name=execer,proto3" json:"execer"`
FuncName string `json:"funcName"` FuncName string `protobuf:"bytes,2,opt,name=funcName" json:"funcName"`
Payload json.RawMessage `json:"payload"` Payload json.RawMessage `protobuf:"bytes,3,opt,name=payload" json:"payload"`
}
type WalletStatus struct {
IsWalletLock bool `json:"isWalletLock"`
IsAutoMining bool `json:"isAutoMining"`
IsHasSeed bool `json:"isHasSeed"`
IsTicketLock bool `json:"isTicketLock"`
}
// Token Transaction
type TokenPreCreateTx struct {
Price int64 `json:"price"`
Name string `json:"name"`
Symbol string `json:"symbol"`
Introduction string `json:"introduction"`
OwnerAddr string `json:"ownerAddr"`
Total int64 `json:"total"`
Fee int64 `json:"fee"`
}
type TokenFinishTx struct {
OwnerAddr string `json:"ownerAddr"`
Symbol string `json:"symbol"`
Fee int64 `json:"fee"`
}
type TokenRevokeTx struct {
OwnerAddr string `json:"ownerAddr"`
Symbol string `json:"symbol"`
Fee int64 `json:"fee"`
}
// Trade Transaction
type TradeSellTx struct {
TokenSymbol string `json:"tokenSymbol"`
AmountPerBoardlot int64 `json:"amountPerBoardlot"`
MinBoardlot int64 `json:"minBoardlot"`
PricePerBoardlot int64 `json:"pricePerBoardlot"`
TotalBoardlot int64 `json:"totalBoardlot"`
Fee int64 `json:"fee"`
}
type TradeBuyTx struct {
SellID string `json:"sellID"`
BoardlotCnt int64 `json:"boardlotCnt"`
Fee int64 `json:"fee"`
}
type TradeRevokeTx struct {
SellID string `json:"sellID,"`
Fee int64 `json:"fee"`
}
type TradeBuyLimitTx struct {
TokenSymbol string `json:"tokenSymbol"`
AmountPerBoardlot int64 `json:"amountPerBoardlot"`
MinBoardlot int64 `json:"minBoardlot"`
PricePerBoardlot int64 `json:"pricePerBoardlot"`
TotalBoardlot int64 `json:"totalBoardlot"`
Fee int64 `json:"fee"`
}
type TradeSellMarketTx struct {
BuyID string `json:"buyID"`
BoardlotCnt int64 `json:"boardlotCnt"`
Fee int64 `json:"fee"`
}
type TradeRevokeBuyTx struct {
BuyID string `json:"buyID,"`
Fee int64 `json:"fee"`
}
type NodeNetinfo struct {
Externaladdr string `json:"externalAddr"`
Localaddr string `json:"localAddr"`
Service bool `json:"service"`
Outbounds int32 `json:"outbounds"`
Inbounds int32 `json:"inbounds"`
}
//// BlockParam block parameter
//type BlockParam struct {
// Start int64 `json:"start"`
// End int64 `json:"end"`
// Isdetail bool `json:"isDetail"`
//}
type Request struct {
Exec string `json:"exec"`
Fcn string `json:"fcn"`
Args [][]byte `json:"args"`
} }
type Response struct {
OK bool `json:"ok"`
Message string `json:"message"`
Data []byte `json:"data"`
}
\ No newline at end of file
...@@ -2,22 +2,38 @@ package broker ...@@ -2,22 +2,38 @@ package broker
const ( const (
TyUnknowAction = iota + 100 TyUnknowAction = iota + 100
TyInitAction
TyRegisterAction TyRegisterAction
TyAuditAction TyAuditAction
TyUpdateIndexAction TyUpdateIndexAction
TyEmitInterchainEventAction TyEmitInterchainEventAction
//NameRegisterAction = "Register" NameInitAction = "Init"
//NameAuditAction = "Audit" NameRegisterAction = "Register"
//NameUpdateIndexAction = "UpdateIndex" NameAuditAction = "Audit"
//NameEmitInterchainEventAction = "EmitInterchainEvent" NameUpdateIndexAction = "UpdateIndex"
NameEmitInterchainEventAction = "EmitInterchainEvent"
FuncNamePollingEvent = "PollingEvent" FuncNamePollingEvent = "PollingEvent"
FuncNameQueryInnerMeta = "QueryInnerMeta" FuncNameQueryInnerMeta = "QueryInnerMeta"
FuncNameQueryOutterMeta = "QueryOutterMeta" FuncNameQueryOutterMeta = "QueryOutterMeta"
FuncNameQueryCallBackMeta = "QueryCallBackMeta"
FuncNameQueryInMessage = "QueryInMessage" FuncNameQueryInMessage = "QueryInMessage"
FuncNameQueryOutMessage = "QueryOutMessage" FuncNameQueryOutMessage = "QueryOutMessage"
FuncNameQueryBrokerInfo = "GetBrokerInfo"
) )
//BrokerX 执行器名称定义
const BrokerX = "broker" const BrokerX = "broker"
const Addr = "1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs" const Addr = "1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs"
var (
//定义actionMap
ActionMap = map[string]int32{
NameInitAction: TyInitAction,
NameRegisterAction: TyRegisterAction,
NameAuditAction: TyAuditAction,
NameUpdateIndexAction: TyUpdateIndexAction,
NameEmitInterchainEventAction: TyEmitInterchainEventAction,
}
)
package broker
import (
"encoding/json"
"github.com/33cn/chain33-sdk-go/client"
"github.com/33cn/chain33-sdk-go/types"
)
func PollingEvent(prefix, url string,meta *types.Meta) (*types.InterChainEventList, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.PollingEvent{Meta:meta})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNamePollingEvent,
Payload: jsonraw,
}
var eventList types.InterChainEventList
err = jsonClient.Call("Chain33.Query", query, &eventList)
if err != nil {
return nil, err
}
return &eventList, nil
}
func QueryInnerMeta(prefix, url string) (*types.Meta, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryInnerMeta{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryInnerMeta,
Payload: jsonraw,
}
var meta types.Meta
err = jsonClient.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func QueryOutterMeta(prefix, url string) (*types.Meta, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryOutterMeta{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryInnerMeta,
Payload: jsonraw,
}
var meta types.Meta
err = jsonClient.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func QueryOutMessage(prefix, url,inServicePair string,index uint64) (*types.Response, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryOutMessage{InServicePair:inServicePair,SequenceNum:index})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryOutMessage,
Payload: jsonraw,
}
var resp types.Response
err = jsonClient.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func QueryInMessage(prefix, url,inServicePair string,index uint64) (*types.Response, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryInMessage{InServicePair:inServicePair,SequenceNum:index})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryInMessage,
Payload: jsonraw,
}
var resp types.Response
err = jsonClient.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
\ No newline at end of file
package storage package dapp
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
. "github.com/bitly/go-simplejson"
"github.com/33cn/chain33-sdk-go/client" "github.com/33cn/chain33-sdk-go/client"
. "github.com/33cn/chain33-sdk-go/dapp/broker"
"github.com/33cn/chain33-sdk-go/dapp/storage"
"github.com/33cn/chain33-sdk-go/types" "github.com/33cn/chain33-sdk-go/types"
. "github.com/bitly/go-simplejson"
) )
func QueryStorageByKey(prefix, url, key string) (*types.Storage, error) { func QueryStorageByKey(prefix, url, key string) (*types.Storage, error) {
...@@ -18,8 +21,8 @@ func QueryStorageByKey(prefix, url, key string) (*types.Storage, error) { ...@@ -18,8 +21,8 @@ func QueryStorageByKey(prefix, url, key string) (*types.Storage, error) {
return nil, err return nil, err
} }
query := client.Query4Jrpc{ query := client.Query4Jrpc{
Execer: prefix + StorageX, Execer: prefix + storage.StorageX,
FuncName: FuncNameQueryStorage, FuncName: storage.FuncNameQueryStorage,
Payload: jsonraw, Payload: jsonraw,
} }
//var storage types.Storage //var storage types.Storage
...@@ -42,7 +45,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -42,7 +45,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
key, _ := contentStorge.Get("key").String() key, _ := contentStorge.Get("key").String()
value, _ := contentStorge.Get("value").String() value, _ := contentStorge.Get("value").String()
op, _ := contentStorge.Get("op").Int() op, _ := contentStorge.Get("op").Int()
storage := &types.Storage{Ty: TyContentStorageAction, Value: &types.Storage_ContentStorage{ContentStorage: &types.ContentOnlyNotaryStorage{ storage := &types.Storage{Ty: storage.TyContentStorageAction, Value: &types.Storage_ContentStorage{ContentStorage: &types.ContentOnlyNotaryStorage{
Content: content, Content: content,
Key: key, Key: key,
Op: int32(op), Op: int32(op),
...@@ -58,7 +61,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -58,7 +61,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
link, _ := types.FromHex(linkHex) link, _ := types.FromHex(linkHex)
key, _ := linkStorge.Get("key").String() key, _ := linkStorge.Get("key").String()
value, _ := linkStorge.Get("value").String() value, _ := linkStorge.Get("value").String()
storage := &types.Storage{Ty: TyLinkStorageAction, Value: &types.Storage_LinkStorage{LinkStorage: &types.LinkNotaryStorage{ storage := &types.Storage{Ty: storage.TyLinkStorageAction, Value: &types.Storage_LinkStorage{LinkStorage: &types.LinkNotaryStorage{
Link: link, Link: link,
Key: key, Key: key,
Value: value, Value: value,
...@@ -73,7 +76,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -73,7 +76,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
hash, _ := types.FromHex(hashHex) hash, _ := types.FromHex(hashHex)
key, _ := hashStorge.Get("key").String() key, _ := hashStorge.Get("key").String()
value, _ := hashStorge.Get("value").String() value, _ := hashStorge.Get("value").String()
storage := &types.Storage{Ty: TyHashStorageAction, Value: &types.Storage_HashStorage{HashStorage: &types.HashOnlyNotaryStorage{ storage := &types.Storage{Ty: storage.TyHashStorageAction, Value: &types.Storage_HashStorage{HashStorage: &types.HashOnlyNotaryStorage{
Hash: hash, Hash: hash,
Key: key, Key: key,
Value: value, Value: value,
...@@ -93,7 +96,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -93,7 +96,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
nonce, _ := types.FromHex(nonceHex) nonce, _ := types.FromHex(nonceHex)
key, _ := encryptStorage.Get("key").String() key, _ := encryptStorage.Get("key").String()
value, _ := encryptStorage.Get("value").String() value, _ := encryptStorage.Get("value").String()
storage := &types.Storage{Ty: TyEncryptStorageAction, Value: &types.Storage_EncryptStorage{EncryptStorage: &types.EncryptNotaryStorage{ storage := &types.Storage{Ty: storage.TyEncryptStorageAction, Value: &types.Storage_EncryptStorage{EncryptStorage: &types.EncryptNotaryStorage{
EncryptContent: encryptContent, EncryptContent: encryptContent,
ContentHash: contentHash, ContentHash: contentHash,
Nonce: nonce, Nonce: nonce,
...@@ -114,7 +117,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -114,7 +117,7 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
pubKey, _ := types.FromHex(pubKeyHex) pubKey, _ := types.FromHex(pubKeyHex)
key, _ := encryptStorage.Get("key").String() key, _ := encryptStorage.Get("key").String()
value, _ := encryptStorage.Get("value").String() value, _ := encryptStorage.Get("value").String()
storage := &types.Storage{Ty: TyEncryptShareStorageAction, Value: &types.Storage_EncryptShareStorage{EncryptShareStorage: &types.EncryptShareNotaryStorage{ storage := &types.Storage{Ty: storage.TyEncryptShareStorageAction, Value: &types.Storage_EncryptShareStorage{EncryptShareStorage: &types.EncryptShareNotaryStorage{
EncryptContent: encryptContent, EncryptContent: encryptContent,
ContentHash: contentHash, ContentHash: contentHash,
PubKey: pubKey, PubKey: pubKey,
...@@ -128,3 +131,157 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -128,3 +131,157 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
} }
return nil, fmt.Errorf("unknow type!") return nil, fmt.Errorf("unknow type!")
} }
func PollingEvent(prefix, url string, meta *types.Meta) (*types.InterChainEventList, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.PollingEvent{Meta: meta})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNamePollingEvent,
Payload: jsonraw,
}
var eventList types.InterChainEventList
err = jsonClient.Call("Chain33.Query", query, &eventList)
if err != nil {
return nil, err
}
return &eventList, nil
}
func QueryInnerMeta(prefix, url string) (*types.Meta, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryInnerMeta{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryInnerMeta,
Payload: jsonraw,
}
var meta types.Meta
err = jsonClient.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func QueryOutterMeta(prefix, url string) (*types.Meta, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryOutterMeta{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryOutterMeta,
Payload: jsonraw,
}
var meta types.Meta
err = jsonClient.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func QueryCallBackMeta(prefix, url string) (*types.Meta, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryNilParam{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryCallBackMeta,
Payload: jsonraw,
}
var meta types.Meta
err = jsonClient.Call("Chain33.Query", query, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func QueryOutMessage(prefix, url, inServicePair string, index uint64) (*types.Response, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryOutMessage{InServicePair: inServicePair, SequenceNum: index})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryOutMessage,
Payload: jsonraw,
}
var resp types.Response
err = jsonClient.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func QueryInMessage(prefix, url, inServicePair string, index uint64) (*types.Response, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryInMessage{InServicePair: inServicePair, SequenceNum: index})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryInMessage,
Payload: jsonraw,
}
var resp types.Response
err = jsonClient.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
func QueryBrokerInfo(prefix, url string) (*types.BrokerInfo, error) {
jsonClient, err := client.NewJSONClient(prefix, url)
if err != nil {
return nil, err
}
jsonraw, err := json.Marshal(&types.QueryNilParam{})
if err != nil {
return nil, err
}
query := client.Query4Jrpc{
Execer: prefix + BrokerX,
FuncName: FuncNameQueryBrokerInfo,
Payload: jsonraw,
}
var resp types.BrokerInfo
err = jsonClient.Call("Chain33.Query", query, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
...@@ -5,7 +5,9 @@ import ( ...@@ -5,7 +5,9 @@ import (
"github.com/33cn/chain33-sdk-go/client" "github.com/33cn/chain33-sdk-go/client"
"github.com/33cn/chain33-sdk-go/crypto" "github.com/33cn/chain33-sdk-go/crypto"
"github.com/33cn/chain33-sdk-go/types" "github.com/33cn/chain33-sdk-go/types"
. "github.com/33cn/chain33-sdk-go/dapp"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"testing" "testing"
"time" "time"
) )
......
package event
type CCEvent struct {
//交易哈希
TxID string
//执行器名称,也可能是合约地址
CCID string
//事件名称,go中表示actionName
EventName string
//信息载体
Payload []byte
//交易所在区块高度
BlockNumber uint64
}
type Registration interface{}
type EventService interface {
//注册区块监听
//RegisterBlockEvent(filter ...BlockFilter) (chan <-Registration, <-chan *BlockEvent, error)
//注册交易时间监听
RegisterTxEvent(ccID, eventFilter string) (chan <-Registration,<-chan *CCEvent, error)
}
\ No newline at end of file
...@@ -108,6 +108,9 @@ message QueryOutterMeta{ ...@@ -108,6 +108,9 @@ message QueryOutterMeta{
message QueryInnerMeta{ message QueryInnerMeta{
} }
message QueryNilParam{
}
message QueryInMessage{ message QueryInMessage{
string inServicePair = 1; string inServicePair = 1;
...@@ -123,7 +126,12 @@ message Meta { ...@@ -123,7 +126,12 @@ message Meta {
map<string,uint64> meta = 1; map<string,uint64> meta = 1;
} }
message BrokerInfo {
//跨链协议版本ID
string bxhId =1;
//应用链ID
string appChainId = 2;
}
message Response{ message Response{
// A status code that should follow the HTTP status codes. // A status code that should follow the HTTP status codes.
int32 status = 1; int32 status = 1;
......
syntax = "proto3";
package types;
//option go_package = "github.com/33cn/chain33/types";
message Reply {
bool isOk = 1;
bytes msg = 2;
}
message ReqString {
string data = 1;
}
message ReplyString {
string data = 1;
}
message ReplyStrings {
repeated string datas = 1;
}
message ReqInt {
int64 height = 1;
}
message Int64 {
int64 data = 1;
}
message ReqHash {
bytes hash = 1;
bool upgrade = 2;
}
message ReplyHash {
bytes hash = 1;
}
message ReqNil {}
message ReqHashes {
repeated bytes hashes = 1;
}
message ReplyHashes {
repeated bytes hashes = 1;
}
message KeyValue {
bytes key = 1;
bytes value = 2;
}
message TxHash {
string hash = 1;
}
message TimeStatus {
string ntpTime = 1;
string localTime = 2;
int64 diff = 3;
}
message ReqKey {
bytes key = 1;
}
message ReqRandHash {
string execName = 1;
int64 height = 2;
int64 blockNum = 3;
bytes hash = 4;
}
/**
*当前软件版本信息
*/
message VersionInfo {
string title = 1;
string app = 2;
string chain33 = 3;
string localDb = 4;
int32 chainID = 5;
}
This diff is collapsed.
This diff is collapsed.
package util
func ToChaincodeArgs(args ...string) [][]byte {
bargs := make([][]byte, len(args))
for i, arg := range args {
bargs[i] = []byte(arg)
}
return bargs
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment