Commit f6103da0 authored by vipwzw's avatar vipwzw Committed by 33cn

update

parent 9eac9d7d
...@@ -68,24 +68,37 @@ type client struct { ...@@ -68,24 +68,37 @@ type client struct {
wg sync.WaitGroup wg sync.WaitGroup
} }
type subConfig struct {
WriteBlockSeconds int64 `json:"writeBlockSeconds,omitempty"`
ParaRemoteGrpcClient string `json:"paraRemoteGrpcClient,omitempty"`
StartHeight int64 `json:"startHeight,omitempty"`
EmptyBlockInterval int64 `json:"emptyBlockInterval,omitempty"`
AuthAccount string `json:"authAccount,omitempty"`
WaitBlocks4CommitMsg int32 `json:"waitBlocks4CommitMsg,omitempty"`
SearchHashMatchedBlockDepth int32 `json:"searchHashMatchedBlockDepth,omitempty"`
}
// New function to init paracross env // New function to init paracross env
func New(cfg *types.Consensus, sub []byte) queue.Module { func New(cfg *types.Consensus, sub []byte) queue.Module {
c := drivers.NewBaseClient(cfg) c := drivers.NewBaseClient(cfg)
if cfg.ParaRemoteGrpcClient != "" { var subcfg subConfig
grpcSite = cfg.ParaRemoteGrpcClient if sub != nil {
types.MustDecode(sub, &subcfg)
} }
if cfg.StartHeight > 0 { if subcfg.ParaRemoteGrpcClient != "" {
startHeight = cfg.StartHeight grpcSite = subcfg.ParaRemoteGrpcClient
} }
if cfg.WriteBlockSeconds > 0 { if subcfg.StartHeight > 0 {
blockSec = cfg.WriteBlockSeconds startHeight = subcfg.StartHeight
} }
if cfg.EmptyBlockInterval > 0 { if subcfg.WriteBlockSeconds > 0 {
emptyBlockInterval = cfg.EmptyBlockInterval blockSec = subcfg.WriteBlockSeconds
} }
if subcfg.EmptyBlockInterval > 0 {
if cfg.SearchHashMatchedBlockDepth > 0 { emptyBlockInterval = subcfg.EmptyBlockInterval
searchHashMatchDepth = cfg.SearchHashMatchedBlockDepth }
if subcfg.SearchHashMatchedBlockDepth > 0 {
searchHashMatchDepth = subcfg.SearchHashMatchedBlockDepth
} }
pk, err := hex.DecodeString(minerPrivateKey) pk, err := hex.DecodeString(minerPrivateKey)
...@@ -121,21 +134,18 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { ...@@ -121,21 +134,18 @@ func New(cfg *types.Consensus, sub []byte) queue.Module {
privateKey: priKey, privateKey: priKey,
isCaughtUp: false, isCaughtUp: false,
} }
if subcfg.WaitBlocks4CommitMsg < 2 {
if cfg.WaitBlocks4CommitMsg < 2 {
panic("config WaitBlocks4CommitMsg should not less 2") panic("config WaitBlocks4CommitMsg should not less 2")
} }
para.commitMsgClient = &commitMsgClient{ para.commitMsgClient = &commitMsgClient{
paraClient: para, paraClient: para,
waitMainBlocks: cfg.WaitBlocks4CommitMsg, waitMainBlocks: subcfg.WaitBlocks4CommitMsg,
commitMsgNotify: make(chan int64, 1), commitMsgNotify: make(chan int64, 1),
delMsgNotify: make(chan int64, 1), delMsgNotify: make(chan int64, 1),
mainBlockAdd: make(chan *types.BlockDetail, 1), mainBlockAdd: make(chan *types.BlockDetail, 1),
quit: make(chan struct{}), quit: make(chan struct{}),
} }
c.SetChild(para) c.SetChild(para)
return para return para
} }
...@@ -178,6 +188,7 @@ func (client *client) InitBlock() { ...@@ -178,6 +188,7 @@ func (client *client) InitBlock() {
newblock.Height = 0 newblock.Height = 0
newblock.BlockTime = genesisBlockTime newblock.BlockTime = genesisBlockTime
newblock.ParentHash = zeroHash[:] newblock.ParentHash = zeroHash[:]
newblock.MainHash = zeroHash[:]
tx := client.CreateGenesisTx() tx := client.CreateGenesisTx()
newblock.Txs = tx newblock.Txs = tx
newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs) newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs)
...@@ -661,16 +672,13 @@ func (client *client) addMinerTx(preStateHash []byte, block *types.Block, main * ...@@ -661,16 +672,13 @@ func (client *client) addMinerTx(preStateHash []byte, block *types.Block, main *
MainBlockHash: main.Seq.Hash, MainBlockHash: main.Seq.Hash,
MainBlockHeight: main.Detail.Block.Height, MainBlockHeight: main.Detail.Block.Height,
} }
tx, err := paracross.CreateRawMinerTx(status) tx, err := paracross.CreateRawMinerTx(status)
if err != nil { if err != nil {
return err return err
} }
tx.Sign(types.SECP256K1, client.privateKey) tx.Sign(types.SECP256K1, client.privateKey)
block.Txs = append([]*types.Transaction{tx}, block.Txs...) block.Txs = append([]*types.Transaction{tx}, block.Txs...)
return nil return nil
} }
func (client *client) createBlock(lastBlock *types.Block, txs []*types.Transaction, seq int64, mainBlock *types.BlockSeq) error { func (client *client) createBlock(lastBlock *types.Block, txs []*types.Transaction, seq int64, mainBlock *types.BlockSeq) error {
...@@ -682,8 +690,8 @@ func (client *client) createBlock(lastBlock *types.Block, txs []*types.Transacti ...@@ -682,8 +690,8 @@ func (client *client) createBlock(lastBlock *types.Block, txs []*types.Transacti
//挖矿固定难度 //挖矿固定难度
newblock.Difficulty = types.GetP(0).PowLimitBits newblock.Difficulty = types.GetP(0).PowLimitBits
newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs) newblock.TxHash = merkle.CalcMerkleRoot(newblock.Txs)
newblock.BlockTime = mainBlock.Detail.Block.BlockTime newblock.BlockTime = mainBlock.BlockTime
newblock.MainHash = mainBlock.Hash()
err := client.addMinerTx(lastBlock.StateHash, &newblock, mainBlock) err := client.addMinerTx(lastBlock.StateHash, &newblock, mainBlock)
if err != nil { if err != nil {
return err return err
......
...@@ -46,7 +46,6 @@ func NewRaftCluster(cfg *types.Consensus, sub []byte) queue.Module { ...@@ -46,7 +46,6 @@ func NewRaftCluster(cfg *types.Consensus, sub []byte) queue.Module {
if sub != nil { if sub != nil {
types.MustDecode(sub, &subcfg) types.MustDecode(sub, &subcfg)
} }
if subcfg.Genesis != "" { if subcfg.Genesis != "" {
genesis = subcfg.Genesis genesis = subcfg.Genesis
} }
......
...@@ -43,7 +43,10 @@ func execBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er ...@@ -43,7 +43,10 @@ func execBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er
block.TxHash = merkle.CalcMerkleRootCache(cacheTxs) block.TxHash = merkle.CalcMerkleRootCache(cacheTxs)
block.Txs = types.CacheToTxs(cacheTxs) block.Txs = types.CacheToTxs(cacheTxs)
//println("1") //println("1")
receipts := util.ExecTx(client, prevStateRoot, block) receipts, err := util.ExecTx(client, prevStateRoot, block)
if err != nil {
return nil, nil, err
}
var maplist = make(map[string]*types.KeyValue) var maplist = make(map[string]*types.KeyValue)
var kvset []*types.KeyValue var kvset []*types.KeyValue
var deltxlist = make(map[int]bool) var deltxlist = make(map[int]bool)
...@@ -94,7 +97,10 @@ func execBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er ...@@ -94,7 +97,10 @@ func execBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er
var detail types.BlockDetail var detail types.BlockDetail
calcHash = util.ExecKVMemSet(client, prevStateRoot, block.Height, kvset, sync) calcHash, err = util.ExecKVMemSet(client, prevStateRoot, block.Height, kvset, sync)
if err != nil {
return nil, nil, err
}
//println("2") //println("2")
if errReturn && !bytes.Equal(block.StateHash, calcHash) { if errReturn && !bytes.Equal(block.StateHash, calcHash) {
util.ExecKVSetRollback(client, calcHash) util.ExecKVSetRollback(client, calcHash)
......
#!/usr/bin/env bash
withdraw=$(../chain33-cli bty withdraw -e "ticket" -n "安全支出费用: $1" -a "$1")
send=$(../chain33-cli bty transfer -a "$1" -n "安全支出费用: $1" -t 1MY4pMgjpS2vWiaSDZasRhN47pcwEire32)
echo "cli wallet sign -d $withdraw -a 1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP >d:/a.txt"
echo "cli wallet sign -d $send -a 1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP >>d:/a.txt"
//这个包提供了平行链和主链的统一的访问接口
package api
import (
"context"
"errors"
"sync/atomic"
"github.com/33cn/chain33/client"
"github.com/33cn/chain33/queue"
"github.com/33cn/chain33/types"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
/*
平行链可以访问的有两条链:
1. 通过 client.QueueProtocolAPI 事件访问 平行链本身
2. 通过 grpc 接口访问主链
通过 client.QueueProtocolAPI 和 grpc 都可能会产生 网络错误,或者超时的问题
这个时候,区块做异常处理的时候需要做一些特殊处理
接口函数:
1. GetBlockByHash
2. GetLastBlockHash
3. GetRandNum
*/
//ErrAPIEnv api的执行环境出问题,区块执行的时候,遇到这一个的错误需要retry
var ErrAPIEnv = errors.New("ErrAPIEnv")
//ExecutorAPI 提供给执行器使用的接口
//因为合约是主链和平行链通用的,所以,主链和平行链都可以调用这套接口
type ExecutorAPI interface {
GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error)
GetRandNum(param *types.ReqRandHash) ([]byte, error)
IsErr() bool
}
type mainChainAPI struct {
api client.QueueProtocolAPI
errflag int32
}
//New 新建接口
func New(api client.QueueProtocolAPI, grpcaddr string) ExecutorAPI {
if types.IsPara() {
return newParaChainAPI(api, grpcaddr)
}
return &mainChainAPI{api: api}
}
func (api *mainChainAPI) IsErr() bool {
return atomic.LoadInt32(&api.errflag) == 1
}
func (api *mainChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
msg, err := api.api.Query(param.ExecName, "RandNumHash", param)
if err != nil {
return nil, seterr(err, &api.errflag)
}
reply, ok := msg.(*types.ReplyHash)
if !ok {
return nil, types.ErrTypeAsset
}
return reply.Hash, nil
}
func (api *mainChainAPI) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) {
data, err := api.api.GetBlockByHashes(param)
return data, seterr(err, &api.errflag)
}
type paraChainAPI struct {
api client.QueueProtocolAPI
grpcClient types.Chain33Client
errflag int32
}
func newParaChainAPI(api client.QueueProtocolAPI, grpcaddr string) ExecutorAPI {
paraRemoteGrpcClient := types.Conf("config.consensus").GStr("ParaRemoteGrpcClient")
if grpcaddr != "" {
paraRemoteGrpcClient = grpcaddr
}
if paraRemoteGrpcClient == "" {
paraRemoteGrpcClient = "127.0.0.1:8002"
}
conn, err := grpc.Dial(paraRemoteGrpcClient, grpc.WithInsecure())
if err != nil {
panic(err)
}
grpcClient := types.NewChain33Client(conn)
return &paraChainAPI{api: api, grpcClient: grpcClient}
}
func (api *paraChainAPI) IsErr() bool {
return atomic.LoadInt32(&api.errflag) == 1
}
func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
reply, err := api.grpcClient.QueryRandNum(context.Background(), param)
if err != nil {
return nil, seterr(err, &api.errflag)
}
return reply.Hash, nil
}
func (api *paraChainAPI) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) {
data, err := api.grpcClient.GetBlockByHashes(context.Background(), param)
return data, seterr(err, &api.errflag)
}
func seterr(err error, flag *int32) error {
if IsGrpcError(err) || IsQueueError(err) {
atomic.StoreInt32(flag, 1)
}
return err
}
//IsGrpcError 判断系统api 错误,还是 rpc 本身的错误
func IsGrpcError(err error) bool {
if err == nil {
return false
}
if err == ErrAPIEnv {
return true
}
if grpc.Code(err) == codes.Unknown {
return false
}
return true
}
//IsQueueError 是否是队列错误
func IsQueueError(err error) bool {
if err == nil {
return false
}
if err == ErrAPIEnv {
return true
}
if err == queue.ErrQueueTimeout ||
err == queue.ErrQueueChannelFull ||
err == queue.ErrIsQueueClosed {
return true
}
return false
}
package api
import (
"errors"
"testing"
"time"
"github.com/33cn/chain33/client/mocks"
"github.com/33cn/chain33/queue"
qmocks "github.com/33cn/chain33/queue/mocks"
"github.com/33cn/chain33/rpc"
"github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestAPI(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
eapi := New(api, "")
param := &types.ReqHashes{
Hashes: [][]byte{[]byte("hello")},
}
api.On("GetBlockByHashes", mock.Anything).Return(&types.BlockDetails{}, nil)
detail, err := eapi.GetBlockByHashes(param)
assert.Nil(t, err)
assert.Equal(t, detail, &types.BlockDetails{})
param2 := &types.ReqRandHash{
ExecName: "ticket",
BlockNum: 5,
Hash: []byte("hello"),
}
api.On("Query", "ticket", "RandNumHash", mock.Anything).Return(&types.ReplyHash{Hash: []byte("hello")}, nil)
randhash, err := eapi.GetRandNum(param2)
assert.Nil(t, err)
assert.Equal(t, randhash, []byte("hello"))
assert.Equal(t, false, eapi.IsErr())
types.SetTitleOnlyForTest("user.p.wzw.")
//testnode setup
rpcCfg := new(types.RPC)
rpcCfg.GrpcBindAddr = "127.0.0.1:8003"
rpcCfg.JrpcBindAddr = "127.0.0.1:8004"
rpcCfg.MainnetJrpcAddr = rpcCfg.JrpcBindAddr
rpcCfg.Whitelist = []string{"127.0.0.1", "0.0.0.0"}
rpcCfg.JrpcFuncWhitelist = []string{"*"}
rpcCfg.GrpcFuncWhitelist = []string{"*"}
rpc.InitCfg(rpcCfg)
server := rpc.NewGRpcServer(&qmocks.Client{}, api)
assert.NotNil(t, server)
go server.Listen()
time.Sleep(time.Second)
eapi = New(api, "")
_, err = eapi.GetBlockByHashes(param)
assert.Equal(t, true, IsGrpcError(err))
assert.Equal(t, false, IsGrpcError(nil))
assert.Equal(t, false, IsGrpcError(errors.New("xxxx")))
assert.Equal(t, true, eapi.IsErr())
eapi = New(api, "127.0.0.1:8003")
detail, err = eapi.GetBlockByHashes(param)
assert.Equal(t, err, nil)
assert.Equal(t, detail, &types.BlockDetails{})
randhash, err = eapi.GetRandNum(param2)
assert.Nil(t, err)
assert.Equal(t, randhash, []byte("hello"))
assert.Equal(t, false, eapi.IsErr())
//queue err
assert.Equal(t, false, IsQueueError(nil))
assert.Equal(t, false, IsQueueError(errors.New("xxxx")))
assert.Equal(t, true, IsQueueError(queue.ErrQueueTimeout))
assert.Equal(t, true, IsQueueError(queue.ErrIsQueueClosed))
assert.Equal(t, false, IsQueueError(errors.New("ErrIsQueueClosed")))
}
...@@ -78,7 +78,10 @@ func main() { ...@@ -78,7 +78,10 @@ func main() {
log.Info("execblock", "block height", *height) log.Info("execblock", "block height", *height)
prevState := blocks.Items[0].Block.StateHash prevState := blocks.Items[0].Block.StateHash
block := blocks.Items[1].Block block := blocks.Items[1].Block
receipt := util.ExecTx(q.Client(), prevState, block) receipt, err := util.ExecTx(q.Client(), prevState, block)
if err != nil {
panic(err)
}
for i, r := range receipt.GetReceipts() { for i, r := range receipt.GetReceipts() {
println("=======================") println("=======================")
println("tx index ", i) println("tx index ", i)
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/client" "github.com/33cn/chain33/client"
"github.com/33cn/chain33/client/api"
"github.com/33cn/chain33/common/address" "github.com/33cn/chain33/common/address"
dbm "github.com/33cn/chain33/common/db" dbm "github.com/33cn/chain33/common/db"
drivers "github.com/33cn/chain33/system/dapp" drivers "github.com/33cn/chain33/system/dapp"
...@@ -21,29 +22,39 @@ type executor struct { ...@@ -21,29 +22,39 @@ type executor struct {
stateDB dbm.KV stateDB dbm.KV
localDB dbm.KVDB localDB dbm.KVDB
coinsAccount *account.DB coinsAccount *account.DB
ctx *executorCtx
height int64 height int64
blocktime int64 blocktime int64
// 增加区块的难度值,后面的执行器逻辑需要这些属性 // 增加区块的难度值,后面的执行器逻辑需要这些属性
difficulty uint64 difficulty uint64
txs []*types.Transaction txs []*types.Transaction
api client.QueueProtocolAPI api client.QueueProtocolAPI
execapi api.ExecutorAPI
receipts []*types.ReceiptData receipts []*types.ReceiptData
} }
func newExecutor(stateHash []byte, exec *Executor, height, blocktime int64, difficulty uint64, type executorCtx struct {
txs []*types.Transaction, receipts []*types.ReceiptData) *executor { stateHash []byte
height int64
blocktime int64
difficulty uint64
parentHash []byte
mainHash []byte
}
func newExecutor(ctx *executorCtx, exec *Executor, txs []*types.Transaction, receipts []*types.ReceiptData) *executor {
client := exec.client client := exec.client
enableMVCC := exec.pluginEnable["mvcc"] enableMVCC := exec.pluginEnable["mvcc"]
opt := &StateDBOption{EnableMVCC: enableMVCC, Height: height} opt := &StateDBOption{EnableMVCC: enableMVCC, Height: ctx.height}
localdb := NewLocalDB(client) localdb := NewLocalDB(client)
e := &executor{ e := &executor{
stateDB: NewStateDB(client, stateHash, localdb, opt), stateDB: NewStateDB(client, ctx.stateHash, localdb, opt),
localDB: localdb, localDB: localdb,
coinsAccount: account.NewCoinsAccount(), coinsAccount: account.NewCoinsAccount(),
height: height, height: ctx.height,
blocktime: blocktime, blocktime: ctx.blocktime,
difficulty: difficulty, difficulty: ctx.difficulty,
ctx: ctx,
txs: txs, txs: txs,
receipts: receipts, receipts: receipts,
} }
...@@ -135,8 +146,9 @@ func (e *executor) checkTx(tx *types.Transaction, index int) error { ...@@ -135,8 +146,9 @@ func (e *executor) checkTx(tx *types.Transaction, index int) error {
func (e *executor) setEnv(exec drivers.Driver) { func (e *executor) setEnv(exec drivers.Driver) {
exec.SetStateDB(e.stateDB) exec.SetStateDB(e.stateDB)
exec.SetLocalDB(e.localDB) exec.SetLocalDB(e.localDB)
exec.SetEnv(e.height, e.blocktime, e.difficulty) exec.SetEnv(e.height, e.blocktime, e.difficulty, e.ctx.parentHash, e.ctx.mainHash)
exec.SetAPI(e.api) exec.SetAPI(e.api)
e.execapi = exec.GetExecutorAPI()
exec.SetTxs(e.txs) exec.SetTxs(e.txs)
exec.SetReceipt(e.receipts) exec.SetReceipt(e.receipts)
} }
......
...@@ -11,6 +11,7 @@ import ( ...@@ -11,6 +11,7 @@ import (
"sync" "sync"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/client/api"
clog "github.com/33cn/chain33/common/log" clog "github.com/33cn/chain33/common/log"
log "github.com/33cn/chain33/common/log/log15" log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/pluginmgr" "github.com/33cn/chain33/pluginmgr"
...@@ -156,7 +157,15 @@ func (exec *Executor) procExecQuery(msg queue.Message) { ...@@ -156,7 +157,15 @@ func (exec *Executor) procExecQuery(msg queue.Message) {
func (exec *Executor) procExecCheckTx(msg queue.Message) { func (exec *Executor) procExecCheckTx(msg queue.Message) {
datas := msg.GetData().(*types.ExecTxList) datas := msg.GetData().(*types.ExecTxList)
execute := newExecutor(datas.StateHash, exec, datas.Height, datas.BlockTime, datas.Difficulty, datas.Txs, nil) ctx := &executorCtx{
stateHash: datas.StateHash,
height: datas.Height,
blocktime: datas.BlockTime,
difficulty: datas.Difficulty,
mainHash: datas.MainHash,
parentHash: datas.ParentHash,
}
execute := newExecutor(ctx, exec, datas.Txs, nil)
execute.enableMVCC() execute.enableMVCC()
execute.api = exec.qclient execute.api = exec.qclient
//返回一个列表表示成功还是失败 //返回一个列表表示成功还是失败
...@@ -179,7 +188,15 @@ func (exec *Executor) procExecCheckTx(msg queue.Message) { ...@@ -179,7 +188,15 @@ func (exec *Executor) procExecCheckTx(msg queue.Message) {
func (exec *Executor) procExecTxList(msg queue.Message) { func (exec *Executor) procExecTxList(msg queue.Message) {
datas := msg.GetData().(*types.ExecTxList) datas := msg.GetData().(*types.ExecTxList)
execute := newExecutor(datas.StateHash, exec, datas.Height, datas.BlockTime, datas.Difficulty, datas.Txs, nil) ctx := &executorCtx{
stateHash: datas.StateHash,
height: datas.Height,
blocktime: datas.BlockTime,
difficulty: datas.Difficulty,
mainHash: datas.MainHash,
parentHash: datas.ParentHash,
}
execute := newExecutor(ctx, exec, datas.Txs, nil)
execute.enableMVCC() execute.enableMVCC()
execute.api = exec.qclient execute.api = exec.qclient
var receipts []*types.Receipt var receipts []*types.Receipt
...@@ -193,6 +210,10 @@ func (exec *Executor) procExecTxList(msg queue.Message) { ...@@ -193,6 +210,10 @@ func (exec *Executor) procExecTxList(msg queue.Message) {
} }
if tx.GroupCount == 0 { if tx.GroupCount == 0 {
receipt, err := execute.execTx(tx, index) receipt, err := execute.execTx(tx, index)
if api.IsGrpcError(err) || api.IsQueueError(err) {
msg.Reply(exec.client.NewMessage("", types.EventReceipts, err))
return
}
if err != nil { if err != nil {
receipts = append(receipts, types.NewErrReceipt(err)) receipts = append(receipts, types.NewErrReceipt(err))
continue continue
...@@ -232,7 +253,15 @@ func (exec *Executor) procExecTxList(msg queue.Message) { ...@@ -232,7 +253,15 @@ func (exec *Executor) procExecTxList(msg queue.Message) {
func (exec *Executor) procExecAddBlock(msg queue.Message) { func (exec *Executor) procExecAddBlock(msg queue.Message) {
datas := msg.GetData().(*types.BlockDetail) datas := msg.GetData().(*types.BlockDetail)
b := datas.Block b := datas.Block
execute := newExecutor(b.StateHash, exec, b.Height, b.BlockTime, uint64(b.Difficulty), b.Txs, datas.Receipts) ctx := &executorCtx{
stateHash: b.StateHash,
height: b.Height,
blocktime: b.BlockTime,
difficulty: uint64(b.Difficulty),
mainHash: b.MainHash,
parentHash: b.ParentHash,
}
execute := newExecutor(ctx, exec, b.Txs, datas.Receipts)
execute.enableMVCC() execute.enableMVCC()
execute.api = exec.qclient execute.api = exec.qclient
var kvset types.LocalDBSet var kvset types.LocalDBSet
...@@ -284,7 +313,15 @@ func (exec *Executor) procExecAddBlock(msg queue.Message) { ...@@ -284,7 +313,15 @@ func (exec *Executor) procExecAddBlock(msg queue.Message) {
func (exec *Executor) procExecDelBlock(msg queue.Message) { func (exec *Executor) procExecDelBlock(msg queue.Message) {
datas := msg.GetData().(*types.BlockDetail) datas := msg.GetData().(*types.BlockDetail)
b := datas.Block b := datas.Block
execute := newExecutor(b.StateHash, exec, b.Height, b.BlockTime, uint64(b.Difficulty), b.Txs, nil) ctx := &executorCtx{
stateHash: b.StateHash,
height: b.Height,
blocktime: b.BlockTime,
difficulty: uint64(b.Difficulty),
mainHash: b.MainHash,
parentHash: b.ParentHash,
}
execute := newExecutor(ctx, exec, b.Txs, nil)
execute.enableMVCC() execute.enableMVCC()
execute.api = exec.qclient execute.api = exec.qclient
var kvset types.LocalDBSet var kvset types.LocalDBSet
......
...@@ -49,7 +49,15 @@ func TestExecutorGetTxGroup(t *testing.T) { ...@@ -49,7 +49,15 @@ func TestExecutorGetTxGroup(t *testing.T) {
txgroup.SignN(1, types.SECP256K1, priv2) txgroup.SignN(1, types.SECP256K1, priv2)
txgroup.SignN(2, types.SECP256K1, priv3) txgroup.SignN(2, types.SECP256K1, priv3)
txs = txgroup.GetTxs() txs = txgroup.GetTxs()
execute := newExecutor(nil, exec, 1, time.Now().Unix(), 1, txs, nil) ctx := &executorCtx{
stateHash: nil,
height: 1,
blocktime: time.Now().Unix(),
difficulty: 1,
mainHash: nil,
parentHash: nil,
}
execute := newExecutor(ctx, exec, txs, nil)
e := execute.loadDriver(txs[0], 0) e := execute.loadDriver(txs[0], 0)
execute.setEnv(e) execute.setEnv(e)
txs2 := e.GetTxs() txs2 := e.GetTxs()
...@@ -64,7 +72,7 @@ func TestExecutorGetTxGroup(t *testing.T) { ...@@ -64,7 +72,7 @@ func TestExecutorGetTxGroup(t *testing.T) {
//err tx group list //err tx group list
txs[0].Header = nil txs[0].Header = nil
execute = newExecutor(nil, exec, 1, time.Now().Unix(), 1, txs, nil) execute = newExecutor(ctx, exec, txs, nil)
e = execute.loadDriver(txs[0], 0) e = execute.loadDriver(txs[0], 0)
execute.setEnv(e) execute.setEnv(e)
_, err = e.GetTxGroup(len(txs) - 1) _, err = e.GetTxGroup(len(txs) - 1)
......
...@@ -76,7 +76,7 @@ func (client *client) Send(msg Message, waitReply bool) (err error) { ...@@ -76,7 +76,7 @@ func (client *client) Send(msg Message, waitReply bool) (err error) {
timeout = time.Minute timeout = time.Minute
} }
err = client.SendTimeout(msg, waitReply, timeout) err = client.SendTimeout(msg, waitReply, timeout)
if err == types.ErrTimeout { if err == ErrQueueTimeout {
panic(err) panic(err)
} }
return err return err
...@@ -85,7 +85,7 @@ func (client *client) Send(msg Message, waitReply bool) (err error) { ...@@ -85,7 +85,7 @@ func (client *client) Send(msg Message, waitReply bool) (err error) {
// SendTimeout 超时发送, msg 消息 ,waitReply 是否等待回应, timeout 超时时间 // SendTimeout 超时发送, msg 消息 ,waitReply 是否等待回应, timeout 超时时间
func (client *client) SendTimeout(msg Message, waitReply bool, timeout time.Duration) (err error) { func (client *client) SendTimeout(msg Message, waitReply bool, timeout time.Duration) (err error) {
if client.isClose() { if client.isClose() {
return types.ErrIsClosed return ErrIsQueueClosed
} }
if !waitReply { if !waitReply {
msg.chReply = nil msg.chReply = nil
...@@ -115,9 +115,9 @@ func (client *client) WaitTimeout(msg Message, timeout time.Duration) (Message, ...@@ -115,9 +115,9 @@ func (client *client) WaitTimeout(msg Message, timeout time.Duration) (Message,
case msg = <-msg.chReply: case msg = <-msg.chReply:
return msg, msg.Err() return msg, msg.Err()
case <-client.done: case <-client.done:
return Message{}, errors.New("client is closed") return Message{}, ErrIsQueueClosed
case <-t.C: case <-t.C:
return Message{}, types.ErrTimeout return Message{}, ErrQueueTimeout
} }
} }
...@@ -128,7 +128,7 @@ func (client *client) Wait(msg Message) (Message, error) { ...@@ -128,7 +128,7 @@ func (client *client) Wait(msg Message) (Message, error) {
timeout = 5 * time.Minute timeout = 5 * time.Minute
} }
msg, err := client.WaitTimeout(msg, timeout) msg, err := client.WaitTimeout(msg, timeout)
if err == types.ErrTimeout { if err == ErrQueueTimeout {
panic(err) panic(err)
} }
return msg, err return msg, err
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
package queue package queue
import ( import (
"errors"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
...@@ -32,6 +33,13 @@ const ( ...@@ -32,6 +33,13 @@ const (
defaultLowChanBuffer = 40960 defaultLowChanBuffer = 40960
) )
//消息队列的错误
var (
ErrIsQueueClosed = errors.New("ErrIsQueueClosed")
ErrQueueTimeout = errors.New("ErrQueueTimeout")
ErrQueueChannelFull = errors.New("ErrQueueChannelFull")
)
// DisableLog disable log // DisableLog disable log
func DisableLog() { func DisableLog() {
qlog.SetHandler(log.DiscardHandler()) qlog.SetHandler(log.DiscardHandler())
...@@ -162,7 +170,7 @@ func (q *queue) send(msg Message, timeout time.Duration) (err error) { ...@@ -162,7 +170,7 @@ func (q *queue) send(msg Message, timeout time.Duration) (err error) {
return nil return nil
default: default:
qlog.Debug("send chainfull", "msg", msg, "topic", msg.Topic, "sub", sub) qlog.Debug("send chainfull", "msg", msg, "topic", msg.Topic, "sub", sub)
return types.ErrChannelFull return ErrQueueChannelFull
} }
} }
t := time.NewTimer(timeout) t := time.NewTimer(timeout)
...@@ -171,7 +179,7 @@ func (q *queue) send(msg Message, timeout time.Duration) (err error) { ...@@ -171,7 +179,7 @@ func (q *queue) send(msg Message, timeout time.Duration) (err error) {
case sub.high <- msg: case sub.high <- msg:
case <-t.C: case <-t.C:
qlog.Debug("send timeout", "msg", msg, "topic", msg.Topic, "sub", sub) qlog.Debug("send timeout", "msg", msg, "topic", msg.Topic, "sub", sub)
return types.ErrTimeout return ErrQueueTimeout
} }
if msg.Topic != "store" { if msg.Topic != "store" {
qlog.Debug("send ok", "msg", msg, "topic", msg.Topic, "sub", sub) qlog.Debug("send ok", "msg", msg, "topic", msg.Topic, "sub", sub)
...@@ -192,8 +200,8 @@ func (q *queue) sendAsyn(msg Message) error { ...@@ -192,8 +200,8 @@ func (q *queue) sendAsyn(msg Message) error {
qlog.Debug("send asyn ok", "msg", msg) qlog.Debug("send asyn ok", "msg", msg)
return nil return nil
default: default:
qlog.Error("send asyn err", "msg", msg, "err", types.ErrChannelFull) qlog.Error("send asyn err", "msg", msg, "err", ErrQueueChannelFull)
return types.ErrChannelFull return ErrQueueChannelFull
} }
} }
...@@ -216,7 +224,7 @@ func (q *queue) sendLowTimeout(msg Message, timeout time.Duration) error { ...@@ -216,7 +224,7 @@ func (q *queue) sendLowTimeout(msg Message, timeout time.Duration) error {
return nil return nil
case <-t.C: case <-t.C:
qlog.Error("send asyn timeout", "msg", msg) qlog.Error("send asyn timeout", "msg", msg)
return types.ErrTimeout return ErrQueueTimeout
} }
} }
......
...@@ -43,14 +43,14 @@ func TestTimeout(t *testing.T) { ...@@ -43,14 +43,14 @@ func TestTimeout(t *testing.T) {
//再发送一个交易返回chain full //再发送一个交易返回chain full
err := client.SendTimeout(msg, true, 0) err := client.SendTimeout(msg, true, 0)
if err != types.ErrChannelFull { if err != ErrQueueChannelFull {
t.Error(err) t.Error(err)
return return
} }
//发送一个交易返回返回timeout //发送一个交易返回返回timeout
err = client.SendTimeout(msg, true, time.Millisecond) err = client.SendTimeout(msg, true, time.Millisecond)
if err != types.ErrTimeout { if err != ErrQueueTimeout {
t.Error(err) t.Error(err)
return return
} }
......
...@@ -15,6 +15,7 @@ import ( ...@@ -15,6 +15,7 @@ import (
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/client" "github.com/33cn/chain33/client"
"github.com/33cn/chain33/client/api"
"github.com/33cn/chain33/common/address" "github.com/33cn/chain33/common/address"
dbm "github.com/33cn/chain33/common/db" dbm "github.com/33cn/chain33/common/db"
log "github.com/33cn/chain33/common/log/log15" log "github.com/33cn/chain33/common/log/log15"
...@@ -41,13 +42,14 @@ type Driver interface { ...@@ -41,13 +42,14 @@ type Driver interface {
GetDriverName() string GetDriverName() string
//执行器的别名(一个驱动(code),允许创建多个执行器,类似evm一份代码可以创建多个合约) //执行器的别名(一个驱动(code),允许创建多个执行器,类似evm一份代码可以创建多个合约)
GetName() string GetName() string
GetExecutorAPI() api.ExecutorAPI
//设置执行器的真实名称 //设置执行器的真实名称
SetName(string) SetName(string)
SetCurrentExecName(string) SetCurrentExecName(string)
Allow(tx *types.Transaction, index int) error Allow(tx *types.Transaction, index int) error
IsFriend(myexec []byte, writekey []byte, othertx *types.Transaction) bool IsFriend(myexec []byte, writekey []byte, othertx *types.Transaction) bool
GetActionName(tx *types.Transaction) string GetActionName(tx *types.Transaction) string
SetEnv(height, blocktime int64, difficulty uint64) SetEnv(height, blocktime int64, difficulty uint64, parentHash, mainHash []byte)
CheckTx(tx *types.Transaction, index int) error CheckTx(tx *types.Transaction, index int) error
Exec(tx *types.Transaction, index int) (*types.Receipt, error) Exec(tx *types.Transaction, index int) (*types.Receipt, error)
ExecLocal(tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) ExecLocal(tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error)
...@@ -69,21 +71,23 @@ type Driver interface { ...@@ -69,21 +71,23 @@ type Driver interface {
// DriverBase defines driverbase type // DriverBase defines driverbase type
type DriverBase struct { type DriverBase struct {
statedb dbm.KV statedb dbm.KV
localdb dbm.KVDB localdb dbm.KVDB
coinsaccount *account.DB coinsaccount *account.DB
height int64 height int64
blocktime int64 blocktime int64
name string parentHash, mainHash []byte
curname string name string
child Driver curname string
childValue reflect.Value child Driver
isFree bool childValue reflect.Value
difficulty uint64 isFree bool
api client.QueueProtocolAPI difficulty uint64
txs []*types.Transaction api client.QueueProtocolAPI
receipts []*types.ReceiptData execapi api.ExecutorAPI
ety types.ExecutorType txs []*types.Transaction
receipts []*types.ReceiptData
ety types.ExecutorType
} }
// GetPayloadValue define get payload func // GetPayloadValue define get payload func
...@@ -99,6 +103,19 @@ func (d *DriverBase) GetExecutorType() types.ExecutorType { ...@@ -99,6 +103,19 @@ func (d *DriverBase) GetExecutorType() types.ExecutorType {
return d.ety return d.ety
} }
//GetLastHash 获取最后区块的hash,主链和平行链不同
func (d *DriverBase) GetLastHash() []byte {
if types.IsPara() {
return d.mainHash
}
return d.parentHash
}
//GetParentHash 获取上一个区块的hash
func (d *DriverBase) GetParentHash() []byte {
return d.parentHash
}
// GetFuncMap defines get execfuncmap func // GetFuncMap defines get execfuncmap func
func (d *DriverBase) GetFuncMap() map[string]reflect.Method { func (d *DriverBase) GetFuncMap() map[string]reflect.Method {
if d.ety == nil { if d.ety == nil {
...@@ -108,8 +125,9 @@ func (d *DriverBase) GetFuncMap() map[string]reflect.Method { ...@@ -108,8 +125,9 @@ func (d *DriverBase) GetFuncMap() map[string]reflect.Method {
} }
// SetAPI set queue protocol api // SetAPI set queue protocol api
func (d *DriverBase) SetAPI(api client.QueueProtocolAPI) { func (d *DriverBase) SetAPI(queueapi client.QueueProtocolAPI) {
d.api = api d.api = queueapi
d.execapi = api.New(queueapi, "")
} }
// GetAPI return queue protocol api // GetAPI return queue protocol api
...@@ -117,11 +135,18 @@ func (d *DriverBase) GetAPI() client.QueueProtocolAPI { ...@@ -117,11 +135,18 @@ func (d *DriverBase) GetAPI() client.QueueProtocolAPI {
return d.api return d.api
} }
// GetExecutorAPI return executor api
func (d *DriverBase) GetExecutorAPI() api.ExecutorAPI {
return d.execapi
}
// SetEnv set env // SetEnv set env
func (d *DriverBase) SetEnv(height, blocktime int64, difficulty uint64) { func (d *DriverBase) SetEnv(height, blocktime int64, difficulty uint64, parentHash, mainHash []byte) {
d.height = height d.height = height
d.blocktime = blocktime d.blocktime = blocktime
d.difficulty = difficulty d.difficulty = difficulty
d.parentHash = parentHash
d.mainHash = mainHash
} }
// SetIsFree set isfree // SetIsFree set isfree
......
...@@ -2,8 +2,11 @@ package dapp ...@@ -2,8 +2,11 @@ package dapp
import ( import (
"testing" "testing"
"time"
"github.com/33cn/chain33/client/mocks"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/33cn/chain33/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
...@@ -35,9 +38,12 @@ func (none *noneApp) GetDriverName() string { ...@@ -35,9 +38,12 @@ func (none *noneApp) GetDriverName() string {
return "none" return "none"
} }
func TestReigister(t *testing.T) { func init() {
Register("none", newnoneApp, 0) Register("none", newnoneApp, 0)
Register("demo", newdemoApp, 1) Register("demo", newdemoApp, 1)
}
func TestReigister(t *testing.T) {
_, err := LoadDriver("demo", 0) _, err := LoadDriver("demo", 0)
assert.Equal(t, err, types.ErrUnknowDriver) assert.Equal(t, err, types.ErrUnknowDriver)
_, err = LoadDriver("demo", 1) _, err = LoadDriver("demo", 1)
...@@ -65,6 +71,47 @@ func TestReigister(t *testing.T) { ...@@ -65,6 +71,47 @@ func TestReigister(t *testing.T) {
assert.Equal(t, "none", driver.GetDriverName()) assert.Equal(t, "none", driver.GetDriverName())
} }
func TestDriverAPI(t *testing.T) {
tx := &types.Transaction{Execer: []byte("demo")}
demo := LoadDriverAllow(tx, 0, 1).(*demoApp)
dir, ldb, kvdb := util.CreateTestDB()
defer util.CloseTestDB(dir, ldb)
demo.SetEnv(1, time.Now().Unix(), 1, []byte("parentHash"), []byte("mainHash"))
demo.SetLocalDB(kvdb)
demo.SetStateDB(kvdb)
demo.SetAPI(&mocks.QueueProtocolAPI{})
assert.NotNil(t, demo.GetAPI())
assert.NotNil(t, demo.GetExecutorAPI())
types.SetTitleOnlyForTest("chain33")
assert.Equal(t, "parentHash", string(demo.GetParentHash()))
assert.Equal(t, "parentHash", string(demo.GetLastHash()))
types.SetTitleOnlyForTest("user.p.wzw.")
assert.Equal(t, "parentHash", string(demo.GetParentHash()))
assert.Equal(t, "mainHash", string(demo.GetLastHash()))
assert.Equal(t, true, IsDriverAddress(ExecAddress("none"), 0))
assert.Equal(t, false, IsDriverAddress(ExecAddress("demo"), 0))
assert.Equal(t, true, IsDriverAddress(ExecAddress("demo"), 1))
}
func TestExecAddress(t *testing.T) { func TestExecAddress(t *testing.T) {
assert.Equal(t, "16htvcBNSEA7fZhAdLJphDwQRQJaHpyHTp", ExecAddress("ticket")) assert.Equal(t, "16htvcBNSEA7fZhAdLJphDwQRQJaHpyHTp", ExecAddress("ticket"))
} }
func TestAllow(t *testing.T) {
tx := &types.Transaction{Execer: []byte("demo")}
demo := LoadDriverAllow(tx, 0, 1).(*demoApp)
assert.Equal(t, true, demo.AllowIsSame([]byte("demo")))
types.SetTitleOnlyForTest("user.p.wzw.")
assert.Equal(t, true, demo.AllowIsSame([]byte("user.p.wzw.demo")))
assert.Equal(t, false, demo.AllowIsSame([]byte("user.p.wzw2.demo")))
assert.Equal(t, false, demo.AllowIsUserDot1([]byte("user.p.wzw.demo")))
assert.Equal(t, true, demo.AllowIsUserDot1([]byte("user.demo")))
assert.Equal(t, true, demo.AllowIsUserDot1([]byte("user.p.wzw.user.demo")))
assert.Equal(t, true, demo.AllowIsUserDot2([]byte("user.p.wzw.user.demo.xxxx")))
assert.Equal(t, true, demo.AllowIsUserDot2([]byte("user.demo.xxxx")))
assert.Equal(t, nil, demo.Allow(tx, 0))
tx = &types.Transaction{Execer: []byte("demo2")}
assert.Equal(t, types.ErrNotAllow, demo.Allow(tx, 0))
assert.Equal(t, false, demo.IsFriend(nil, nil, nil))
}
...@@ -7,23 +7,12 @@ package dapp ...@@ -7,23 +7,12 @@ package dapp
//store package store the world - state data //store package store the world - state data
import ( import (
"github.com/33cn/chain33/common/address" "github.com/33cn/chain33/common/address"
clog "github.com/33cn/chain33/common/log"
log "github.com/33cn/chain33/common/log/log15" log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
) )
var elog = log.New("module", "execs") var elog = log.New("module", "execs")
// SetLogLevel set log level
func SetLogLevel(level string) {
clog.SetLogLevel(level)
}
// DisableLog disable log
func DisableLog() {
elog.SetHandler(log.DiscardHandler())
}
// DriverCreate defines a drivercreate function // DriverCreate defines a drivercreate function
type DriverCreate func() Driver type DriverCreate func() Driver
......
...@@ -65,19 +65,12 @@ type Mempool struct { ...@@ -65,19 +65,12 @@ type Mempool struct {
// Consensus 配置 // Consensus 配置
type Consensus struct { type Consensus struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
GenesisBlockTime int64 `protobuf:"varint,2,opt,name=genesisBlockTime" json:"genesisBlockTime,omitempty"` GenesisBlockTime int64 `protobuf:"varint,2,opt,name=genesisBlockTime" json:"genesisBlockTime,omitempty"`
Minerstart bool `protobuf:"varint,3,opt,name=minerstart" json:"minerstart,omitempty"` Minerstart bool `protobuf:"varint,3,opt,name=minerstart" json:"minerstart,omitempty"`
Genesis string `protobuf:"bytes,4,opt,name=genesis" json:"genesis,omitempty"` Genesis string `protobuf:"bytes,4,opt,name=genesis" json:"genesis,omitempty"`
HotkeyAddr string `protobuf:"bytes,5,opt,name=hotkeyAddr" json:"hotkeyAddr,omitempty"` HotkeyAddr string `protobuf:"bytes,5,opt,name=hotkeyAddr" json:"hotkeyAddr,omitempty"`
ForceMining bool `protobuf:"varint,6,opt,name=forceMining" json:"forceMining,omitempty"` ForceMining bool `protobuf:"varint,6,opt,name=forceMining" json:"forceMining,omitempty"`
WriteBlockSeconds int64 `protobuf:"varint,20,opt,name=writeBlockSeconds" json:"writeBlockSeconds,omitempty"`
ParaRemoteGrpcClient string `protobuf:"bytes,22,opt,name=paraRemoteGrpcClient" json:"paraRemoteGrpcClient,omitempty"`
StartHeight int64 `protobuf:"varint,23,opt,name=startHeight" json:"startHeight,omitempty"`
EmptyBlockInterval int64 `protobuf:"varint,24,opt,name=emptyBlockInterval" json:"emptyBlockInterval,omitempty"`
AuthAccount string `protobuf:"bytes,25,opt,name=authAccount" json:"authAccount,omitempty"`
WaitBlocks4CommitMsg int32 `protobuf:"varint,26,opt,name=waitBlocks4CommitMsg" json:"waitBlocks4CommitMsg,omitempty"`
SearchHashMatchedBlockDepth int32 `protobuf:"varint,27,opt,name=searchHashMatchedBlockDepth" json:"searchHashMatchedBlockDepth,omitempty"`
} }
// Wallet 配置 // Wallet 配置
......
...@@ -27,7 +27,6 @@ var ( ...@@ -27,7 +27,6 @@ var (
ErrReRunGenesis = errors.New("ErrReRunGenesis") ErrReRunGenesis = errors.New("ErrReRunGenesis")
ErrActionNotSupport = errors.New("ErrActionNotSupport") ErrActionNotSupport = errors.New("ErrActionNotSupport")
ErrQueryNotSupport = errors.New("ErrQueryNotSupport") ErrQueryNotSupport = errors.New("ErrQueryNotSupport")
ErrChannelFull = errors.New("ErrChannelFull")
ErrAmount = errors.New("ErrAmount") ErrAmount = errors.New("ErrAmount")
ErrMinerIsStared = errors.New("ErrMinerIsStared") ErrMinerIsStared = errors.New("ErrMinerIsStared")
ErrMinerNotStared = errors.New("ErrMinerNotStared") ErrMinerNotStared = errors.New("ErrMinerNotStared")
...@@ -57,11 +56,11 @@ var ( ...@@ -57,11 +56,11 @@ var (
ErrToAddrNotSameToExecAddr = errors.New("ErrToAddrNotSameToExecAddr") ErrToAddrNotSameToExecAddr = errors.New("ErrToAddrNotSameToExecAddr")
ErrTypeAsset = errors.New("ErrTypeAsset") ErrTypeAsset = errors.New("ErrTypeAsset")
ErrEmpty = errors.New("ErrEmpty") ErrEmpty = errors.New("ErrEmpty")
ErrIsClosed = errors.New("ErrIsClosed")
ErrSendSameToRecv = errors.New("ErrSendSameToRecv") ErrSendSameToRecv = errors.New("ErrSendSameToRecv")
ErrExecNameNotAllow = errors.New("ErrExecNameNotAllow") ErrExecNameNotAllow = errors.New("ErrExecNameNotAllow")
ErrExecNotFound = errors.New("ErrExecNotFound") ErrExecNotFound = errors.New("ErrExecNotFound")
ErrLocalDBPerfix = errors.New("ErrLocalDBPerfix") ErrLocalDBPerfix = errors.New("ErrLocalDBPerfix")
ErrTimeout = errors.New("ErrTimeout")
ErrBlockHeaderDifficulty = errors.New("ErrBlockHeaderDifficulty") ErrBlockHeaderDifficulty = errors.New("ErrBlockHeaderDifficulty")
ErrNoTx = errors.New("ErrNoTx") ErrNoTx = errors.New("ErrNoTx")
ErrTxExist = errors.New("ErrTxExist") ErrTxExist = errors.New("ErrTxExist")
...@@ -99,7 +98,6 @@ var ( ...@@ -99,7 +98,6 @@ var (
ErrBlockHeightNoMatch = errors.New("ErrBlockHeightNoEqual") ErrBlockHeightNoMatch = errors.New("ErrBlockHeightNoEqual")
ErrParentTdNoExist = errors.New("ErrParentTdNoExist") ErrParentTdNoExist = errors.New("ErrParentTdNoExist")
ErrBlockHashNoMatch = errors.New("ErrBlockHashNoMatch") ErrBlockHashNoMatch = errors.New("ErrBlockHashNoMatch")
ErrIsClosed = errors.New("ErrIsClosed")
ErrDecode = errors.New("ErrDecode") ErrDecode = errors.New("ErrDecode")
ErrNotRollBack = errors.New("ErrNotRollBack") ErrNotRollBack = errors.New("ErrNotRollBack")
ErrPeerInfoIsNil = errors.New("ErrPeerInfoIsNil") ErrPeerInfoIsNil = errors.New("ErrPeerInfoIsNil")
......
...@@ -62,6 +62,8 @@ func (m *Genesis) GetIsrun() bool { ...@@ -62,6 +62,8 @@ func (m *Genesis) GetIsrun() bool {
type ExecTxList struct { type ExecTxList struct {
StateHash []byte `protobuf:"bytes,1,opt,name=stateHash,proto3" json:"stateHash,omitempty"` StateHash []byte `protobuf:"bytes,1,opt,name=stateHash,proto3" json:"stateHash,omitempty"`
ParentHash []byte `protobuf:"bytes,7,opt,name=parentHash,proto3" json:"parentHash,omitempty"`
MainHash []byte `protobuf:"bytes,8,opt,name=mainHash,proto3" json:"mainHash,omitempty"`
Txs []*Transaction `protobuf:"bytes,2,rep,name=txs,proto3" json:"txs,omitempty"` Txs []*Transaction `protobuf:"bytes,2,rep,name=txs,proto3" json:"txs,omitempty"`
BlockTime int64 `protobuf:"varint,3,opt,name=blockTime,proto3" json:"blockTime,omitempty"` BlockTime int64 `protobuf:"varint,3,opt,name=blockTime,proto3" json:"blockTime,omitempty"`
Height int64 `protobuf:"varint,4,opt,name=height,proto3" json:"height,omitempty"` Height int64 `protobuf:"varint,4,opt,name=height,proto3" json:"height,omitempty"`
...@@ -104,6 +106,20 @@ func (m *ExecTxList) GetStateHash() []byte { ...@@ -104,6 +106,20 @@ func (m *ExecTxList) GetStateHash() []byte {
return nil return nil
} }
func (m *ExecTxList) GetParentHash() []byte {
if m != nil {
return m.ParentHash
}
return nil
}
func (m *ExecTxList) GetMainHash() []byte {
if m != nil {
return m.MainHash
}
return nil
}
func (m *ExecTxList) GetTxs() []*Transaction { func (m *ExecTxList) GetTxs() []*Transaction {
if m != nil { if m != nil {
return m.Txs return m.Txs
...@@ -816,45 +832,46 @@ func init() { ...@@ -816,45 +832,46 @@ func init() {
func init() { proto.RegisterFile("executor.proto", fileDescriptor_12d1cdcda51e000f) } func init() { proto.RegisterFile("executor.proto", fileDescriptor_12d1cdcda51e000f) }
var fileDescriptor_12d1cdcda51e000f = []byte{ var fileDescriptor_12d1cdcda51e000f = []byte{
// 633 bytes of a gzipped FileDescriptorProto // 653 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x61, 0x6b, 0xdb, 0x48, 0x1f, 0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x13, 0x3b, 0xc9, 0x4f, 0xa8, 0xab, 0x29, 0x32, 0x33, 0x46, 0x39, 0xa7, 0x45, 0x71, 0xc7, 0x24, 0x27, 0x1c, 0x3a, 0x95, 0xef, 0x54, 0x0f, 0x09, 0x76, 0x06, 0x7b, 0x06, 0xef, 0xb5, 0xe0,
0x25, 0xe0, 0xb2, 0x6a, 0x4d, 0xe3, 0xcd, 0x95, 0x37, 0x36, 0xd9, 0x1d, 0x70, 0x75, 0x7a, 0xf7, 0xf6, 0xdf, 0xb5, 0x8f, 0x89, 0xfb, 0x13, 0xdb, 0xf1, 0x1f, 0xa8, 0x3d, 0x53, 0x64, 0x66, 0x84,
0x62, 0x2e, 0x69, 0x91, 0xdd, 0xf7, 0x85, 0x5e, 0x5d, 0x0e, 0x87, 0x42, 0x5d, 0x8a, 0x05, 0x97, 0x72, 0x46, 0xf3, 0x62, 0x8f, 0x4b, 0xc0, 0xb2, 0x6a, 0x45, 0xa3, 0xf5, 0x96, 0xd7, 0xd7, 0xec,
0x6a, 0x38, 0xbc, 0xf4, 0x03, 0xbb, 0xdf, 0xf3, 0x4f, 0xd7, 0xf0, 0x47, 0x00, 0x00, 0x00, 0xff, 0x16, 0xb8, 0x38, 0xbe, 0x79, 0x35, 0x93, 0x34, 0xcf, 0x6e, 0x7b, 0x42, 0x2f, 0xcf, 0x07, 0x03,
0xff, 0x95, 0x0a, 0xd4, 0x55, 0xe6, 0x04, 0x00, 0x00, 0xa1, 0xce, 0xc5, 0x9c, 0x4b, 0x35, 0x18, 0x9c, 0xbb, 0x81, 0xdd, 0xee, 0xb8, 0x67, 0x6f, 0xf0,
0x3b, 0x00, 0x00, 0xff, 0xff, 0xd4, 0xce, 0x6b, 0x62, 0x22, 0x05, 0x00, 0x00,
} }
...@@ -28,6 +28,7 @@ message Header { ...@@ -28,6 +28,7 @@ message Header {
Signature signature = 8; Signature signature = 8;
} }
// 参考Header解释 // 参考Header解释
// mainHash 平行链上使用的字段,代表这个区块的主链hash
message Block { message Block {
int64 version = 1; int64 version = 1;
bytes parentHash = 2; bytes parentHash = 2;
...@@ -36,6 +37,7 @@ message Block { ...@@ -36,6 +37,7 @@ message Block {
int64 height = 5; int64 height = 5;
int64 blockTime = 6; int64 blockTime = 6;
uint32 difficulty = 11; uint32 difficulty = 11;
bytes mainHash = 12;
Signature signature = 8; Signature signature = 8;
repeated Transaction txs = 7; repeated Transaction txs = 7;
} }
......
...@@ -11,6 +11,8 @@ message Genesis { ...@@ -11,6 +11,8 @@ message Genesis {
message ExecTxList { message ExecTxList {
bytes stateHash = 1; bytes stateHash = 1;
bytes parentHash = 7;
bytes mainHash = 8;
repeated Transaction txs = 2; repeated Transaction txs = 2;
int64 blockTime = 3; int64 blockTime = 3;
int64 height = 4; int64 height = 4;
......
...@@ -30,9 +30,11 @@ func CheckBlock(client queue.Client, block *types.BlockDetail) error { ...@@ -30,9 +30,11 @@ func CheckBlock(client queue.Client, block *types.BlockDetail) error {
} }
//ExecTx : To send lists of txs within a block to exector for execution //ExecTx : To send lists of txs within a block to exector for execution
func ExecTx(client queue.Client, prevStateRoot []byte, block *types.Block) *types.Receipts { func ExecTx(client queue.Client, prevStateRoot []byte, block *types.Block) (*types.Receipts, error) {
list := &types.ExecTxList{ list := &types.ExecTxList{
StateHash: prevStateRoot, StateHash: prevStateRoot,
ParentHash: block.ParentHash,
MainHash: block.MainHash,
Txs: block.Txs, Txs: block.Txs,
BlockTime: block.BlockTime, BlockTime: block.BlockTime,
Height: block.Height, Height: block.Height,
...@@ -43,14 +45,14 @@ func ExecTx(client queue.Client, prevStateRoot []byte, block *types.Block) *type ...@@ -43,14 +45,14 @@ func ExecTx(client queue.Client, prevStateRoot []byte, block *types.Block) *type
client.Send(msg, true) client.Send(msg, true)
resp, err := client.Wait(msg) resp, err := client.Wait(msg)
if err != nil { if err != nil {
panic(err) return nil, err
} }
receipts := resp.GetData().(*types.Receipts) receipts := resp.GetData().(*types.Receipts)
return receipts return receipts, nil
} }
//ExecKVMemSet : send kv values to memory store and set it in db //ExecKVMemSet : send kv values to memory store and set it in db
func ExecKVMemSet(client queue.Client, prevStateRoot []byte, height int64, kvset []*types.KeyValue, sync bool) []byte { func ExecKVMemSet(client queue.Client, prevStateRoot []byte, height int64, kvset []*types.KeyValue, sync bool) ([]byte, error) {
set := &types.StoreSet{StateHash: prevStateRoot, KV: kvset, Height: height} set := &types.StoreSet{StateHash: prevStateRoot, KV: kvset, Height: height}
setwithsync := &types.StoreSetWithSync{Storeset: set, Sync: sync} setwithsync := &types.StoreSetWithSync{Storeset: set, Sync: sync}
...@@ -58,10 +60,10 @@ func ExecKVMemSet(client queue.Client, prevStateRoot []byte, height int64, kvset ...@@ -58,10 +60,10 @@ func ExecKVMemSet(client queue.Client, prevStateRoot []byte, height int64, kvset
client.Send(msg, true) client.Send(msg, true)
resp, err := client.Wait(msg) resp, err := client.Wait(msg)
if err != nil { if err != nil {
panic(err) return nil, err
} }
hash := resp.GetData().(*types.ReplyHash) hash := resp.GetData().(*types.ReplyHash)
return hash.GetHash() return hash.GetHash(), nil
} }
//ExecKVSetCommit : commit the data set opetation to db //ExecKVSetCommit : commit the data set opetation to db
......
...@@ -102,6 +102,20 @@ targetTimePerBlock = 2 ...@@ -102,6 +102,20 @@ targetTimePerBlock = 2
[mver.consensus.ForkChainParamV2] [mver.consensus.ForkChainParamV2]
powLimitBits = "0x1f2fffff" powLimitBits = "0x1f2fffff"
[consensus.sub.para]
ParaRemoteGrpcClient="localhost:8802"
#主链指定高度的区块开始同步
startHeight=345850
#打包时间间隔,单位秒
writeBlockSeconds=2
#主链每隔几个没有相关交易的区块,平行链上打包空区块
emptyBlockInterval=50
#验证账户,验证节点需要配置自己的账户,并且钱包导入对应种子,非验证节点留空
authAccount=""
#等待平行链共识消息在主链上链并成功的块数,超出会重发共识消息,最小是2
waitBlocks4CommitMsg=2
searchHashMatchedBlockDepth=100
[consensus.sub.solo] [consensus.sub.solo]
genesis="14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" genesis="14KEKbYtKKQm4wMthSK9J4La4nAiidGozt"
genesisBlockTime=1514533394 genesisBlockTime=1514533394
......
...@@ -245,7 +245,10 @@ func ExecBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er ...@@ -245,7 +245,10 @@ func ExecBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er
block.TxHash = merkle.CalcMerkleRootCache(cacheTxs) block.TxHash = merkle.CalcMerkleRootCache(cacheTxs)
block.Txs = types.CacheToTxs(cacheTxs) block.Txs = types.CacheToTxs(cacheTxs)
receipts := ExecTx(client, prevStateRoot, block) receipts, err := ExecTx(client, prevStateRoot, block)
if err != nil {
return nil, nil, err
}
var kvset []*types.KeyValue var kvset []*types.KeyValue
var deltxlist = make(map[int]bool) var deltxlist = make(map[int]bool)
var rdata []*types.ReceiptData //save to db receipt log var rdata []*types.ReceiptData //save to db receipt log
...@@ -285,7 +288,10 @@ func ExecBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er ...@@ -285,7 +288,10 @@ func ExecBlock(client queue.Client, prevStateRoot []byte, block *types.Block, er
} }
var detail types.BlockDetail var detail types.BlockDetail
calcHash = ExecKVMemSet(client, prevStateRoot, block.Height, kvset, sync) calcHash, err = ExecKVMemSet(client, prevStateRoot, block.Height, kvset, sync)
if err != nil {
return nil, nil, err
}
if errReturn && !bytes.Equal(block.StateHash, calcHash) { if errReturn && !bytes.Equal(block.StateHash, calcHash) {
ExecKVSetRollback(client, calcHash) ExecKVSetRollback(client, calcHash)
if len(rdata) > 0 { if len(rdata) > 0 {
......
...@@ -139,7 +139,10 @@ func SaveAccountTomavl(client queue.Client, prevStateRoot []byte, accs []*types. ...@@ -139,7 +139,10 @@ func SaveAccountTomavl(client queue.Client, prevStateRoot []byte, accs []*types.
kvs := accountdb.GetKVSet(acc) kvs := accountdb.GetKVSet(acc)
kvset = append(kvset, kvs...) kvset = append(kvset, kvs...)
} }
hash := util.ExecKVMemSet(client, prevStateRoot, 0, kvset, true) hash, err := util.ExecKVMemSet(client, prevStateRoot, 0, kvset, true)
if err != nil {
panic(err)
}
Statehash = hash Statehash = hash
util.ExecKVSetCommit(client, Statehash) util.ExecKVSetCommit(client, Statehash)
return hash return hash
......
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