Commit 973b4e61 authored by Litian's avatar Litian

Merge branch 'master' into evm_abi

parents 781721f6 83795d85
...@@ -11,6 +11,7 @@ APP := build/chain33 ...@@ -11,6 +11,7 @@ APP := build/chain33
CHAIN33=github.com/33cn/chain33 CHAIN33=github.com/33cn/chain33
CHAIN33_PATH=vendor/${CHAIN33} CHAIN33_PATH=vendor/${CHAIN33}
LDFLAGS := -ldflags "-w -s" LDFLAGS := -ldflags "-w -s"
PKG_LIST_VET := `go list ./... | grep -v "vendor" | grep -v plugin/dapp/evm/executor/vm/common/crypto/bn256`
PKG_LIST := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "pbft"` PKG_LIST := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "pbft"`
PKG_LIST_Q := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "blockchain" | grep -v "pbft"` PKG_LIST_Q := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "blockchain" | grep -v "pbft"`
BUILD_FLAGS = -ldflags "-X github.com/33cn/chain33/common/version.GitCommit=`git rev-parse --short=8 HEAD`" BUILD_FLAGS = -ldflags "-X github.com/33cn/chain33/common/version.GitCommit=`git rev-parse --short=8 HEAD`"
...@@ -35,6 +36,8 @@ build_ci: depends ## Build the binary file for CI ...@@ -35,6 +36,8 @@ build_ci: depends ## Build the binary file for CI
para: para:
@go build -v -o build/$(NAME) -ldflags "-X $(SRC_CLI)/buildflags.ParaName=user.p.$(NAME). -X $(SRC_CLI)/buildflags.RPCAddr=http://localhost:8901" $(SRC_CLI) @go build -v -o build/$(NAME) -ldflags "-X $(SRC_CLI)/buildflags.ParaName=user.p.$(NAME). -X $(SRC_CLI)/buildflags.RPCAddr=http://localhost:8901" $(SRC_CLI)
vet:
@go vet ${PKG_LIST_VET}
autotest: ## build autotest binary autotest: ## build autotest binary
@cd build/autotest && bash ./build.sh && cd ../../ @cd build/autotest && bash ./build.sh && cd ../../
...@@ -55,7 +58,7 @@ autotest_tick: autotest ## run with ticket mining ...@@ -55,7 +58,7 @@ autotest_tick: autotest ## run with ticket mining
update: update:
rm -rf ${CHAIN33_PATH} rm -rf ${CHAIN33_PATH}
git clone --depth 1 -b master https://${CHAIN33}.git ${CHAIN33_PATH} git clone --depth 1 -b ${b} https://${CHAIN33}.git ${CHAIN33_PATH}
rm -rf vendor/${CHAIN33}/.git rm -rf vendor/${CHAIN33}/.git
rm -rf vendor/${CHAIN33}/vendor/github.com/apache/thrift/tutorial/erl/ rm -rf vendor/${CHAIN33}/vendor/github.com/apache/thrift/tutorial/erl/
cp -Rf vendor/${CHAIN33}/vendor/* vendor/ cp -Rf vendor/${CHAIN33}/vendor/* vendor/
...@@ -71,30 +74,12 @@ updatevendor: ...@@ -71,30 +74,12 @@ updatevendor:
dep: dep:
dep init -v dep init -v
linter: vet ## Use gometalinter check code, ignore some unserious warning
@./golinter.sh "filter"
@find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck
linter: ## Use gometalinter check code, ignore some unserious warning linter_test: ## Use gometalinter check code, for local test
@res=$$(gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \ @./golinter.sh "test" "${p}"
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--vendor ./...) \
# --enable=vet \
# --enable=staticcheck \
# --enable=gocyclo \
# --enable=staticcheck \
# --enable=golint \
# --enable=unused \
# --enable=gotype \
# --enable=gotypex \
if [ -n "$$res" ]; then \
echo "$${res}"; \
exit 1; \
fi;
@find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck @find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck
race: ## Run data race detector race: ## Run data race detector
...@@ -260,4 +245,23 @@ push: ...@@ -260,4 +245,23 @@ push:
make sync make sync
git checkout ${b} git checkout ${b}
git merge master git merge master
git push origin ${b} git push origin ${b}
\ No newline at end of file
pull:
@remotelist=$$(git remote | grep ${name});if [ -z $$remotelist ]; then \
echo ${remotelist}; \
git remote add ${name} https://github.com/${name}/plugin.git ; \
fi;
git fetch ${name}
git checkout ${name}/${b}
git checkout -b ${name}-${b}
pullsync:
git fetch ${name}
git checkout ${name}-${b}
git merge ${name}/${b}
pullpush:
@if [ -n "$$m" ]; then \
git commit -a -m "${m}" ; \
fi;
make pullsync
git push ${name} ${name}-${b}:${b}
...@@ -4,5 +4,8 @@ ...@@ -4,5 +4,8 @@
package buildflags package buildflags
// ParaName para name
var ParaName string var ParaName string
// RPCAddr rpc address
var RPCAddr string var RPCAddr string
#!/bin/bash
# shellcheck disable=SC2207
set +e
OP="${1}"
path="${2}"
function filterLinter() {
res=$(gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--vendor ./...)
# --enable=staticcheck \
# --enable=gocyclo \
# --enable=staticcheck \
# --enable=golint \
# --enable=unused \
# --enable=gotype \
# --enable=gotypex \
if [[ ${#res} -gt "0" ]]; then
resNoSpace=$(echo "${res}" | tr ' ' '@')
array=($(echo "${resNoSpace}" | tr '\n' '\n'))
str=""
for var in ${array[*]}; do
if ! [[ $var =~ "underscores" ]]; then
str="${str}""${var}""\\n"
fi
done
res=""
res=$(echo "${str}" | tr '@' ' ')
fi
if [[ ${#res} -gt "0" ]]; then
echo -e "${res}"
exit 1
fi
}
function testLinter() {
cd "${path}" >/dev/null || exit
gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--enable=vet \
--enable=golint \
--enable=ineffassign \
--vendor ./...
cd - >/dev/null || exit
}
function main() {
if [ "${OP}" == "filter" ]; then
filterLinter
elif [ "${OP}" == "test" ]; then
testLinter
fi
}
# run script
main
...@@ -2,13 +2,13 @@ ...@@ -2,13 +2,13 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// +build go1.9
/* /*
每个系统的功能通过插件完成,插件分成4类: 每个系统的功能通过插件完成,插件分成4类:
共识 加密 dapp 存储 共识 加密 dapp 存储
这个go 包提供了 官方提供的 插件。 这个go 包提供了 官方提供的 插件。
*/ */
// +build go1.8
package main package main
import ( import (
......
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package init package init
import ( import (
......
...@@ -43,6 +43,7 @@ type envelope struct { ...@@ -43,6 +43,7 @@ type envelope struct {
Data *json.RawMessage `json:"data"` Data *json.RawMessage `json:"data"`
} }
// EvidenceInfo struct
type EvidenceInfo struct { type EvidenceInfo struct {
Committed bool `json:"committed"` Committed bool `json:"committed"`
Priority int64 `json:"priority"` Priority int64 `json:"priority"`
...@@ -77,8 +78,8 @@ func keyPending(evidence ttypes.Evidence) []byte { ...@@ -77,8 +78,8 @@ func keyPending(evidence ttypes.Evidence) []byte {
return _key("%s/%s/%X", baseKeyPending, bE(evidence.Height()), evidence.Hash()) return _key("%s/%s/%X", baseKeyPending, bE(evidence.Height()), evidence.Hash())
} }
func _key(fmt_ string, o ...interface{}) []byte { func _key(s string, o ...interface{}) []byte {
return []byte(fmt.Sprintf(fmt_, o...)) return []byte(fmt.Sprintf(s, o...))
} }
// EvidenceStore is a store of all the evidence we've seen, including // EvidenceStore is a store of all the evidence we've seen, including
...@@ -88,6 +89,7 @@ type EvidenceStore struct { ...@@ -88,6 +89,7 @@ type EvidenceStore struct {
db dbm.DB db dbm.DB
} }
// NewEvidenceStore method
func NewEvidenceStore(db dbm.DB) *EvidenceStore { func NewEvidenceStore(db dbm.DB) *EvidenceStore {
if len(ttypes.EvidenceType2Type) == 0 { if len(ttypes.EvidenceType2Type) == 0 {
ttypes.EvidenceType2Type = map[string]reflect.Type{ ttypes.EvidenceType2Type = map[string]reflect.Type{
...@@ -160,8 +162,8 @@ func (store *EvidenceStore) GetEvidence(height int64, hash []byte) *EvidenceInfo ...@@ -160,8 +162,8 @@ func (store *EvidenceStore) GetEvidence(height int64, hash []byte) *EvidenceInfo
// It returns false if the evidence is already stored. // It returns false if the evidence is already stored.
func (store *EvidenceStore) AddNewEvidence(evidence ttypes.Evidence, priority int64) bool { func (store *EvidenceStore) AddNewEvidence(evidence ttypes.Evidence, priority int64) bool {
// check if we already have seen it // check if we already have seen it
ei_ := store.GetEvidence(evidence.Height(), evidence.Hash()) ei := store.GetEvidence(evidence.Height(), evidence.Hash())
if ei_ != nil && len(ei_.Evidence.Kind) == 0 { if ei != nil && len(ei.Evidence.Kind) == 0 {
return false return false
} }
...@@ -191,7 +193,7 @@ func (store *EvidenceStore) MarkEvidenceAsBroadcasted(evidence ttypes.Evidence) ...@@ -191,7 +193,7 @@ func (store *EvidenceStore) MarkEvidenceAsBroadcasted(evidence ttypes.Evidence)
store.db.Delete(key) store.db.Delete(key)
} }
// MarkEvidenceAsPending removes evidence from pending and outqueue and sets the state to committed. // MarkEvidenceAsCommitted removes evidence from pending and outqueue and sets the state to committed.
func (store *EvidenceStore) MarkEvidenceAsCommitted(evidence ttypes.Evidence) { func (store *EvidenceStore) MarkEvidenceAsCommitted(evidence ttypes.Evidence) {
// if its committed, its been broadcast // if its committed, its been broadcast
store.MarkEvidenceAsBroadcasted(evidence) store.MarkEvidenceAsBroadcasted(evidence)
...@@ -227,6 +229,7 @@ func (store *EvidenceStore) getEvidenceInfo(evidence ttypes.Evidence) EvidenceIn ...@@ -227,6 +229,7 @@ func (store *EvidenceStore) getEvidenceInfo(evidence ttypes.Evidence) EvidenceIn
return ei return ei
} }
// EvidenceToInfoBytes method
func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, error) { func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, error) {
evi, err := json.Marshal(evidence) evi, err := json.Marshal(evidence)
if err != nil { if err != nil {
...@@ -250,6 +253,7 @@ func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, erro ...@@ -250,6 +253,7 @@ func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, erro
return eiBytes, nil return eiBytes, nil
} }
// EvidenceFromInfoBytes method
func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence, error) { func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence, error) {
vote2 := EvidenceInfo{} vote2 := EvidenceInfo{}
err := json.Unmarshal(data, &vote2) err := json.Unmarshal(data, &vote2)
...@@ -268,7 +272,6 @@ func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence, ...@@ -268,7 +272,6 @@ func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence,
} }
//-------------------------evidence pool----------------------------
// EvidencePool maintains a pool of valid evidence // EvidencePool maintains a pool of valid evidence
// in an EvidenceStore. // in an EvidenceStore.
type EvidencePool struct { type EvidencePool struct {
...@@ -285,6 +288,7 @@ type EvidencePool struct { ...@@ -285,6 +288,7 @@ type EvidencePool struct {
evidenceChan chan ttypes.Evidence evidenceChan chan ttypes.Evidence
} }
// NewEvidencePool method
func NewEvidencePool(stateDB *CSStateDB, state State, evidenceStore *EvidenceStore) *EvidencePool { func NewEvidencePool(stateDB *CSStateDB, state State, evidenceStore *EvidenceStore) *EvidencePool {
evpool := &EvidencePool{ evpool := &EvidencePool{
stateDB: stateDB, stateDB: stateDB,
......
...@@ -22,14 +22,15 @@ import ( ...@@ -22,14 +22,15 @@ import (
) )
const ( const (
numBufferedConnections = 10 numBufferedConnections = 10
MaxNumPeers = 50 maxNumPeers = 50
tryListenSeconds = 5 tryListenSeconds = 5
HandshakeTimeout = 20 // * time.Second, handshakeTimeout = 20 // * time.Second,
maxSendQueueSize = 1024 maxSendQueueSize = 1024
defaultSendTimeout = 60 * time.Second defaultSendTimeout = 60 * time.Second
//MaxMsgPacketPayloadSize define
MaxMsgPacketPayloadSize = 10 * 1024 * 1024 MaxMsgPacketPayloadSize = 10 * 1024 * 1024
DefaultDialTimeout = 3 * time.Second defaultDialTimeout = 3 * time.Second
dialRandomizerIntervalMilliseconds = 3000 dialRandomizerIntervalMilliseconds = 3000
// repeatedly try to reconnect for a few minutes // repeatedly try to reconnect for a few minutes
// ie. 5 * 20 = 100s // ie. 5 * 20 = 100s
...@@ -47,6 +48,7 @@ const ( ...@@ -47,6 +48,7 @@ const (
broadcastEvidenceIntervalS = 60 // broadcast uncommitted evidence this often broadcastEvidenceIntervalS = 60 // broadcast uncommitted evidence this often
) )
// Parallel method
func Parallel(tasks ...func()) { func Parallel(tasks ...func()) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(len(tasks)) wg.Add(len(tasks))
...@@ -59,23 +61,27 @@ func Parallel(tasks ...func()) { ...@@ -59,23 +61,27 @@ func Parallel(tasks ...func()) {
wg.Wait() wg.Wait()
} }
// GenAddressByPubKey method
func GenAddressByPubKey(pubkey crypto.PubKey) []byte { func GenAddressByPubKey(pubkey crypto.PubKey) []byte {
//must add 3 bytes ahead to make compatibly //must add 3 bytes ahead to make compatibly
typeAddr := append([]byte{byte(0x01), byte(0x01), byte(0x20)}, pubkey.Bytes()...) typeAddr := append([]byte{byte(0x01), byte(0x01), byte(0x20)}, pubkey.Bytes()...)
return crypto.Ripemd160(typeAddr) return crypto.Ripemd160(typeAddr)
} }
// IP2IPPort struct
type IP2IPPort struct { type IP2IPPort struct {
mutex sync.RWMutex mutex sync.RWMutex
mapList map[string]string mapList map[string]string
} }
// NewMutexMap method
func NewMutexMap() *IP2IPPort { func NewMutexMap() *IP2IPPort {
return &IP2IPPort{ return &IP2IPPort{
mapList: make(map[string]string), mapList: make(map[string]string),
} }
} }
// Has method
func (ipp *IP2IPPort) Has(ip string) bool { func (ipp *IP2IPPort) Has(ip string) bool {
ipp.mutex.RLock() ipp.mutex.RLock()
defer ipp.mutex.RUnlock() defer ipp.mutex.RUnlock()
...@@ -83,18 +89,21 @@ func (ipp *IP2IPPort) Has(ip string) bool { ...@@ -83,18 +89,21 @@ func (ipp *IP2IPPort) Has(ip string) bool {
return ok return ok
} }
// Set method
func (ipp *IP2IPPort) Set(ip string, ipport string) { func (ipp *IP2IPPort) Set(ip string, ipport string) {
ipp.mutex.Lock() ipp.mutex.Lock()
defer ipp.mutex.Unlock() defer ipp.mutex.Unlock()
ipp.mapList[ip] = ipport ipp.mapList[ip] = ipport
} }
// Delete method
func (ipp *IP2IPPort) Delete(ip string) { func (ipp *IP2IPPort) Delete(ip string) {
ipp.mutex.Lock() ipp.mutex.Lock()
defer ipp.mutex.Unlock() defer ipp.mutex.Unlock()
delete(ipp.mapList, ip) delete(ipp.mapList, ip)
} }
// NodeInfo struct
type NodeInfo struct { type NodeInfo struct {
ID ID `json:"id"` ID ID `json:"id"`
Network string `json:"network"` Network string `json:"network"`
...@@ -102,6 +111,7 @@ type NodeInfo struct { ...@@ -102,6 +111,7 @@ type NodeInfo struct {
IP string `json:"ip,omitempty"` IP string `json:"ip,omitempty"`
} }
// Node struct
type Node struct { type Node struct {
listener net.Listener listener net.Listener
connections chan net.Conn connections chan net.Conn
...@@ -129,6 +139,7 @@ type Node struct { ...@@ -129,6 +139,7 @@ type Node struct {
quit chan struct{} quit chan struct{}
} }
// NewNode method
func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivKey, network string, version string, state *ConsensusState, evpool *EvidencePool) *Node { func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivKey, network string, version string, state *ConsensusState, evpool *EvidencePool) *Node {
address := GenAddressByPubKey(privKey.PubKey()) address := GenAddressByPubKey(privKey.PubKey())
...@@ -163,6 +174,7 @@ func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivK ...@@ -163,6 +174,7 @@ func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivK
return node return node
} }
// Start node
func (node *Node) Start() { func (node *Node) Start() {
if atomic.CompareAndSwapUint32(&node.started, 0, 1) { if atomic.CompareAndSwapUint32(&node.started, 0, 1) {
// Create listener // Create listener
...@@ -211,6 +223,7 @@ func (node *Node) Start() { ...@@ -211,6 +223,7 @@ func (node *Node) Start() {
} }
} }
// DialPeerWithAddress ...
func (node *Node) DialPeerWithAddress(addr string) error { func (node *Node) DialPeerWithAddress(addr string) error {
ip, _ := splitHostPort(addr) ip, _ := splitHostPort(addr)
node.dialing.Set(ip, addr) node.dialing.Set(ip, addr)
...@@ -234,6 +247,7 @@ func (node *Node) addOutboundPeerWithConfig(addr string) error { ...@@ -234,6 +247,7 @@ func (node *Node) addOutboundPeerWithConfig(addr string) error {
return nil return nil
} }
// Stop ...
func (node *Node) Stop() { func (node *Node) Stop() {
atomic.CompareAndSwapUint32(&node.stopped, 0, 1) atomic.CompareAndSwapUint32(&node.stopped, 0, 1)
node.listener.Close() node.listener.Close()
...@@ -245,10 +259,11 @@ func (node *Node) Stop() { ...@@ -245,10 +259,11 @@ func (node *Node) Stop() {
peer.Stop() peer.Stop()
node.peerSet.Remove(peer) node.peerSet.Remove(peer)
} }
// Stop reactors //stop consensus
tendermintlog.Debug("Switch: Stopping reactors") node.state.Stop()
} }
// IsRunning ...
func (node *Node) IsRunning() bool { func (node *Node) IsRunning() bool {
return atomic.LoadUint32(&node.started) == 1 && atomic.LoadUint32(&node.stopped) == 0 return atomic.LoadUint32(&node.started) == 1 && atomic.LoadUint32(&node.stopped) == 0
} }
...@@ -277,8 +292,10 @@ func (node *Node) listenRoutine() { ...@@ -277,8 +292,10 @@ func (node *Node) listenRoutine() {
} }
} }
// StartConsensusRoutine if peers reached the threshold start consensus routine
func (node *Node) StartConsensusRoutine() { func (node *Node) StartConsensusRoutine() {
for { for {
//TODO:the peer count need be optimized
if node.peerSet.Size() >= 0 { if node.peerSet.Size() >= 0 {
node.state.Start() node.state.Start()
break break
...@@ -347,6 +364,7 @@ func (node *Node) evidenceBroadcastRoutine() { ...@@ -347,6 +364,7 @@ func (node *Node) evidenceBroadcastRoutine() {
} }
} }
// BroadcastRoutine receive to broadcast
func (node *Node) BroadcastRoutine() { func (node *Node) BroadcastRoutine() {
for { for {
msg, ok := <-node.broadcastChannel msg, ok := <-node.broadcastChannel
...@@ -359,7 +377,7 @@ func (node *Node) BroadcastRoutine() { ...@@ -359,7 +377,7 @@ func (node *Node) BroadcastRoutine() {
} }
func (node *Node) connectComming(inConn net.Conn) { func (node *Node) connectComming(inConn net.Conn) {
maxPeers := MaxNumPeers maxPeers := maxNumPeers
if maxPeers <= node.peerSet.Size() { if maxPeers <= node.peerSet.Size() {
tendermintlog.Debug("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", node.peerSet.Size(), "max", maxPeers) tendermintlog.Debug("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", node.peerSet.Size(), "max", maxPeers)
return return
...@@ -378,6 +396,7 @@ func (node *Node) stopAndRemovePeer(peer Peer, reason interface{}) { ...@@ -378,6 +396,7 @@ func (node *Node) stopAndRemovePeer(peer Peer, reason interface{}) {
peer.Stop() peer.Stop()
} }
// StopPeerForError called if error occured
func (node *Node) StopPeerForError(peer Peer, reason interface{}) { func (node *Node) StopPeerForError(peer Peer, reason interface{}) {
tendermintlog.Error("Stopping peer for error", "peer", peer, "err", reason) tendermintlog.Error("Stopping peer for error", "peer", peer, "err", reason)
addr, err := peer.RemoteAddr() addr, err := peer.RemoteAddr()
...@@ -408,7 +427,7 @@ func (node *Node) addInboundPeer(conn net.Conn) error { ...@@ -408,7 +427,7 @@ func (node *Node) addInboundPeer(conn net.Conn) error {
// peer to the switch and to all registered reactors. // peer to the switch and to all registered reactors.
// NOTE: This performs a blocking handshake before the peer is added. // NOTE: This performs a blocking handshake before the peer is added.
// NOTE: If error is returned, caller is responsible for calling peer.CloseConn() // NOTE: If error is returned, caller is responsible for calling peer.CloseConn()
func (node *Node) addPeer(pc peerConn) error { func (node *Node) addPeer(pc *peerConn) error {
addr := pc.conn.RemoteAddr() addr := pc.conn.RemoteAddr()
if err := node.FilterConnByAddr(addr); err != nil { if err := node.FilterConnByAddr(addr); err != nil {
return err return err
...@@ -422,7 +441,7 @@ func (node *Node) addPeer(pc peerConn) error { ...@@ -422,7 +441,7 @@ func (node *Node) addPeer(pc peerConn) error {
Version: node.Version, Version: node.Version,
} }
// Exchange NodeInfo on the conn // Exchange NodeInfo on the conn
peerNodeInfo, err := pc.HandshakeTimeout(nodeinfo, HandshakeTimeout*time.Second) peerNodeInfo, err := pc.HandshakeTimeout(nodeinfo, handshakeTimeout*time.Second)
if err != nil { if err != nil {
return err return err
} }
...@@ -472,7 +491,7 @@ func (node *Node) addPeer(pc peerConn) error { ...@@ -472,7 +491,7 @@ func (node *Node) addPeer(pc peerConn) error {
// All good. Start peer // All good. Start peer
if node.IsRunning() { if node.IsRunning() {
pc.SetTransferChannel(node.state.peerMsgQueue) pc.SetTransferChannel(node.state.peerMsgQueue)
if err = node.startInitPeer(&pc); err != nil { if err = node.startInitPeer(pc); err != nil {
return err return err
} }
} }
...@@ -480,7 +499,7 @@ func (node *Node) addPeer(pc peerConn) error { ...@@ -480,7 +499,7 @@ func (node *Node) addPeer(pc peerConn) error {
// Add the peer to .peers. // Add the peer to .peers.
// We start it first so that a peer in the list is safe to Stop. // We start it first so that a peer in the list is safe to Stop.
// It should not err since we already checked peers.Has(). // It should not err since we already checked peers.Has().
if err := node.peerSet.Add(&pc); err != nil { if err := node.peerSet.Add(pc); err != nil {
return err return err
} }
//node.metrics.Peers.Add(float64(1)) //node.metrics.Peers.Add(float64(1))
...@@ -489,6 +508,7 @@ func (node *Node) addPeer(pc peerConn) error { ...@@ -489,6 +508,7 @@ func (node *Node) addPeer(pc peerConn) error {
return nil return nil
} }
// Broadcast to peers in set
func (node *Node) Broadcast(msg MsgInfo) chan bool { func (node *Node) Broadcast(msg MsgInfo) chan bool {
successChan := make(chan bool, len(node.peerSet.List())) successChan := make(chan bool, len(node.peerSet.List()))
tendermintlog.Debug("Broadcast", "msgtype", msg.TypeID) tendermintlog.Debug("Broadcast", "msgtype", msg.TypeID)
...@@ -519,13 +539,12 @@ func (node *Node) startInitPeer(peer *peerConn) error { ...@@ -519,13 +539,12 @@ func (node *Node) startInitPeer(peer *peerConn) error {
return nil return nil
} }
// FilterConnByAddr TODO:can make fileter by addr
func (node *Node) FilterConnByAddr(addr net.Addr) error { func (node *Node) FilterConnByAddr(addr net.Addr) error {
//if node.filterConnByAddr != nil {
// return node.filterConnByAddr(addr)
//}
return nil return nil
} }
// CompatibleWith one node by nodeInfo
func (node *Node) CompatibleWith(other NodeInfo) error { func (node *Node) CompatibleWith(other NodeInfo) error {
iMajor, iMinor, _, iErr := splitVersion(node.Version) iMajor, iMinor, _, iErr := splitVersion(node.Version)
oMajor, oMinor, _, oErr := splitVersion(other.Version) oMajor, oMinor, _, oErr := splitVersion(other.Version)
...@@ -679,25 +698,25 @@ func splitHostPort(addr string) (host string, port int) { ...@@ -679,25 +698,25 @@ func splitHostPort(addr string) (host string, port int) {
} }
func dial(addr string) (net.Conn, error) { func dial(addr string) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", addr, DefaultDialTimeout) conn, err := net.DialTimeout("tcp", addr, defaultDialTimeout)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return conn, nil return conn, nil
} }
func newOutboundPeerConn(addr string, ourNodePrivKey crypto.PrivKey, onPeerError func(Peer, interface{}), state *ConsensusState, evpool *EvidencePool) (peerConn, error) { func newOutboundPeerConn(addr string, ourNodePrivKey crypto.PrivKey, onPeerError func(Peer, interface{}), state *ConsensusState, evpool *EvidencePool) (*peerConn, error) {
conn, err := dial(addr) conn, err := dial(addr)
if err != nil { if err != nil {
return peerConn{}, fmt.Errorf("Error creating peer:%v", err) return &peerConn{}, fmt.Errorf("Error creating peer:%v", err)
} }
pc, err := newPeerConn(conn, true, true, ourNodePrivKey, onPeerError, state, evpool) pc, err := newPeerConn(conn, true, true, ourNodePrivKey, onPeerError, state, evpool)
if err != nil { if err != nil {
if cerr := conn.Close(); cerr != nil { if cerr := conn.Close(); cerr != nil {
return peerConn{}, fmt.Errorf("newPeerConn failed:%v, connection close failed:%v", err, cerr) return &peerConn{}, fmt.Errorf("newPeerConn failed:%v, connection close failed:%v", err, cerr)
} }
return peerConn{}, err return &peerConn{}, err
} }
return pc, nil return pc, nil
...@@ -709,7 +728,7 @@ func newInboundPeerConn( ...@@ -709,7 +728,7 @@ func newInboundPeerConn(
onPeerError func(Peer, interface{}), onPeerError func(Peer, interface{}),
state *ConsensusState, state *ConsensusState,
evpool *EvidencePool, evpool *EvidencePool,
) (peerConn, error) { ) (*peerConn, error) {
// TODO: issue PoW challenge // TODO: issue PoW challenge
...@@ -723,11 +742,11 @@ func newPeerConn( ...@@ -723,11 +742,11 @@ func newPeerConn(
onPeerError func(Peer, interface{}), onPeerError func(Peer, interface{}),
state *ConsensusState, state *ConsensusState,
evpool *EvidencePool, evpool *EvidencePool,
) (pc peerConn, err error) { ) (pc *peerConn, err error) {
conn := rawConn conn := rawConn
// Set deadline for secret handshake // Set deadline for secret handshake
dl := time.Now().Add(HandshakeTimeout * time.Second) dl := time.Now().Add(handshakeTimeout * time.Second)
if err := conn.SetDeadline(dl); err != nil { if err := conn.SetDeadline(dl); err != nil {
return pc, fmt.Errorf("Error setting deadline while encrypting connection:%v", err) return pc, fmt.Errorf("Error setting deadline while encrypting connection:%v", err)
} }
...@@ -739,7 +758,7 @@ func newPeerConn( ...@@ -739,7 +758,7 @@ func newPeerConn(
} }
// Only the information we already have // Only the information we already have
return peerConn{ return &peerConn{
outbound: outbound, outbound: outbound,
persistent: persistent, persistent: persistent,
conn: conn, conn: conn,
......
...@@ -33,6 +33,7 @@ type msgPacket struct { ...@@ -33,6 +33,7 @@ type msgPacket struct {
Bytes []byte Bytes []byte
} }
// MsgInfo struct
type MsgInfo struct { type MsgInfo struct {
TypeID byte TypeID byte
Msg proto.Message Msg proto.Message
...@@ -40,6 +41,7 @@ type MsgInfo struct { ...@@ -40,6 +41,7 @@ type MsgInfo struct {
PeerIP string PeerIP string
} }
// Peer interface
type Peer interface { type Peer interface {
ID() ID ID() ID
RemoteIP() (net.IP, error) // remote IP of the connection RemoteIP() (net.IP, error) // remote IP of the connection
...@@ -57,6 +59,7 @@ type Peer interface { ...@@ -57,6 +59,7 @@ type Peer interface {
//Get(string) interface{} //Get(string) interface{}
} }
// PeerConnState struct
type PeerConnState struct { type PeerConnState struct {
mtx sync.Mutex mtx sync.Mutex
ip net.IP ip net.IP
...@@ -98,6 +101,7 @@ type peerConn struct { ...@@ -98,6 +101,7 @@ type peerConn struct {
heartbeatQueue chan proto.Message heartbeatQueue chan proto.Message
} }
// PeerSet struct
type PeerSet struct { type PeerSet struct {
mtx sync.Mutex mtx sync.Mutex
lookup map[ID]*peerSetItem lookup map[ID]*peerSetItem
...@@ -109,6 +113,7 @@ type peerSetItem struct { ...@@ -109,6 +113,7 @@ type peerSetItem struct {
index int index int
} }
// NewPeerSet method
func NewPeerSet() *PeerSet { func NewPeerSet() *PeerSet {
return &PeerSet{ return &PeerSet{
lookup: make(map[ID]*peerSetItem), lookup: make(map[ID]*peerSetItem),
...@@ -164,6 +169,7 @@ func (ps *PeerSet) hasIP(peerIP net.IP) bool { ...@@ -164,6 +169,7 @@ func (ps *PeerSet) hasIP(peerIP net.IP) bool {
return false return false
} }
// Size of list
func (ps *PeerSet) Size() int { func (ps *PeerSet) Size() int {
ps.mtx.Lock() ps.mtx.Lock()
defer ps.mtx.Unlock() defer ps.mtx.Unlock()
...@@ -277,36 +283,41 @@ func (pc *peerConn) HandshakeTimeout( ...@@ -277,36 +283,41 @@ func (pc *peerConn) HandshakeTimeout(
func() { func() {
info, err1 := json.Marshal(ourNodeInfo) info, err1 := json.Marshal(ourNodeInfo)
if err1 != nil { if err1 != nil {
tendermintlog.Error("Peer handshake peerNodeInfo failed", "err", err1) tendermintlog.Error("Peer handshake Marshal ourNodeInfo failed", "err", err1)
return
}
frame := make([]byte, 4)
binary.BigEndian.PutUint32(frame, uint32(len(info)))
_, err1 = pc.conn.Write(frame)
if err1 != nil {
tendermintlog.Error("Peer handshake write info size failed", "err", err1)
return
}
_, err1 = pc.conn.Write(info[:])
if err1 != nil {
tendermintlog.Error("Peer handshake write info failed", "err", err1)
return return
} else {
frame := make([]byte, 4)
binary.BigEndian.PutUint32(frame, uint32(len(info)))
_, err1 = pc.conn.Write(frame)
_, err1 = pc.conn.Write(info[:])
} }
//var n int
//wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
}, },
func() { func() {
readBuffer := make([]byte, 4) readBuffer := make([]byte, 4)
_, err2 = io.ReadFull(pc.conn, readBuffer[:]) _, err2 = io.ReadFull(pc.conn, readBuffer[:])
if err2 != nil { if err2 != nil {
tendermintlog.Error("Peer handshake read info size failed", "err", err1)
return return
} }
len := binary.BigEndian.Uint32(readBuffer) len := binary.BigEndian.Uint32(readBuffer)
readBuffer = make([]byte, len) readBuffer = make([]byte, len)
_, err2 = io.ReadFull(pc.conn, readBuffer[:]) _, err2 = io.ReadFull(pc.conn, readBuffer[:])
if err2 != nil { if err2 != nil {
tendermintlog.Error("Peer handshake read info failed", "err", err1)
return return
} }
err2 = json.Unmarshal(readBuffer, &peerNodeInfo) err2 = json.Unmarshal(readBuffer, &peerNodeInfo)
if err2 != nil { if err2 != nil {
tendermintlog.Error("Peer handshake Unmarshal failed", "err", err1)
return return
} }
//var n int
//wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
tendermintlog.Info("Peer handshake", "peerNodeInfo", peerNodeInfo) tendermintlog.Info("Peer handshake", "peerNodeInfo", peerNodeInfo)
}, },
) )
...@@ -537,7 +548,7 @@ FOR_LOOP: ...@@ -537,7 +548,7 @@ FOR_LOOP:
tendermintlog.Debug("Receiving vote", "vote-height", vote.Height, "peerip", pc.ip.String()) tendermintlog.Debug("Receiving vote", "vote-height", vote.Height, "peerip", pc.ip.String())
pc.state.SetHasVote(vote) pc.state.SetHasVote(vote)
} else if pkt.TypeID == ttypes.ProposalBlockID { } else if pkt.TypeID == ttypes.ProposalBlockID {
block := &ttypes.TendermintBlock{realMsg.(*tmtypes.TendermintBlock)} block := &ttypes.TendermintBlock{TendermintBlock: realMsg.(*tmtypes.TendermintBlock)}
tendermintlog.Debug("Receiving proposal block", "block-height", block.Header.Height, "peerip", pc.ip.String()) tendermintlog.Debug("Receiving proposal block", "block-height", block.Header.Height, "peerip", pc.ip.String())
pc.state.SetHasProposalBlock(block) pc.state.SetHasProposalBlock(block)
} }
...@@ -956,6 +967,7 @@ OUTER_LOOP: ...@@ -956,6 +967,7 @@ OUTER_LOOP:
} }
} }
// StackError struct
type StackError struct { type StackError struct {
Err interface{} Err interface{}
Stack []byte Stack []byte
...@@ -969,7 +981,6 @@ func (se StackError) Error() string { ...@@ -969,7 +981,6 @@ func (se StackError) Error() string {
return se.String() return se.String()
} }
//-----------------------------------------------------------------
// GetRoundState returns an atomic snapshot of the PeerRoundState. // GetRoundState returns an atomic snapshot of the PeerRoundState.
// There's no point in mutating it since it won't change PeerState. // There's no point in mutating it since it won't change PeerState.
func (ps *PeerConnState) GetRoundState() *ttypes.PeerRoundState { func (ps *PeerConnState) GetRoundState() *ttypes.PeerRoundState {
...@@ -1034,7 +1045,7 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype ...@@ -1034,7 +1045,7 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype
return nil, false return nil, false
} }
height, round, type_, size := votes.Height(), votes.Round(), votes.Type(), votes.Size() height, round, voteType, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
// Lazily set data using 'votes'. // Lazily set data using 'votes'.
if votes.IsCommit() { if votes.IsCommit() {
...@@ -1042,28 +1053,28 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype ...@@ -1042,28 +1053,28 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype
} }
ps.ensureVoteBitArrays(height, size) ps.ensureVoteBitArrays(height, size)
psVotes := ps.getVoteBitArray(height, round, type_) psVotes := ps.getVoteBitArray(height, round, voteType)
if psVotes == nil { if psVotes == nil {
return nil, false // Not something worth sending return nil, false // Not something worth sending
} }
if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok { if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
tendermintlog.Debug("PickVoteToSend", "height", height, "index", index, "type", type_, "selfVotes", votes.BitArray().String(), tendermintlog.Debug("PickVoteToSend", "height", height, "index", index, "type", voteType, "selfVotes", votes.BitArray().String(),
"peerVotes", psVotes.String(), "peerip", ps.ip.String()) "peerVotes", psVotes.String(), "peerip", ps.ip.String())
ps.setHasVote(height, round, type_, index) ps.setHasVote(height, round, voteType, index)
return votes.GetByIndex(index), true return votes.GetByIndex(index), true
} }
return nil, false return nil, false
} }
func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *ttypes.BitArray { func (ps *PeerConnState) getVoteBitArray(height int64, round int, voteType byte) *ttypes.BitArray {
if !ttypes.IsVoteTypeValid(type_) { if !ttypes.IsVoteTypeValid(voteType) {
return nil return nil
} }
if ps.Height == height { if ps.Height == height {
if ps.Round == round { if ps.Round == round {
switch type_ { switch voteType {
case ttypes.VoteTypePrevote: case ttypes.VoteTypePrevote:
return ps.Prevotes return ps.Prevotes
case ttypes.VoteTypePrecommit: case ttypes.VoteTypePrecommit:
...@@ -1071,7 +1082,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t ...@@ -1071,7 +1082,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
} }
} }
if ps.CatchupCommitRound == round { if ps.CatchupCommitRound == round {
switch type_ { switch voteType {
case ttypes.VoteTypePrevote: case ttypes.VoteTypePrevote:
return nil return nil
case ttypes.VoteTypePrecommit: case ttypes.VoteTypePrecommit:
...@@ -1079,7 +1090,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t ...@@ -1079,7 +1090,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
} }
} }
if ps.ProposalPOLRound == round { if ps.ProposalPOLRound == round {
switch type_ { switch voteType {
case ttypes.VoteTypePrevote: case ttypes.VoteTypePrevote:
return ps.ProposalPOL return ps.ProposalPOL
case ttypes.VoteTypePrecommit: case ttypes.VoteTypePrecommit:
...@@ -1090,7 +1101,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t ...@@ -1090,7 +1101,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
} }
if ps.Height == height+1 { if ps.Height == height+1 {
if ps.LastCommitRound == round { if ps.LastCommitRound == round {
switch type_ { switch voteType {
case ttypes.VoteTypePrevote: case ttypes.VoteTypePrevote:
return nil return nil
case ttypes.VoteTypePrecommit: case ttypes.VoteTypePrecommit:
...@@ -1127,7 +1138,7 @@ func (ps *PeerConnState) ensureCatchupCommitRound(height int64, round int, numVa ...@@ -1127,7 +1138,7 @@ func (ps *PeerConnState) ensureCatchupCommitRound(height int64, round int, numVa
} }
} }
// EnsureVoteVitArrays ensures the bit-arrays have been allocated for tracking // EnsureVoteBitArrays ensures the bit-arrays have been allocated for tracking
// what votes this peer has received. // what votes this peer has received.
// NOTE: It's important to make sure that numValidators actually matches // NOTE: It's important to make sure that numValidators actually matches
// what the node sees as the number of validators for height. // what the node sees as the number of validators for height.
...@@ -1166,14 +1177,14 @@ func (ps *PeerConnState) SetHasVote(vote *ttypes.Vote) { ...@@ -1166,14 +1177,14 @@ func (ps *PeerConnState) SetHasVote(vote *ttypes.Vote) {
ps.setHasVote(vote.Height, int(vote.Round), byte(vote.Type), int(vote.ValidatorIndex)) ps.setHasVote(vote.Height, int(vote.Round), byte(vote.Type), int(vote.ValidatorIndex))
} }
func (ps *PeerConnState) setHasVote(height int64, round int, type_ byte, index int) { func (ps *PeerConnState) setHasVote(height int64, round int, voteType byte, index int) {
// NOTE: some may be nil BitArrays -> no side effects. // NOTE: some may be nil BitArrays -> no side effects.
psVotes := ps.getVoteBitArray(height, round, type_) psVotes := ps.getVoteBitArray(height, round, voteType)
tendermintlog.Debug("setHasVote before", "height", height, "psVotes", psVotes.String(), "peerip", ps.ip.String()) tendermintlog.Debug("setHasVote before", "height", height, "psVotes", psVotes.String(), "peerip", ps.ip.String())
if psVotes != nil { if psVotes != nil {
psVotes.SetIndex(index, true) psVotes.SetIndex(index, true)
} }
tendermintlog.Debug("setHasVote after", "height", height, "index", index, "type", type_, "peerVotes", psVotes.String(), "peerip", ps.ip.String()) tendermintlog.Debug("setHasVote after", "height", height, "index", index, "type", voteType, "peerVotes", psVotes.String(), "peerip", ps.ip.String())
} }
// ApplyNewRoundStepMessage updates the peer state for the new round. // ApplyNewRoundStepMessage updates the peer state for the new round.
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Uses nacl's secret_box to encrypt a net.Conn. // Package tendermint Uses nacl's secret_box to encrypt a net.Conn.
// It is (meant to be) an implementation of the STS protocol. // It is (meant to be) an implementation of the STS protocol.
// Note we do not (yet) assume that a remote peer's pubkey // Note we do not (yet) assume that a remote peer's pubkey
// is known ahead of time, and thus we are technically // is known ahead of time, and thus we are technically
...@@ -36,7 +36,7 @@ const ( ...@@ -36,7 +36,7 @@ const (
authSigMsgSize = (32) + (64) authSigMsgSize = (32) + (64)
) // fixed size (length prefixed) byte arrays ) // fixed size (length prefixed) byte arrays
// Implements net.Conn // SecretConnection Implements net.Conn
type SecretConnection struct { type SecretConnection struct {
conn io.ReadWriteCloser conn io.ReadWriteCloser
recvBuffer []byte recvBuffer []byte
...@@ -46,7 +46,7 @@ type SecretConnection struct { ...@@ -46,7 +46,7 @@ type SecretConnection struct {
shrSecret *[32]byte // shared secret shrSecret *[32]byte // shared secret
} }
// Performs handshake and returns a new authenticated SecretConnection. // MakeSecretConnection Performs handshake and returns a new authenticated SecretConnection.
// Returns nil if error in handshake. // Returns nil if error in handshake.
// Caller should call conn.Close() // Caller should call conn.Close()
// See docs/sts-final.pdf for more information. // See docs/sts-final.pdf for more information.
...@@ -108,7 +108,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (* ...@@ -108,7 +108,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*
return sc, nil return sc, nil
} }
// Returns authenticated remote pubkey // RemotePubKey Returns authenticated remote pubkey
func (sc *SecretConnection) RemotePubKey() crypto.PubKey { func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
return sc.remPubKey return sc.remPubKey
} }
...@@ -140,9 +140,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) { ...@@ -140,9 +140,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) {
_, err := sc.conn.Write(sealedFrame) _, err := sc.conn.Write(sealedFrame)
if err != nil { if err != nil {
return n, err return n, err
} else {
n += len(chunk)
} }
n += len(chunk)
} }
return return
} }
...@@ -150,8 +149,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) { ...@@ -150,8 +149,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) {
// CONTRACT: data smaller than dataMaxSize is read atomically. // CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Read(data []byte) (n int, err error) { func (sc *SecretConnection) Read(data []byte) (n int, err error) {
if 0 < len(sc.recvBuffer) { if 0 < len(sc.recvBuffer) {
n_ := copy(data, sc.recvBuffer) count := copy(data, sc.recvBuffer)
sc.recvBuffer = sc.recvBuffer[n_:] sc.recvBuffer = sc.recvBuffer[count:]
return return
} }
...@@ -182,14 +181,24 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { ...@@ -182,14 +181,24 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) {
return return
} }
// Implements net.Conn // Close Implements net.Conn
func (sc *SecretConnection) Close() error { return sc.conn.Close() } func (sc *SecretConnection) Close() error { return sc.conn.Close() }
func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } // LocalAddr ...
func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
// RemoteAddr ...
func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
// SetDeadline ...
func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) } func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
// SetReadDeadline ...
func (sc *SecretConnection) SetReadDeadline(t time.Time) error { func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetReadDeadline(t) return sc.conn.(net.Conn).SetReadDeadline(t)
} }
// SetWriteDeadline ...
func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetWriteDeadline(t) return sc.conn.(net.Conn).SetWriteDeadline(t)
} }
...@@ -343,7 +352,7 @@ func incr2Nonce(nonce *[24]byte) { ...@@ -343,7 +352,7 @@ func incr2Nonce(nonce *[24]byte) {
// increment nonce big-endian by 1 with wraparound. // increment nonce big-endian by 1 with wraparound.
func incrNonce(nonce *[24]byte) { func incrNonce(nonce *[24]byte) {
for i := 23; 0 <= i; i-- { for i := 23; 0 <= i; i-- {
nonce[i] += 1 nonce[i]++
if nonce[i] != 0 { if nonce[i] != 0 {
return return
} }
......
...@@ -174,7 +174,7 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) { ...@@ -174,7 +174,7 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) {
for i, val := range genDoc.Validators { for i, val := range genDoc.Validators {
pubKey, err := ttypes.PubKeyFromString(val.PubKey.Data) pubKey, err := ttypes.PubKeyFromString(val.PubKey.Data)
if err != nil { if err != nil {
return State{}, fmt.Errorf("Error validate[i] in genesis file: %v", i, err) return State{}, fmt.Errorf("Error validate[%v] in genesis file: %v", i, err)
} }
// Make validator // Make validator
...@@ -204,14 +204,15 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) { ...@@ -204,14 +204,15 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) {
}, nil }, nil
} }
//-------------------stateDB------------------------ // CSStateDB just for EvidencePool and BlockExecutor
type CSStateDB struct { type CSStateDB struct {
client *TendermintClient client *Client
state State state State
mtx sync.Mutex mtx sync.Mutex
} }
func NewStateDB(client *TendermintClient, state State) *CSStateDB { // NewStateDB make a new one
func NewStateDB(client *Client, state State) *CSStateDB {
r = rand.New(rand.NewSource(time.Now().UnixNano())) r = rand.New(rand.NewSource(time.Now().UnixNano()))
return &CSStateDB{ return &CSStateDB{
client: client, client: client,
...@@ -219,6 +220,7 @@ func NewStateDB(client *TendermintClient, state State) *CSStateDB { ...@@ -219,6 +220,7 @@ func NewStateDB(client *TendermintClient, state State) *CSStateDB {
} }
} }
// LoadState convert external state to internal state
func LoadState(state *tmtypes.State) State { func LoadState(state *tmtypes.State) State {
stateTmp := State{ stateTmp := State{
ChainID: state.GetChainID(), ChainID: state.GetChainID(),
...@@ -286,18 +288,21 @@ func LoadState(state *tmtypes.State) State { ...@@ -286,18 +288,21 @@ func LoadState(state *tmtypes.State) State {
return stateTmp return stateTmp
} }
// SaveState to state cache
func (csdb *CSStateDB) SaveState(state State) { func (csdb *CSStateDB) SaveState(state State) {
csdb.mtx.Lock() csdb.mtx.Lock()
defer csdb.mtx.Unlock() defer csdb.mtx.Unlock()
csdb.state = state.Copy() csdb.state = state.Copy()
} }
// LoadState from state cache
func (csdb *CSStateDB) LoadState() State { func (csdb *CSStateDB) LoadState() State {
csdb.mtx.Lock() csdb.mtx.Lock()
defer csdb.mtx.Unlock() defer csdb.mtx.Unlock()
return csdb.state return csdb.state
} }
// LoadValidators by height
func (csdb *CSStateDB) LoadValidators(height int64) (*ttypes.ValidatorSet, error) { func (csdb *CSStateDB) LoadValidators(height int64) (*ttypes.ValidatorSet, error) {
if height == 0 { if height == 0 {
return nil, nil return nil, nil
...@@ -363,6 +368,7 @@ func saveProposer(dest *tmtypes.Validator, source *ttypes.Validator) { ...@@ -363,6 +368,7 @@ func saveProposer(dest *tmtypes.Validator, source *ttypes.Validator) {
} }
} }
// SaveState convert internal state to external state
func SaveState(state State) *tmtypes.State { func SaveState(state State) *tmtypes.State {
newState := tmtypes.State{ newState := tmtypes.State{
ChainID: state.ChainID, ChainID: state.ChainID,
...@@ -405,6 +411,7 @@ func getprivkey(key string) crypto.PrivKey { ...@@ -405,6 +411,7 @@ func getprivkey(key string) crypto.PrivKey {
return priv return priv
} }
// LoadValidators convert all external validators to internal validators
func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) { func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) {
for i, item := range source { for i, item := range source {
if item.GetAddress() == nil || len(item.GetAddress()) == 0 { if item.GetAddress() == nil || len(item.GetAddress()) == 0 {
...@@ -427,6 +434,7 @@ func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) { ...@@ -427,6 +434,7 @@ func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) {
} }
} }
// LoadProposer convert external proposer to internal proposer
func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) { func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) {
if source.GetAddress() == nil || len(source.GetAddress()) == 0 { if source.GetAddress() == nil || len(source.GetAddress()) == 0 {
tendermintlog.Warn("LoadProposer get address is nil or empty") tendermintlog.Warn("LoadProposer get address is nil or empty")
...@@ -449,6 +457,7 @@ func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) { ...@@ -449,6 +457,7 @@ func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) {
return des, nil return des, nil
} }
// CreateBlockInfoTx make blockInfo to the first transaction of the block and execer is valnode
func CreateBlockInfoTx(pubkey string, lastCommit *tmtypes.TendermintCommit, seenCommit *tmtypes.TendermintCommit, state *tmtypes.State, proposal *tmtypes.Proposal, block *tmtypes.TendermintBlock) *types.Transaction { func CreateBlockInfoTx(pubkey string, lastCommit *tmtypes.TendermintCommit, seenCommit *tmtypes.TendermintCommit, state *tmtypes.State, proposal *tmtypes.Proposal, block *tmtypes.TendermintBlock) *types.Transaction {
blockNoTxs := *block blockNoTxs := *block
blockNoTxs.Txs = make([]*types.Transaction, 0) blockNoTxs.Txs = make([]*types.Transaction, 0)
......
This diff is collapsed.
...@@ -36,7 +36,7 @@ import ( ...@@ -36,7 +36,7 @@ import (
var ( var (
random *rand.Rand random *rand.Rand
loopCount int = 10 loopCount = 10
conn *grpc.ClientConn conn *grpc.ClientConn
c types.Chain33Client c types.Chain33Client
) )
...@@ -147,7 +147,7 @@ func prepareTxList() *types.Transaction { ...@@ -147,7 +147,7 @@ func prepareTxList() *types.Transaction {
key = generateKey(i, 32) key = generateKey(i, 32)
value = generateValue(i, 180) value = generateValue(i, 180)
nput := &pty.NormAction_Nput{&pty.NormPut{Key: key, Value: []byte(value)}} nput := &pty.NormAction_Nput{Nput: &pty.NormPut{Key: key, Value: []byte(value)}}
action := &pty.NormAction{Value: nput, Ty: pty.NormActionPut} action := &pty.NormAction{Value: nput, Ty: pty.NormActionPut}
tx := &types.Transaction{Execer: []byte("norm"), Payload: types.Encode(action), Fee: fee} tx := &types.Transaction{Execer: []byte("norm"), Payload: types.Encode(action), Fee: fee}
tx.To = address.ExecAddress("norm") tx.To = address.ExecAddress("norm")
......
...@@ -29,7 +29,9 @@ const fee = 1e6 ...@@ -29,7 +29,9 @@ const fee = 1e6
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var r *rand.Rand var r *rand.Rand
var TxHeightOffset int64 = 0
// TxHeightOffset needed
var TxHeightOffset int64
func main() { func main() {
if len(os.Args) == 1 || os.Args[1] == "-h" { if len(os.Args) == 1 || os.Args[1] == "-h" {
...@@ -69,6 +71,7 @@ func main() { ...@@ -69,6 +71,7 @@ func main() {
} }
} }
// LoadHelp ...
func LoadHelp() { func LoadHelp() {
fmt.Println("Available Commands:") fmt.Println("Available Commands:")
fmt.Println("perf [ip, size, num, interval, duration] {offset} : 写数据性能测试") fmt.Println("perf [ip, size, num, interval, duration] {offset} : 写数据性能测试")
...@@ -77,6 +80,7 @@ func LoadHelp() { ...@@ -77,6 +80,7 @@ func LoadHelp() {
fmt.Println("valnode [ip, pubkey, power] : 增加/删除/修改tendermint节点") fmt.Println("valnode [ip, pubkey, power] : 增加/删除/修改tendermint节点")
} }
// Perf ...
func Perf(ip, size, num, interval, duration string) { func Perf(ip, size, num, interval, duration string) {
var numThread int var numThread int
numInt, err := strconv.Atoi(num) numInt, err := strconv.Atoi(num)
...@@ -128,6 +132,7 @@ func Perf(ip, size, num, interval, duration string) { ...@@ -128,6 +132,7 @@ func Perf(ip, size, num, interval, duration string) {
} }
} }
// Put ...
func Put(ip string, size string, privkey string) { func Put(ip string, size string, privkey string) {
sizeInt, err := strconv.Atoi(size) sizeInt, err := strconv.Atoi(size)
if err != nil { if err != nil {
...@@ -164,6 +169,7 @@ func Put(ip string, size string, privkey string) { ...@@ -164,6 +169,7 @@ func Put(ip string, size string, privkey string) {
fmt.Printf("returned JSON: %s\n", string(b)) fmt.Printf("returned JSON: %s\n", string(b))
} }
// Get ...
func Get(ip string, hash string) { func Get(ip string, hash string) {
url := "http://" + ip + ":8801" url := "http://" + ip + ":8801"
fmt.Println("transaction hash:", hash) fmt.Println("transaction hash:", hash)
...@@ -209,8 +215,9 @@ func setTxHeight(ip string) { ...@@ -209,8 +215,9 @@ func setTxHeight(ip string) {
fmt.Println("TxHeightOffset:", TxHeightOffset) fmt.Println("TxHeightOffset:", TxHeightOffset)
} }
// RespMsg ...
type RespMsg struct { type RespMsg struct {
Id int64 `json:"id"` ID int64 `json:"id"`
Result rpctypes.Header `json:"result"` Result rpctypes.Header `json:"result"`
Err string `json:"error"` Err string `json:"error"`
} }
...@@ -245,6 +252,7 @@ func genaddress() (string, crypto.PrivKey) { ...@@ -245,6 +252,7 @@ func genaddress() (string, crypto.PrivKey) {
return addrto.String(), privto return addrto.String(), privto
} }
// RandStringBytes ...
func RandStringBytes(n int) string { func RandStringBytes(n int) string {
b := make([]byte, n) b := make([]byte, n)
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
...@@ -254,6 +262,7 @@ func RandStringBytes(n int) string { ...@@ -254,6 +262,7 @@ func RandStringBytes(n int) string {
return string(b) return string(b)
} }
// ValNode ...
func ValNode(ip, pubkey, power string) { func ValNode(ip, pubkey, power string) {
url := "http://" + ip + ":8801" url := "http://" + ip + ":8801"
......
...@@ -21,12 +21,12 @@ import ( ...@@ -21,12 +21,12 @@ import (
) )
var ( var (
blocklog = log15.New("module", "tendermint-block") blocklog = log15.New("module", "tendermint-block")
// ConsensusCrypto define
ConsensusCrypto crypto.Crypto ConsensusCrypto crypto.Crypto
) )
//----------------------------------------------------------------------------- // BlockID struct
//BlockID
type BlockID struct { type BlockID struct {
tmtypes.BlockID tmtypes.BlockID
} }
...@@ -51,8 +51,7 @@ func (blockID BlockID) String() string { ...@@ -51,8 +51,7 @@ func (blockID BlockID) String() string {
return Fmt(`%v`, blockID.Hash) return Fmt(`%v`, blockID.Hash)
} }
//----------------------------------------------------------------------------- //TendermintBlock struct
//TendermintBlock
type TendermintBlock struct { type TendermintBlock struct {
*tmtypes.TendermintBlock *tmtypes.TendermintBlock
} }
...@@ -186,12 +185,10 @@ func (b *TendermintBlock) StringIndented(indent string) string { ...@@ -186,12 +185,10 @@ func (b *TendermintBlock) StringIndented(indent string) string {
func (b *TendermintBlock) StringShort() string { func (b *TendermintBlock) StringShort() string {
if b == nil { if b == nil {
return "nil-Block" return "nil-Block"
} else {
return Fmt("Block#%v", b.Hash())
} }
return Fmt("Block#%v", b.Hash())
} }
//-----------------------------------------------------------------------------
// Header defines the structure of a Tendermint block header // Header defines the structure of a Tendermint block header
// TODO: limit header size // TODO: limit header size
// NOTE: changes to the Header should be duplicated in the abci Header // NOTE: changes to the Header should be duplicated in the abci Header
...@@ -247,8 +244,7 @@ func (h *Header) StringIndented(indent string) string { ...@@ -247,8 +244,7 @@ func (h *Header) StringIndented(indent string) string {
indent, h.Hash()) indent, h.Hash())
} }
//----------------------------------------------------------------------------- // Commit struct
//Commit
type Commit struct { type Commit struct {
*tmtypes.TendermintCommit *tmtypes.TendermintCommit
...@@ -393,21 +389,21 @@ func (commit *Commit) StringIndented(indent string) string { ...@@ -393,21 +389,21 @@ func (commit *Commit) StringIndented(indent string) string {
indent, commit.hash) indent, commit.hash)
} }
//-----------------------------------------------------------------------------
// SignedHeader is a header along with the commits that prove it // SignedHeader is a header along with the commits that prove it
type SignedHeader struct { type SignedHeader struct {
Header *Header `json:"header"` Header *Header `json:"header"`
Commit *Commit `json:"commit"` Commit *Commit `json:"commit"`
} }
//----------------------------------------------------------------------------- // EvidenceEnvelope ...
type EvidenceEnvelope struct { type EvidenceEnvelope struct {
*tmtypes.EvidenceEnvelope *tmtypes.EvidenceEnvelope
} }
// EvidenceData contains any evidence of malicious wrong-doing by validators // EvidenceEnvelopeList contains any evidence of malicious wrong-doing by validators
type EvidenceEnvelopeList []EvidenceEnvelope type EvidenceEnvelopeList []EvidenceEnvelope
// Hash ...
func (env EvidenceEnvelope) Hash() []byte { func (env EvidenceEnvelope) Hash() []byte {
penv := env.EvidenceEnvelope penv := env.EvidenceEnvelope
evidence := EvidenceEnvelope2Evidence(penv) evidence := EvidenceEnvelope2Evidence(penv)
...@@ -464,6 +460,7 @@ func (evl EvidenceEnvelopeList) Has(evidence Evidence) bool { ...@@ -464,6 +460,7 @@ func (evl EvidenceEnvelopeList) Has(evidence Evidence) bool {
return false return false
} }
// EvidenceData ...
type EvidenceData struct { type EvidenceData struct {
*tmtypes.EvidenceData *tmtypes.EvidenceData
hash []byte hash []byte
...@@ -505,5 +502,4 @@ func (data *EvidenceData) StringIndented(indent string) string { ...@@ -505,5 +502,4 @@ func (data *EvidenceData) StringIndented(indent string) string {
%s}#%v`, %s}#%v`,
indent, strings.Join(evStrings, "\n"+indent+" "), indent, strings.Join(evStrings, "\n"+indent+" "),
indent, data.hash) indent, data.hash)
return ""
} }
...@@ -23,6 +23,7 @@ type ErrEvidenceInvalid struct { ...@@ -23,6 +23,7 @@ type ErrEvidenceInvalid struct {
ErrorValue error ErrorValue error
} }
// NewEvidenceInvalidErr ...
func NewEvidenceInvalidErr(ev Evidence, err error) *ErrEvidenceInvalid { func NewEvidenceInvalidErr(ev Evidence, err error) *ErrEvidenceInvalid {
return &ErrEvidenceInvalid{ev, err} return &ErrEvidenceInvalid{ev, err}
} }
...@@ -39,8 +40,11 @@ const ( ...@@ -39,8 +40,11 @@ const (
MockBad = "MockBad" MockBad = "MockBad"
) )
var EvidenceType2Type map[string]reflect.Type // EvidenceType map define
var EvidenceType2Obj map[string]Evidence var (
EvidenceType2Type map[string]reflect.Type
EvidenceType2Obj map[string]Evidence
)
// Evidence represents any provable malicious activity by a validator // Evidence represents any provable malicious activity by a validator
type Evidence interface { type Evidence interface {
...@@ -205,22 +209,27 @@ func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool { ...@@ -205,22 +209,27 @@ func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
return bytes.Equal(SimpleHashFromBinary(dve), SimpleHashFromBinary(ev.(*DuplicateVoteEvidence))) return bytes.Equal(SimpleHashFromBinary(dve), SimpleHashFromBinary(ev.(*DuplicateVoteEvidence)))
} }
// TypeName ...
func (dve *DuplicateVoteEvidence) TypeName() string { func (dve *DuplicateVoteEvidence) TypeName() string {
return DuplicateVote return DuplicateVote
} }
// Copy ...
func (dve *DuplicateVoteEvidence) Copy() Evidence { func (dve *DuplicateVoteEvidence) Copy() Evidence {
return &DuplicateVoteEvidence{} return &DuplicateVoteEvidence{}
} }
// SetChild ...
func (dve *DuplicateVoteEvidence) SetChild(child proto.Message) { func (dve *DuplicateVoteEvidence) SetChild(child proto.Message) {
dve.DuplicateVoteEvidence = child.(*tmtypes.DuplicateVoteEvidence) dve.DuplicateVoteEvidence = child.(*tmtypes.DuplicateVoteEvidence)
} }
// Child ...
func (dve *DuplicateVoteEvidence) Child() proto.Message { func (dve *DuplicateVoteEvidence) Child() proto.Message {
return dve.DuplicateVoteEvidence return dve.DuplicateVoteEvidence
} }
// SimpleHashFromBinary ...
func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte { func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte {
bytes, e := json.Marshal(item) bytes, e := json.Marshal(item)
if e != nil { if e != nil {
...@@ -231,6 +240,7 @@ func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte { ...@@ -231,6 +240,7 @@ func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte {
} }
// EvidenceEnvelope2Evidence ...
func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence { func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence {
if v, ok := EvidenceType2Type[envelope.TypeName]; ok { if v, ok := EvidenceType2Type[envelope.TypeName]; ok {
realMsg2 := reflect.New(v).Interface() realMsg2 := reflect.New(v).Interface()
...@@ -247,69 +257,98 @@ func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence { ...@@ -247,69 +257,98 @@ func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence {
return nil return nil
} }
//----------------------------------------------------------------- // MockGoodEvidence UNSTABLE
// UNSTABLE
type MockGoodEvidence struct { type MockGoodEvidence struct {
Height_ int64 MGHeight int64
Address_ []byte MGAddress []byte
Index_ int MGIndex int
} }
// UNSTABLE // NewMockGoodEvidence UNSTABLE
func NewMockGoodEvidence(height int64, index int, address []byte) MockGoodEvidence { func NewMockGoodEvidence(height int64, index int, address []byte) MockGoodEvidence {
return MockGoodEvidence{height, address, index} return MockGoodEvidence{height, address, index}
} }
func (e MockGoodEvidence) Height() int64 { return e.Height_ } // Height ...
func (e MockGoodEvidence) Address() []byte { return e.Address_ } func (e MockGoodEvidence) Height() int64 { return e.MGHeight }
func (e MockGoodEvidence) Index() int { return e.Index_ }
// Address ...
func (e MockGoodEvidence) Address() []byte { return e.MGAddress }
// Index ...
func (e MockGoodEvidence) Index() int { return e.MGIndex }
// Hash ...
func (e MockGoodEvidence) Hash() []byte { func (e MockGoodEvidence) Hash() []byte {
return []byte(Fmt("%d-%d", e.Height_, e.Index_)) return []byte(Fmt("%d-%d", e.MGHeight, e.MGIndex))
} }
// Verify ...
func (e MockGoodEvidence) Verify(chainID string) error { return nil } func (e MockGoodEvidence) Verify(chainID string) error { return nil }
// Equal ...
func (e MockGoodEvidence) Equal(ev Evidence) bool { func (e MockGoodEvidence) Equal(ev Evidence) bool {
e2 := ev.(MockGoodEvidence) e2 := ev.(MockGoodEvidence)
return e.Height_ == e2.Height_ && return e.MGHeight == e2.MGHeight &&
bytes.Equal(e.Address_, e2.Address_) && bytes.Equal(e.MGAddress, e2.MGAddress) &&
e.Index_ == e2.Index_ e.MGIndex == e2.MGIndex
} }
func (e MockGoodEvidence) String() string { func (e MockGoodEvidence) String() string {
return Fmt("GoodEvidence: %d/%s/%d", e.Height_, e.Address_, e.Index_) return Fmt("GoodEvidence: %d/%s/%d", e.MGHeight, e.MGAddress, e.MGIndex)
} }
// TypeName ...
func (e MockGoodEvidence) TypeName() string { func (e MockGoodEvidence) TypeName() string {
return MockGood return MockGood
} }
// Copy ...
func (e MockGoodEvidence) Copy() Evidence { func (e MockGoodEvidence) Copy() Evidence {
return &MockGoodEvidence{} return &MockGoodEvidence{}
} }
// SetChild ...
func (e MockGoodEvidence) SetChild(proto.Message) {} func (e MockGoodEvidence) SetChild(proto.Message) {}
// Child ...
func (e MockGoodEvidence) Child() proto.Message { func (e MockGoodEvidence) Child() proto.Message {
return nil return nil
} }
// UNSTABLE // MockBadEvidence UNSTABLE
type MockBadEvidence struct { type MockBadEvidence struct {
MockGoodEvidence MockGoodEvidence
} }
// Verify ...
func (e MockBadEvidence) Verify(chainID string) error { return fmt.Errorf("MockBadEvidence") } func (e MockBadEvidence) Verify(chainID string) error { return fmt.Errorf("MockBadEvidence") }
// Equal ...
func (e MockBadEvidence) Equal(ev Evidence) bool { func (e MockBadEvidence) Equal(ev Evidence) bool {
e2 := ev.(MockBadEvidence) e2 := ev.(MockBadEvidence)
return e.Height_ == e2.Height_ && return e.MGHeight == e2.MGHeight &&
bytes.Equal(e.Address_, e2.Address_) && bytes.Equal(e.MGAddress, e2.MGAddress) &&
e.Index_ == e2.Index_ e.MGIndex == e2.MGIndex
} }
func (e MockBadEvidence) String() string { func (e MockBadEvidence) String() string {
return Fmt("BadEvidence: %d/%s/%d", e.Height_, e.Address_, e.Index_) return Fmt("BadEvidence: %d/%s/%d", e.MGHeight, e.MGAddress, e.MGIndex)
} }
// TypeName ...
func (e MockBadEvidence) TypeName() string { func (e MockBadEvidence) TypeName() string {
return MockBad return MockBad
} }
// Copy ...
func (e MockBadEvidence) Copy() Evidence { func (e MockBadEvidence) Copy() Evidence {
return &MockBadEvidence{} return &MockBadEvidence{}
} }
// SetChild ...
func (e MockBadEvidence) SetChild(proto.Message) {} func (e MockBadEvidence) SetChild(proto.Message) {}
// Child ...
func (e MockBadEvidence) Child() proto.Message { func (e MockBadEvidence) Child() proto.Message {
return nil return nil
} }
...@@ -325,11 +364,16 @@ type EvidencePool interface { ...@@ -325,11 +364,16 @@ type EvidencePool interface {
Update(*TendermintBlock) Update(*TendermintBlock)
} }
// MockMempool is an empty implementation of a Mempool, useful for testing. // MockEvidencePool is an empty implementation of a Mempool, useful for testing.
// UNSTABLE // UNSTABLE
type MockEvidencePool struct { type MockEvidencePool struct {
} }
// PendingEvidence ...
func (m MockEvidencePool) PendingEvidence() []Evidence { return nil } func (m MockEvidencePool) PendingEvidence() []Evidence { return nil }
func (m MockEvidencePool) AddEvidence(Evidence) error { return nil }
func (m MockEvidencePool) Update(*TendermintBlock) {} // AddEvidence ...
func (m MockEvidencePool) AddEvidence(Evidence) error { return nil }
// Update ...
func (m MockEvidencePool) Update(*TendermintBlock) {}
...@@ -12,6 +12,7 @@ import ( ...@@ -12,6 +12,7 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types" tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
) )
// RoundVoteSet ...
type RoundVoteSet struct { type RoundVoteSet struct {
Prevotes *VoteSet Prevotes *VoteSet
Precommits *VoteSet Precommits *VoteSet
...@@ -31,6 +32,8 @@ peer to prevent abuse. ...@@ -31,6 +32,8 @@ peer to prevent abuse.
We let each peer provide us with up to 2 unexpected "catchup" rounds. We let each peer provide us with up to 2 unexpected "catchup" rounds.
One for their LastCommit round, and another for the official commit round. One for their LastCommit round, and another for the official commit round.
*/ */
// HeightVoteSet ...
type HeightVoteSet struct { type HeightVoteSet struct {
chainID string chainID string
height int64 height int64
...@@ -42,6 +45,7 @@ type HeightVoteSet struct { ...@@ -42,6 +45,7 @@ type HeightVoteSet struct {
peerCatchupRounds map[string][]int // keys: peer.Key; values: at most 2 rounds peerCatchupRounds map[string][]int // keys: peer.Key; values: at most 2 rounds
} }
// NewHeightVoteSet ...
func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *HeightVoteSet { func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *HeightVoteSet {
hvs := &HeightVoteSet{ hvs := &HeightVoteSet{
chainID: chainID, chainID: chainID,
...@@ -50,6 +54,7 @@ func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *Heigh ...@@ -50,6 +54,7 @@ func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *Heigh
return hvs return hvs
} }
// Reset ...
func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) { func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
...@@ -63,19 +68,21 @@ func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) { ...@@ -63,19 +68,21 @@ func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) {
hvs.round = 0 hvs.round = 0
} }
// Height ...
func (hvs *HeightVoteSet) Height() int64 { func (hvs *HeightVoteSet) Height() int64 {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
return hvs.height return hvs.height
} }
// Round ...
func (hvs *HeightVoteSet) Round() int { func (hvs *HeightVoteSet) Round() int {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
return hvs.round return hvs.round
} }
// Create more RoundVoteSets up to round. // SetRound Create more RoundVoteSets up to round.
func (hvs *HeightVoteSet) SetRound(round int) { func (hvs *HeightVoteSet) SetRound(round int) {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
...@@ -104,7 +111,7 @@ func (hvs *HeightVoteSet) addRound(round int) { ...@@ -104,7 +111,7 @@ func (hvs *HeightVoteSet) addRound(round int) {
} }
} }
// Duplicate votes return added=false, err=nil. // AddVote Duplicate votes return added=false, err=nil.
// By convention, peerKey is "" if origin is self. // By convention, peerKey is "" if origin is self.
func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err error) { func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err error) {
hvs.mtx.Lock() hvs.mtx.Lock()
...@@ -132,19 +139,21 @@ func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err er ...@@ -132,19 +139,21 @@ func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err er
return return
} }
// Prevotes ...
func (hvs *HeightVoteSet) Prevotes(round int) *VoteSet { func (hvs *HeightVoteSet) Prevotes(round int) *VoteSet {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
return hvs.getVoteSet(round, VoteTypePrevote) return hvs.getVoteSet(round, VoteTypePrevote)
} }
// Precommits ...
func (hvs *HeightVoteSet) Precommits(round int) *VoteSet { func (hvs *HeightVoteSet) Precommits(round int) *VoteSet {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
return hvs.getVoteSet(round, VoteTypePrecommit) return hvs.getVoteSet(round, VoteTypePrecommit)
} }
// Last round and blockID that has +2/3 prevotes for a particular block or nil. // POLInfo Last round and blockID that has +2/3 prevotes for a particular block or nil.
// Returns -1 if no such round exists. // Returns -1 if no such round exists.
func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) { func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) {
hvs.mtx.Lock() hvs.mtx.Lock()
...@@ -159,19 +168,18 @@ func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) { ...@@ -159,19 +168,18 @@ func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) {
return -1, BlockID{} return -1, BlockID{}
} }
func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *VoteSet { func (hvs *HeightVoteSet) getVoteSet(round int, voteType byte) *VoteSet {
rvs, ok := hvs.roundVoteSets[round] rvs, ok := hvs.roundVoteSets[round]
if !ok { if !ok {
return nil return nil
} }
switch type_ { switch voteType {
case VoteTypePrevote: case VoteTypePrevote:
return rvs.Prevotes return rvs.Prevotes
case VoteTypePrecommit: case VoteTypePrecommit:
return rvs.Precommits return rvs.Precommits
default: default:
panic(Fmt("Panicked on a Sanity Check: %v", Fmt("Unexpected vote type %X", type_))) panic(Fmt("Panicked on a Sanity Check: %v", Fmt("Unexpected vote type %X", voteType)))
return nil
} }
} }
...@@ -179,6 +187,7 @@ func (hvs *HeightVoteSet) String() string { ...@@ -179,6 +187,7 @@ func (hvs *HeightVoteSet) String() string {
return hvs.StringIndented("") return hvs.StringIndented("")
} }
// StringIndented ...
func (hvs *HeightVoteSet) StringIndented(indent string) string { func (hvs *HeightVoteSet) StringIndented(indent string) string {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
...@@ -208,17 +217,17 @@ func (hvs *HeightVoteSet) StringIndented(indent string) string { ...@@ -208,17 +217,17 @@ func (hvs *HeightVoteSet) StringIndented(indent string) string {
indent) indent)
} }
// If a peer claims that it has 2/3 majority for given blockKey, call this. // SetPeerMaj23 If a peer claims that it has 2/3 majority for given blockKey, call this.
// NOTE: if there are too many peers, or too much peer churn, // NOTE: if there are too many peers, or too much peer churn,
// this can cause memory issues. // this can cause memory issues.
// TODO: implement ability to remove peers too // TODO: implement ability to remove peers too
func (hvs *HeightVoteSet) SetPeerMaj23(round int, type_ byte, peerID string, blockID *tmtypes.BlockID) { func (hvs *HeightVoteSet) SetPeerMaj23(round int, voteType byte, peerID string, blockID *tmtypes.BlockID) {
hvs.mtx.Lock() hvs.mtx.Lock()
defer hvs.mtx.Unlock() defer hvs.mtx.Unlock()
if !IsVoteTypeValid(type_) { if !IsVoteTypeValid(voteType) {
return return
} }
voteSet := hvs.getVoteSet(round, type_) voteSet := hvs.getVoteSet(round, voteType)
if voteSet == nil { if voteSet == nil {
return return
} }
......
...@@ -82,7 +82,7 @@ func DefaultBlockGossip() BlockGossip { ...@@ -82,7 +82,7 @@ func DefaultBlockGossip() BlockGossip {
} }
} }
// DefaultEvidence Params returns a default EvidenceParams. // DefaultEvidenceParams returns a default EvidenceParams.
func DefaultEvidenceParams() EvidenceParams { func DefaultEvidenceParams() EvidenceParams {
return EvidenceParams{ return EvidenceParams{
MaxAge: 100000, // 27.8 hrs at 1block/s MaxAge: 100000, // 27.8 hrs at 1block/s
......
...@@ -22,6 +22,7 @@ var ( ...@@ -22,6 +22,7 @@ var (
pvFile = "priv_validator_" pvFile = "priv_validator_"
) )
// KeyFileCmd ...
func KeyFileCmd() *cobra.Command { func KeyFileCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "keyfile", Use: "keyfile",
...@@ -34,6 +35,7 @@ func KeyFileCmd() *cobra.Command { ...@@ -34,6 +35,7 @@ func KeyFileCmd() *cobra.Command {
return cmd return cmd
} }
// CreateCmd ...
func CreateCmd() *cobra.Command { func CreateCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "create", Use: "create",
...@@ -49,6 +51,7 @@ func addCreateCmdFlags(cmd *cobra.Command) { ...@@ -49,6 +51,7 @@ func addCreateCmdFlags(cmd *cobra.Command) {
cmd.MarkFlagRequired("num") cmd.MarkFlagRequired("num")
} }
// RandStr ...
func RandStr(length int) string { func RandStr(length int) string {
chars := []byte{} chars := []byte{}
MAIN_LOOP: MAIN_LOOP:
......
...@@ -12,16 +12,15 @@ import ( ...@@ -12,16 +12,15 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types" tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
) )
//-----------------------------------------------------------------------------
// RoundStepType enum type
// RoundStepType enumerates the state of the consensus state machine // RoundStepType enumerates the state of the consensus state machine
type RoundStepType uint8 // These must be numeric, ordered. type RoundStepType uint8 // These must be numeric, ordered.
var ( var (
// MsgMap define
MsgMap map[byte]reflect.Type MsgMap map[byte]reflect.Type
) )
// step and message id define
const ( const (
RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit
RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose
...@@ -49,6 +48,7 @@ const ( ...@@ -49,6 +48,7 @@ const (
PacketTypePong = byte(0xfe) PacketTypePong = byte(0xfe)
) )
// InitMessageMap ...
func InitMessageMap() { func InitMessageMap() {
MsgMap = map[byte]reflect.Type{ MsgMap = map[byte]reflect.Type{
EvidenceListID: reflect.TypeOf(tmtypes.EvidenceData{}), EvidenceListID: reflect.TypeOf(tmtypes.EvidenceData{}),
...@@ -114,6 +114,7 @@ type RoundState struct { ...@@ -114,6 +114,7 @@ type RoundState struct {
LastValidators *ValidatorSet LastValidators *ValidatorSet
} }
// RoundStateMessage ...
func (rs *RoundState) RoundStateMessage() *tmtypes.NewRoundStepMsg { func (rs *RoundState) RoundStateMessage() *tmtypes.NewRoundStepMsg {
return &tmtypes.NewRoundStepMsg{ return &tmtypes.NewRoundStepMsg{
Height: rs.Height, Height: rs.Height,
...@@ -164,7 +165,7 @@ func (rs *RoundState) StringShort() string { ...@@ -164,7 +165,7 @@ func (rs *RoundState) StringShort() string {
rs.Height, rs.Round, rs.Step, rs.StartTime) rs.Height, rs.Round, rs.Step, rs.StartTime)
} }
//---------------------PeerRoundState---------------------------- // PeerRoundState ...
type PeerRoundState struct { type PeerRoundState struct {
Height int64 // Height peer is at Height int64 // Height peer is at
Round int // Round peer is at, -1 if unknown. Round int // Round peer is at, -1 if unknown.
...@@ -211,16 +212,20 @@ func (prs PeerRoundState) StringIndented(indent string) string { ...@@ -211,16 +212,20 @@ func (prs PeerRoundState) StringIndented(indent string) string {
} }
//---------------------Canonical json----------------------------------- //---------------------Canonical json-----------------------------------
// CanonicalJSONBlockID ...
type CanonicalJSONBlockID struct { type CanonicalJSONBlockID struct {
Hash []byte `json:"hash,omitempty"` Hash []byte `json:"hash,omitempty"`
PartsHeader CanonicalJSONPartSetHeader `json:"parts,omitempty"` PartsHeader CanonicalJSONPartSetHeader `json:"parts,omitempty"`
} }
// CanonicalJSONPartSetHeader ...
type CanonicalJSONPartSetHeader struct { type CanonicalJSONPartSetHeader struct {
Hash []byte `json:"hash"` Hash []byte `json:"hash"`
Total int `json:"total"` Total int `json:"total"`
} }
// CanonicalJSONProposal ...
type CanonicalJSONProposal struct { type CanonicalJSONProposal struct {
BlockBytes []byte `json:"block_parts_header"` BlockBytes []byte `json:"block_parts_header"`
Height int64 `json:"height"` Height int64 `json:"height"`
...@@ -230,6 +235,7 @@ type CanonicalJSONProposal struct { ...@@ -230,6 +235,7 @@ type CanonicalJSONProposal struct {
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
} }
// CanonicalJSONVote ...
type CanonicalJSONVote struct { type CanonicalJSONVote struct {
BlockID CanonicalJSONBlockID `json:"block_id"` BlockID CanonicalJSONBlockID `json:"block_id"`
Height int64 `json:"height"` Height int64 `json:"height"`
...@@ -238,6 +244,7 @@ type CanonicalJSONVote struct { ...@@ -238,6 +244,7 @@ type CanonicalJSONVote struct {
Type byte `json:"type"` Type byte `json:"type"`
} }
// CanonicalJSONHeartbeat ...
type CanonicalJSONHeartbeat struct { type CanonicalJSONHeartbeat struct {
Height int64 `json:"height"` Height int64 `json:"height"`
Round int `json:"round"` Round int `json:"round"`
...@@ -246,33 +253,36 @@ type CanonicalJSONHeartbeat struct { ...@@ -246,33 +253,36 @@ type CanonicalJSONHeartbeat struct {
ValidatorIndex int `json:"validator_index"` ValidatorIndex int `json:"validator_index"`
} }
//------------------------------------
// Messages including a "chain id" can only be applied to one chain, hence "Once" // Messages including a "chain id" can only be applied to one chain, hence "Once"
// CanonicalJSONOnceProposal ...
type CanonicalJSONOnceProposal struct { type CanonicalJSONOnceProposal struct {
ChainID string `json:"chain_id"` ChainID string `json:"chain_id"`
Proposal CanonicalJSONProposal `json:"proposal"` Proposal CanonicalJSONProposal `json:"proposal"`
} }
// CanonicalJSONOnceVote ...
type CanonicalJSONOnceVote struct { type CanonicalJSONOnceVote struct {
ChainID string `json:"chain_id"` ChainID string `json:"chain_id"`
Vote CanonicalJSONVote `json:"vote"` Vote CanonicalJSONVote `json:"vote"`
} }
// CanonicalJSONOnceHeartbeat ...
type CanonicalJSONOnceHeartbeat struct { type CanonicalJSONOnceHeartbeat struct {
ChainID string `json:"chain_id"` ChainID string `json:"chain_id"`
Heartbeat CanonicalJSONHeartbeat `json:"heartbeat"` Heartbeat CanonicalJSONHeartbeat `json:"heartbeat"`
} }
//-----------------------------------
// Canonicalize the structs // Canonicalize the structs
// CanonicalBlockID ...
func CanonicalBlockID(blockID BlockID) CanonicalJSONBlockID { func CanonicalBlockID(blockID BlockID) CanonicalJSONBlockID {
return CanonicalJSONBlockID{ return CanonicalJSONBlockID{
Hash: blockID.Hash, Hash: blockID.Hash,
} }
} }
// CanonicalProposal ...
func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal { func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal {
return CanonicalJSONProposal{ return CanonicalJSONProposal{
//BlockBytes: proposal.BlockBytes, //BlockBytes: proposal.BlockBytes,
...@@ -286,6 +296,7 @@ func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal { ...@@ -286,6 +296,7 @@ func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal {
} }
} }
// CanonicalVote ...
func CanonicalVote(vote *Vote) CanonicalJSONVote { func CanonicalVote(vote *Vote) CanonicalJSONVote {
return CanonicalJSONVote{ return CanonicalJSONVote{
BlockID: CanonicalJSONBlockID{Hash: vote.BlockID.Hash}, BlockID: CanonicalJSONBlockID{Hash: vote.BlockID.Hash},
...@@ -296,6 +307,7 @@ func CanonicalVote(vote *Vote) CanonicalJSONVote { ...@@ -296,6 +307,7 @@ func CanonicalVote(vote *Vote) CanonicalJSONVote {
} }
} }
// CanonicalHeartbeat ...
func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat { func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat {
return CanonicalJSONHeartbeat{ return CanonicalJSONHeartbeat{
heartbeat.Height, heartbeat.Height,
...@@ -306,6 +318,7 @@ func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat { ...@@ -306,6 +318,7 @@ func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat {
} }
} }
// CanonicalTime ...
func CanonicalTime(t time.Time) string { func CanonicalTime(t time.Time) string {
// note that sending time over go-wire resets it to // note that sending time over go-wire resets it to
// local time, we need to force UTC here, so the // local time, we need to force UTC here, so the
......
...@@ -17,6 +17,7 @@ import ( ...@@ -17,6 +17,7 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types" tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
) )
// error defines
var ( var (
ErrVoteUnexpectedStep = errors.New("Unexpected step") ErrVoteUnexpectedStep = errors.New("Unexpected step")
ErrVoteInvalidValidatorIndex = errors.New("Invalid validator index") ErrVoteInvalidValidatorIndex = errors.New("Invalid validator index")
...@@ -44,7 +45,6 @@ func SignBytes(chainID string, o Signable) []byte { ...@@ -44,7 +45,6 @@ func SignBytes(chainID string, o Signable) []byte {
return buf.Bytes() return buf.Bytes()
} }
//----------------------Proposal----------------------
// Proposal defines a block proposal for the consensus. // Proposal defines a block proposal for the consensus.
// It refers to the block only by its PartSetHeader. // It refers to the block only by its PartSetHeader.
// It must be signed by the correct proposer for the given Height/Round // It must be signed by the correct proposer for the given Height/Round
...@@ -89,12 +89,12 @@ func (p *Proposal) WriteSignBytes(chainID string, w io.Writer, n *int, err *erro ...@@ -89,12 +89,12 @@ func (p *Proposal) WriteSignBytes(chainID string, w io.Writer, n *int, err *erro
*err = e *err = e
return return
} }
n_, err_ := w.Write(byteOnceProposal) number, writeErr := w.Write(byteOnceProposal)
*n = n_ *n = number
*err = err_ *err = writeErr
} }
//-------------------heartbeat------------------------- // Heartbeat ...
type Heartbeat struct { type Heartbeat struct {
*tmtypes.Heartbeat *tmtypes.Heartbeat
} }
...@@ -114,12 +114,12 @@ func (heartbeat *Heartbeat) WriteSignBytes(chainID string, w io.Writer, n *int, ...@@ -114,12 +114,12 @@ func (heartbeat *Heartbeat) WriteSignBytes(chainID string, w io.Writer, n *int,
*err = e *err = e
return return
} }
n_, err_ := w.Write(byteHeartbeat) number, writeErr := w.Write(byteHeartbeat)
*n = n_ *n = number
*err = err_ *err = writeErr
} }
//----------------------vote----------------------------- // ErrVoteConflictingVotes ...
type ErrVoteConflictingVotes struct { type ErrVoteConflictingVotes struct {
*DuplicateVoteEvidence *DuplicateVoteEvidence
} }
...@@ -133,6 +133,7 @@ func (err *ErrVoteConflictingVotes) Error() string { ...@@ -133,6 +133,7 @@ func (err *ErrVoteConflictingVotes) Error() string {
return fmt.Sprintf("Conflicting votes from validator %v", addr) return fmt.Sprintf("Conflicting votes from validator %v", addr)
} }
// NewConflictingVoteError ...
func NewConflictingVoteError(val *Validator, voteA, voteB *tmtypes.Vote) *ErrVoteConflictingVotes { func NewConflictingVoteError(val *Validator, voteA, voteB *tmtypes.Vote) *ErrVoteConflictingVotes {
keyString := fmt.Sprintf("%X", val.PubKey) keyString := fmt.Sprintf("%X", val.PubKey)
return &ErrVoteConflictingVotes{ return &ErrVoteConflictingVotes{
...@@ -153,8 +154,9 @@ const ( ...@@ -153,8 +154,9 @@ const (
VoteTypePrecommit = byte(0x02) VoteTypePrecommit = byte(0x02)
) )
func IsVoteTypeValid(type_ byte) bool { // IsVoteTypeValid ...
switch type_ { func IsVoteTypeValid(voteType byte) bool {
switch voteType {
case VoteTypePrevote: case VoteTypePrevote:
return true return true
case VoteTypePrecommit: case VoteTypePrecommit:
...@@ -164,11 +166,12 @@ func IsVoteTypeValid(type_ byte) bool { ...@@ -164,11 +166,12 @@ func IsVoteTypeValid(type_ byte) bool {
} }
} }
// Represents a prevote, precommit, or commit vote from validators for consensus. // Vote Represents a prevote, precommit, or commit vote from validators for consensus.
type Vote struct { type Vote struct {
*tmtypes.Vote *tmtypes.Vote
} }
// WriteSignBytes ...
func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) { func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) {
if *err != nil { if *err != nil {
return return
...@@ -183,11 +186,12 @@ func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error ...@@ -183,11 +186,12 @@ func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error
votelog.Error("vote WriteSignBytes marshal failed", "err", e) votelog.Error("vote WriteSignBytes marshal failed", "err", e)
return return
} }
n_, err_ := w.Write(byteVote) number, writeErr := w.Write(byteVote)
*n = n_ *n = number
*err = err_ *err = writeErr
} }
// Copy ...
func (vote *Vote) Copy() *Vote { func (vote *Vote) Copy() *Vote {
voteCopy := *vote voteCopy := *vote
return &voteCopy return &voteCopy
...@@ -214,6 +218,7 @@ func (vote *Vote) String() string { ...@@ -214,6 +218,7 @@ func (vote *Vote) String() string {
CanonicalTime(time.Unix(0, vote.Timestamp))) CanonicalTime(time.Unix(0, vote.Timestamp)))
} }
// Verify ...
func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error { func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
addr := GenAddressByPubKey(pubKey) addr := GenAddressByPubKey(pubKey)
if !bytes.Equal(addr, vote.ValidatorAddress) { if !bytes.Equal(addr, vote.ValidatorAddress) {
...@@ -232,6 +237,7 @@ func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error { ...@@ -232,6 +237,7 @@ func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
return nil return nil
} }
// Hash ...
func (vote *Vote) Hash() []byte { func (vote *Vote) Hash() []byte {
if vote == nil { if vote == nil {
//votelog.Error("vote hash is nil") //votelog.Error("vote hash is nil")
......
...@@ -22,6 +22,7 @@ import ( ...@@ -22,6 +22,7 @@ import (
) )
const ( const (
// RFC3339Millis ...
RFC3339Millis = "2006-01-02T15:04:05.000Z" // forced microseconds RFC3339Millis = "2006-01-02T15:04:05.000Z" // forced microseconds
timeFormat = RFC3339Millis timeFormat = RFC3339Millis
) )
...@@ -29,9 +30,11 @@ const ( ...@@ -29,9 +30,11 @@ const (
var ( var (
randgen *rand.Rand randgen *rand.Rand
randMux sync.Mutex randMux sync.Mutex
Fmt = fmt.Sprintf // Fmt ...
Fmt = fmt.Sprintf
) )
// Init ...
func Init() { func Init() {
if randgen == nil { if randgen == nil {
randMux.Lock() randMux.Lock()
...@@ -40,10 +43,12 @@ func Init() { ...@@ -40,10 +43,12 @@ func Init() {
} }
} }
// WriteFile ...
func WriteFile(filePath string, contents []byte, mode os.FileMode) error { func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
return ioutil.WriteFile(filePath, contents, mode) return ioutil.WriteFile(filePath, contents, mode)
} }
// WriteFileAtomic ...
func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error { func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
dir := filepath.Dir(filePath) dir := filepath.Dir(filePath)
f, err := ioutil.TempFile(dir, "") f, err := ioutil.TempFile(dir, "")
...@@ -70,7 +75,7 @@ func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error { ...@@ -70,7 +75,7 @@ func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
return err return err
} }
//---------------------------------------------------------- // Tempfile ...
func Tempfile(prefix string) (*os.File, string) { func Tempfile(prefix string) (*os.File, string) {
file, err := ioutil.TempFile("", prefix) file, err := ioutil.TempFile("", prefix)
if err != nil { if err != nil {
...@@ -79,12 +84,14 @@ func Tempfile(prefix string) (*os.File, string) { ...@@ -79,12 +84,14 @@ func Tempfile(prefix string) (*os.File, string) {
return file, file.Name() return file, file.Name()
} }
// Fingerprint ...
func Fingerprint(slice []byte) []byte { func Fingerprint(slice []byte) []byte {
fingerprint := make([]byte, 6) fingerprint := make([]byte, 6)
copy(fingerprint, slice) copy(fingerprint, slice)
return fingerprint return fingerprint
} }
// Kill ...
func Kill() error { func Kill() error {
p, err := os.FindProcess(os.Getpid()) p, err := os.FindProcess(os.Getpid())
if err != nil { if err != nil {
...@@ -93,12 +100,13 @@ func Kill() error { ...@@ -93,12 +100,13 @@ func Kill() error {
return p.Signal(syscall.SIGTERM) return p.Signal(syscall.SIGTERM)
} }
// Exit ...
func Exit(s string) { func Exit(s string) {
fmt.Printf(s + "\n") fmt.Printf(s + "\n")
os.Exit(1) os.Exit(1)
} }
//----------------------------------------------------------- // Parallel ...
func Parallel(tasks ...func()) { func Parallel(tasks ...func()) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(len(tasks)) wg.Add(len(tasks))
...@@ -114,6 +122,7 @@ func Parallel(tasks ...func()) { ...@@ -114,6 +122,7 @@ func Parallel(tasks ...func()) {
// Percent represents a percentage in increments of 1/1000th of a percent. // Percent represents a percentage in increments of 1/1000th of a percent.
type Percent uint32 type Percent uint32
// Float ...
func (p Percent) Float() float64 { func (p Percent) Float() float64 {
return float64(p) * 1e-3 return float64(p) * 1e-3
} }
...@@ -127,7 +136,7 @@ func (p Percent) String() string { ...@@ -127,7 +136,7 @@ func (p Percent) String() string {
return string(append(b, '%')) return string(append(b, '%'))
} }
//------------------------------------------------------------------- // MinInt ...
func MinInt(a, b int) int { func MinInt(a, b int) int {
if a < b { if a < b {
return a return a
...@@ -135,6 +144,7 @@ func MinInt(a, b int) int { ...@@ -135,6 +144,7 @@ func MinInt(a, b int) int {
return b return b
} }
// MaxInt ...
func MaxInt(a, b int) int { func MaxInt(a, b int) int {
if a > b { if a > b {
return a return a
...@@ -142,7 +152,7 @@ func MaxInt(a, b int) int { ...@@ -142,7 +152,7 @@ func MaxInt(a, b int) int {
return b return b
} }
//-------------------------------------------------------------- // RandIntn ...
func RandIntn(n int) int { func RandIntn(n int) int {
if n <= 0 { if n <= 0 {
panic("invalid argument to Intn") panic("invalid argument to Intn")
...@@ -159,6 +169,7 @@ func RandIntn(n int) int { ...@@ -159,6 +169,7 @@ func RandIntn(n int) int {
return int(i64) return int(i64)
} }
// RandUint32 ...
func RandUint32() uint32 { func RandUint32() uint32 {
randMux.Lock() randMux.Lock()
u32 := randgen.Uint32() u32 := randgen.Uint32()
...@@ -166,6 +177,7 @@ func RandUint32() uint32 { ...@@ -166,6 +177,7 @@ func RandUint32() uint32 {
return u32 return u32
} }
// RandInt63n ...
func RandInt63n(n int64) int64 { func RandInt63n(n int64) int64 {
randMux.Lock() randMux.Lock()
i64 := randgen.Int63n(n) i64 := randgen.Int63n(n)
...@@ -173,26 +185,28 @@ func RandInt63n(n int64) int64 { ...@@ -173,26 +185,28 @@ func RandInt63n(n int64) int64 {
return i64 return i64
} }
//------------------------------------------------------------- // PanicSanity ...
func PanicSanity(v interface{}) { func PanicSanity(v interface{}) {
panic(Fmt("Panicked on a Sanity Check: %v", v)) panic(Fmt("Panicked on a Sanity Check: %v", v))
} }
// PanicCrisis ...
func PanicCrisis(v interface{}) { func PanicCrisis(v interface{}) {
panic(Fmt("Panicked on a Crisis: %v", v)) panic(Fmt("Panicked on a Crisis: %v", v))
} }
// PanicQ ...
func PanicQ(v interface{}) { func PanicQ(v interface{}) {
panic(Fmt("Panicked questionably: %v", v)) panic(Fmt("Panicked questionably: %v", v))
} }
//--------------------BitArray------------------------ // BitArray ...
type BitArray struct { type BitArray struct {
*tmtypes.TendermintBitArray *tmtypes.TendermintBitArray
mtx sync.Mutex `json:"-"` mtx sync.Mutex
} }
// There is no BitArray whose Size is 0. Use nil instead. // NewBitArray There is no BitArray whose Size is 0. Use nil instead.
func NewBitArray(bits int) *BitArray { func NewBitArray(bits int) *BitArray {
if bits <= 0 { if bits <= 0 {
return nil return nil
...@@ -205,6 +219,7 @@ func NewBitArray(bits int) *BitArray { ...@@ -205,6 +219,7 @@ func NewBitArray(bits int) *BitArray {
} }
} }
// Size ...
func (bA *BitArray) Size() int { func (bA *BitArray) Size() int {
if bA == nil { if bA == nil {
return 0 return 0
...@@ -212,7 +227,7 @@ func (bA *BitArray) Size() int { ...@@ -212,7 +227,7 @@ func (bA *BitArray) Size() int {
return int(bA.Bits) return int(bA.Bits)
} }
// NOTE: behavior is undefined if i >= bA.Bits // GetIndex NOTE: behavior is undefined if i >= bA.Bits
func (bA *BitArray) GetIndex(i int) bool { func (bA *BitArray) GetIndex(i int) bool {
if bA == nil { if bA == nil {
return false return false
...@@ -229,7 +244,7 @@ func (bA *BitArray) getIndex(i int) bool { ...@@ -229,7 +244,7 @@ func (bA *BitArray) getIndex(i int) bool {
return bA.Elems[i/64]&(uint64(1)<<uint(i%64)) > 0 return bA.Elems[i/64]&(uint64(1)<<uint(i%64)) > 0
} }
// NOTE: behavior is undefined if i >= bA.Bits // SetIndex NOTE: behavior is undefined if i >= bA.Bits
func (bA *BitArray) SetIndex(i int, v bool) bool { func (bA *BitArray) SetIndex(i int, v bool) bool {
if bA == nil { if bA == nil {
return false return false
...@@ -251,6 +266,7 @@ func (bA *BitArray) setIndex(i int, v bool) bool { ...@@ -251,6 +266,7 @@ func (bA *BitArray) setIndex(i int, v bool) bool {
return true return true
} }
// Copy ...
func (bA *BitArray) Copy() *BitArray { func (bA *BitArray) Copy() *BitArray {
if bA == nil { if bA == nil {
return nil return nil
...@@ -280,7 +296,7 @@ func (bA *BitArray) copyBits(bits int) *BitArray { ...@@ -280,7 +296,7 @@ func (bA *BitArray) copyBits(bits int) *BitArray {
} }
} }
// Returns a BitArray of larger bits size. // Or Returns a BitArray of larger bits size.
func (bA *BitArray) Or(o *BitArray) *BitArray { func (bA *BitArray) Or(o *BitArray) *BitArray {
if bA == nil && o.TendermintBitArray == nil { if bA == nil && o.TendermintBitArray == nil {
return nil return nil
...@@ -300,7 +316,7 @@ func (bA *BitArray) Or(o *BitArray) *BitArray { ...@@ -300,7 +316,7 @@ func (bA *BitArray) Or(o *BitArray) *BitArray {
return c return c
} }
// Returns a BitArray of smaller bit size. // And Returns a BitArray of smaller bit size.
func (bA *BitArray) And(o *BitArray) *BitArray { func (bA *BitArray) And(o *BitArray) *BitArray {
if bA == nil || o.TendermintBitArray == nil { if bA == nil || o.TendermintBitArray == nil {
return nil return nil
...@@ -318,6 +334,7 @@ func (bA *BitArray) and(o *BitArray) *BitArray { ...@@ -318,6 +334,7 @@ func (bA *BitArray) and(o *BitArray) *BitArray {
return c return c
} }
// Not ...
func (bA *BitArray) Not() *BitArray { func (bA *BitArray) Not() *BitArray {
if bA == nil { if bA == nil {
return nil // Degenerate return nil // Degenerate
...@@ -331,6 +348,7 @@ func (bA *BitArray) Not() *BitArray { ...@@ -331,6 +348,7 @@ func (bA *BitArray) Not() *BitArray {
return c return c
} }
// Sub ...
func (bA *BitArray) Sub(o *BitArray) *BitArray { func (bA *BitArray) Sub(o *BitArray) *BitArray {
if bA == nil || o.TendermintBitArray == nil { if bA == nil || o.TendermintBitArray == nil {
return nil return nil
...@@ -354,6 +372,7 @@ func (bA *BitArray) Sub(o *BitArray) *BitArray { ...@@ -354,6 +372,7 @@ func (bA *BitArray) Sub(o *BitArray) *BitArray {
return bA.and(o.Not()) // Note degenerate case where o == nil return bA.and(o.Not()) // Note degenerate case where o == nil
} }
// IsEmpty ...
func (bA *BitArray) IsEmpty() bool { func (bA *BitArray) IsEmpty() bool {
if bA == nil { if bA == nil {
return true // should this be opposite? return true // should this be opposite?
...@@ -368,6 +387,7 @@ func (bA *BitArray) IsEmpty() bool { ...@@ -368,6 +387,7 @@ func (bA *BitArray) IsEmpty() bool {
return true return true
} }
// IsFull ...
func (bA *BitArray) IsFull() bool { func (bA *BitArray) IsFull() bool {
if bA == nil { if bA == nil {
return true return true
...@@ -388,6 +408,7 @@ func (bA *BitArray) IsFull() bool { ...@@ -388,6 +408,7 @@ func (bA *BitArray) IsFull() bool {
return (lastElem+1)&((uint64(1)<<uint(lastElemBits))-1) == 0 return (lastElem+1)&((uint64(1)<<uint(lastElemBits))-1) == 0
} }
// PickRandom ...
func (bA *BitArray) PickRandom() (int, bool) { func (bA *BitArray) PickRandom() (int, bool) {
if bA == nil { if bA == nil {
return 0, false return 0, false
...@@ -440,6 +461,7 @@ func (bA *BitArray) String() string { ...@@ -440,6 +461,7 @@ func (bA *BitArray) String() string {
return bA.stringIndented("") return bA.stringIndented("")
} }
// StringIndented ...
func (bA *BitArray) StringIndented(indent string) string { func (bA *BitArray) StringIndented(indent string) string {
if bA == nil { if bA == nil {
return "nil-BitArray" return "nil-BitArray"
...@@ -476,6 +498,7 @@ func (bA *BitArray) stringIndented(indent string) string { ...@@ -476,6 +498,7 @@ func (bA *BitArray) stringIndented(indent string) string {
return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent)) return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent))
} }
// Bytes ...
func (bA *BitArray) Bytes() []byte { func (bA *BitArray) Bytes() []byte {
bA.mtx.Lock() bA.mtx.Lock()
defer bA.mtx.Unlock() defer bA.mtx.Unlock()
...@@ -490,7 +513,7 @@ func (bA *BitArray) Bytes() []byte { ...@@ -490,7 +513,7 @@ func (bA *BitArray) Bytes() []byte {
return bytes return bytes
} }
// NOTE: other bitarray o is not locked when reading, // Update NOTE: other bitarray o is not locked when reading,
// so if necessary, caller must copy or lock o prior to calling Update. // so if necessary, caller must copy or lock o prior to calling Update.
// If bA is nil, does nothing. // If bA is nil, does nothing.
func (bA *BitArray) Update(o *BitArray) { func (bA *BitArray) Update(o *BitArray) {
...@@ -503,12 +526,12 @@ func (bA *BitArray) Update(o *BitArray) { ...@@ -503,12 +526,12 @@ func (bA *BitArray) Update(o *BitArray) {
} }
//------------------Heap---------------------- //------------------Heap----------------------
// Comparable ...
type Comparable interface { type Comparable interface {
Less(o interface{}) bool Less(o interface{}) bool
} }
//-----------------------------------------------------------------------------
/* /*
Example usage: Example usage:
h := NewHeap() h := NewHeap()
...@@ -522,22 +545,27 @@ Example usage: ...@@ -522,22 +545,27 @@ Example usage:
fmt.Println(h.Pop()) fmt.Println(h.Pop())
*/ */
// Heap ...
type Heap struct { type Heap struct {
pq priorityQueue pq priorityQueue
} }
// NewHeap ...
func NewHeap() *Heap { func NewHeap() *Heap {
return &Heap{pq: make([]*pqItem, 0)} return &Heap{pq: make([]*pqItem, 0)}
} }
// Len ...
func (h *Heap) Len() int64 { func (h *Heap) Len() int64 {
return int64(len(h.pq)) return int64(len(h.pq))
} }
// Push ...
func (h *Heap) Push(value interface{}, priority Comparable) { func (h *Heap) Push(value interface{}, priority Comparable) {
heap.Push(&h.pq, &pqItem{value: value, priority: priority}) heap.Push(&h.pq, &pqItem{value: value, priority: priority})
} }
// Peek ...
func (h *Heap) Peek() interface{} { func (h *Heap) Peek() interface{} {
if len(h.pq) == 0 { if len(h.pq) == 0 {
return nil return nil
...@@ -545,10 +573,12 @@ func (h *Heap) Peek() interface{} { ...@@ -545,10 +573,12 @@ func (h *Heap) Peek() interface{} {
return h.pq[0].value return h.pq[0].value
} }
// Update ...
func (h *Heap) Update(value interface{}, priority Comparable) { func (h *Heap) Update(value interface{}, priority Comparable) {
h.pq.Update(h.pq[0], value, priority) h.pq.Update(h.pq[0], value, priority)
} }
// Pop ...
func (h *Heap) Pop() interface{} { func (h *Heap) Pop() interface{} {
item := heap.Pop(&h.pq).(*pqItem) item := heap.Pop(&h.pq).(*pqItem)
return item.value return item.value
......
...@@ -19,6 +19,7 @@ import ( ...@@ -19,6 +19,7 @@ import (
var validatorsetlog = log15.New("module", "tendermint-val") var validatorsetlog = log15.New("module", "tendermint-val")
// Validator ...
type Validator struct { type Validator struct {
Address []byte `json:"address"` Address []byte `json:"address"`
PubKey []byte `json:"pub_key"` PubKey []byte `json:"pub_key"`
...@@ -27,6 +28,7 @@ type Validator struct { ...@@ -27,6 +28,7 @@ type Validator struct {
Accum int64 `json:"accum"` Accum int64 `json:"accum"`
} }
// NewValidator ...
func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator { func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
return &Validator{ return &Validator{
Address: GenAddressByPubKey(pubKey), Address: GenAddressByPubKey(pubKey),
...@@ -36,14 +38,14 @@ func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator { ...@@ -36,14 +38,14 @@ func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
} }
} }
// Creates a new copy of the validator so we can mutate accum. // Copy Creates a new copy of the validator so we can mutate accum.
// Panics if the validator is nil. // Panics if the validator is nil.
func (v *Validator) Copy() *Validator { func (v *Validator) Copy() *Validator {
vCopy := *v vCopy := *v
return &vCopy return &vCopy
} }
// Returns the one with higher Accum. // CompareAccum Returns the one with higher Accum.
func (v *Validator) CompareAccum(other *Validator) *Validator { func (v *Validator) CompareAccum(other *Validator) *Validator {
if v == nil { if v == nil {
return other return other
...@@ -105,6 +107,7 @@ type ValidatorSet struct { ...@@ -105,6 +107,7 @@ type ValidatorSet struct {
totalVotingPower int64 totalVotingPower int64
} }
// NewValidatorSet ...
func NewValidatorSet(vals []*Validator) *ValidatorSet { func NewValidatorSet(vals []*Validator) *ValidatorSet {
validators := make([]*Validator, len(vals)) validators := make([]*Validator, len(vals))
for i, val := range vals { for i, val := range vals {
...@@ -122,7 +125,7 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet { ...@@ -122,7 +125,7 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet {
return vs return vs
} }
// incrementAccum and update the proposer // IncrementAccum incrementAccum and update the proposer
// TODO: mind the overflow when times and votingPower shares too large. // TODO: mind the overflow when times and votingPower shares too large.
func (valSet *ValidatorSet) IncrementAccum(times int) { func (valSet *ValidatorSet) IncrementAccum(times int) {
// Add VotingPower * times to each validator and order into heap. // Add VotingPower * times to each validator and order into heap.
...@@ -143,6 +146,7 @@ func (valSet *ValidatorSet) IncrementAccum(times int) { ...@@ -143,6 +146,7 @@ func (valSet *ValidatorSet) IncrementAccum(times int) {
} }
} }
// Copy ...
func (valSet *ValidatorSet) Copy() *ValidatorSet { func (valSet *ValidatorSet) Copy() *ValidatorSet {
validators := make([]*Validator, len(valSet.Validators)) validators := make([]*Validator, len(valSet.Validators))
for i, val := range valSet.Validators { for i, val := range valSet.Validators {
...@@ -156,6 +160,7 @@ func (valSet *ValidatorSet) Copy() *ValidatorSet { ...@@ -156,6 +160,7 @@ func (valSet *ValidatorSet) Copy() *ValidatorSet {
} }
} }
// HasAddress ...
func (valSet *ValidatorSet) HasAddress(address []byte) bool { func (valSet *ValidatorSet) HasAddress(address []byte) bool {
idx := sort.Search(len(valSet.Validators), func(i int) bool { idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0 return bytes.Compare(address, valSet.Validators[i].Address) <= 0
...@@ -163,15 +168,15 @@ func (valSet *ValidatorSet) HasAddress(address []byte) bool { ...@@ -163,15 +168,15 @@ func (valSet *ValidatorSet) HasAddress(address []byte) bool {
return idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) return idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address)
} }
// GetByAddress ...
func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) { func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
idx := sort.Search(len(valSet.Validators), func(i int) bool { idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0 return bytes.Compare(address, valSet.Validators[i].Address) <= 0
}) })
if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) { if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) {
return idx, valSet.Validators[idx].Copy() return idx, valSet.Validators[idx].Copy()
} else {
return -1, nil
} }
return -1, nil
} }
// GetByIndex returns the validator by index. // GetByIndex returns the validator by index.
...@@ -185,10 +190,12 @@ func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validato ...@@ -185,10 +190,12 @@ func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validato
return val.Address, val.Copy() return val.Address, val.Copy()
} }
// Size ...
func (valSet *ValidatorSet) Size() int { func (valSet *ValidatorSet) Size() int {
return len(valSet.Validators) return len(valSet.Validators)
} }
// TotalVotingPower ...
func (valSet *ValidatorSet) TotalVotingPower() int64 { func (valSet *ValidatorSet) TotalVotingPower() int64 {
if valSet.totalVotingPower == 0 { if valSet.totalVotingPower == 0 {
for _, val := range valSet.Validators { for _, val := range valSet.Validators {
...@@ -198,6 +205,7 @@ func (valSet *ValidatorSet) TotalVotingPower() int64 { ...@@ -198,6 +205,7 @@ func (valSet *ValidatorSet) TotalVotingPower() int64 {
return valSet.totalVotingPower return valSet.totalVotingPower
} }
// GetProposer ...
func (valSet *ValidatorSet) GetProposer() (proposer *Validator) { func (valSet *ValidatorSet) GetProposer() (proposer *Validator) {
if len(valSet.Validators) == 0 { if len(valSet.Validators) == 0 {
return nil return nil
...@@ -218,6 +226,7 @@ func (valSet *ValidatorSet) findProposer() *Validator { ...@@ -218,6 +226,7 @@ func (valSet *ValidatorSet) findProposer() *Validator {
return proposer return proposer
} }
// Hash ...
func (valSet *ValidatorSet) Hash() []byte { func (valSet *ValidatorSet) Hash() []byte {
if len(valSet.Validators) == 0 { if len(valSet.Validators) == 0 {
return nil return nil
...@@ -229,6 +238,7 @@ func (valSet *ValidatorSet) Hash() []byte { ...@@ -229,6 +238,7 @@ func (valSet *ValidatorSet) Hash() []byte {
return merkle.GetMerkleRoot(hashables) return merkle.GetMerkleRoot(hashables)
} }
// Add ...
func (valSet *ValidatorSet) Add(val *Validator) (added bool) { func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
val = val.Copy() val = val.Copy()
idx := sort.Search(len(valSet.Validators), func(i int) bool { idx := sort.Search(len(valSet.Validators), func(i int) bool {
...@@ -255,39 +265,40 @@ func (valSet *ValidatorSet) Add(val *Validator) (added bool) { ...@@ -255,39 +265,40 @@ func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
} }
} }
// Update ...
func (valSet *ValidatorSet) Update(val *Validator) (updated bool) { func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
index, sameVal := valSet.GetByAddress(val.Address) index, sameVal := valSet.GetByAddress(val.Address)
if sameVal == nil { if sameVal == nil {
return false return false
} else {
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
} }
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
} }
// Remove ...
func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) { func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
idx := sort.Search(len(valSet.Validators), func(i int) bool { idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0 return bytes.Compare(address, valSet.Validators[i].Address) <= 0
}) })
if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) { if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) {
return nil, false return nil, false
} else {
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
} }
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
} }
// Iterate ...
func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
for i, val := range valSet.Validators { for i, val := range valSet.Validators {
stop := fn(i, val.Copy()) stop := fn(i, val.Copy())
...@@ -297,7 +308,7 @@ func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { ...@@ -297,7 +308,7 @@ func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
} }
} }
// Verify that +2/3 of the set had signed the given signBytes // VerifyCommit Verify that +2/3 of the set had signed the given signBytes
func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit) error { func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit) error {
if valSet.Size() != len(commit.Precommits) { if valSet.Size() != len(commit.Precommits) {
return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", valSet.Size(), len(commit.Precommits)) return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", valSet.Size(), len(commit.Precommits))
...@@ -350,10 +361,9 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height ...@@ -350,10 +361,9 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height
if talliedVotingPower > valSet.TotalVotingPower()*2/3 { if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
return nil return nil
} else {
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
} }
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
} }
// VerifyCommitAny will check to see if the set would // VerifyCommitAny will check to see if the set would
...@@ -453,6 +463,7 @@ func (valSet *ValidatorSet) String() string { ...@@ -453,6 +463,7 @@ func (valSet *ValidatorSet) String() string {
return valSet.StringIndented("") return valSet.StringIndented("")
} }
// StringIndented ...
func (valSet *ValidatorSet) StringIndented(indent string) string { func (valSet *ValidatorSet) StringIndented(indent string) string {
if valSet == nil { if valSet == nil {
return "nil-ValidatorSet" return "nil-ValidatorSet"
...@@ -474,9 +485,9 @@ func (valSet *ValidatorSet) StringIndented(indent string) string { ...@@ -474,9 +485,9 @@ func (valSet *ValidatorSet) StringIndented(indent string) string {
} }
//-------------------------------------
// Implements sort for sorting validators by address. // Implements sort for sorting validators by address.
// ValidatorsByAddress ...
type ValidatorsByAddress []*Validator type ValidatorsByAddress []*Validator
func (vs ValidatorsByAddress) Len() int { func (vs ValidatorsByAddress) Len() int {
......
...@@ -7,11 +7,14 @@ package ticket ...@@ -7,11 +7,14 @@ package ticket
import ( import (
"testing" "testing"
"github.com/33cn/plugin/plugin/dapp/ticket/types" "github.com/33cn/chain33/types"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/queue"
_ "github.com/33cn/chain33/system" _ "github.com/33cn/chain33/system"
"github.com/33cn/chain33/util/testnode" "github.com/33cn/chain33/util/testnode"
_ "github.com/33cn/plugin/plugin/dapp/init" _ "github.com/33cn/plugin/plugin/dapp/init"
ty "github.com/33cn/plugin/plugin/dapp/ticket/types"
_ "github.com/33cn/plugin/plugin/store/init" _ "github.com/33cn/plugin/plugin/store/init"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
...@@ -28,8 +31,8 @@ func TestTicket(t *testing.T) { ...@@ -28,8 +31,8 @@ func TestTicket(t *testing.T) {
func TestTicketMap(t *testing.T) { func TestTicketMap(t *testing.T) {
c := Client{} c := Client{}
ticketList := &types.ReplyTicketList{} ticketList := &ty.ReplyTicketList{}
ticketList.Tickets = []*types.Ticket{ ticketList.Tickets = []*ty.Ticket{
{TicketId: "1111"}, {TicketId: "1111"},
{TicketId: "2222"}, {TicketId: "2222"},
{TicketId: "3333"}, {TicketId: "3333"},
...@@ -40,5 +43,34 @@ func TestTicketMap(t *testing.T) { ...@@ -40,5 +43,34 @@ func TestTicketMap(t *testing.T) {
assert.Equal(t, c.getTicketCount(), int64(4)) assert.Equal(t, c.getTicketCount(), int64(4))
c.delTicket("3333") c.delTicket("3333")
assert.Equal(t, c.getTicketCount(), int64(3)) assert.Equal(t, c.getTicketCount(), int64(3))
}
func TestProcEvent(t *testing.T) {
c := Client{}
ret := c.ProcEvent(queue.Message{})
assert.Equal(t, ret, true)
}
func Test_genPrivHash(t *testing.T) {
c, err := crypto.New(types.GetSignName("", types.SECP256K1))
assert.NoError(t, err)
priv, _ := c.GenKey()
bt, err := genPrivHash(priv, "AA:BB:CC:DD")
assert.NotNil(t, err)
assert.Equal(t, 0, len(bt))
bt, err = genPrivHash(priv, "111:222:333:444")
assert.NoError(t, err)
assert.Equal(t, 32, len(bt))
}
func Test_getNextRequiredDifficulty(t *testing.T) {
c := &Client{}
bits, bt, err := c.getNextRequiredDifficulty(nil, 1)
assert.NoError(t, err)
assert.Equal(t, bt, defaultModify)
assert.Equal(t, bits, types.GetP(0).PowLimitBits)
} }
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package init package init
import ( import (
......
...@@ -15,6 +15,7 @@ import ( ...@@ -15,6 +15,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// BlackwhiteCmd 黑白配游戏命令行
func BlackwhiteCmd() *cobra.Command { func BlackwhiteCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "blackwhite", Use: "blackwhite",
...@@ -33,6 +34,7 @@ func BlackwhiteCmd() *cobra.Command { ...@@ -33,6 +34,7 @@ func BlackwhiteCmd() *cobra.Command {
return cmd return cmd
} }
// BlackwhiteCreateRawTxCmd 创建黑白配游戏交易命令
func BlackwhiteCreateRawTxCmd() *cobra.Command { func BlackwhiteCreateRawTxCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "create", Use: "create",
...@@ -83,6 +85,7 @@ func blackwhiteCreate(cmd *cobra.Command, args []string) { ...@@ -83,6 +85,7 @@ func blackwhiteCreate(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal() ctx.RunWithoutMarshal()
} }
// BlackwhitePlayRawTxCmd 参与玩黑白配游戏
func BlackwhitePlayRawTxCmd() *cobra.Command { func BlackwhitePlayRawTxCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "play", Use: "play",
...@@ -142,6 +145,7 @@ func blackwhitePlay(cmd *cobra.Command, args []string) { ...@@ -142,6 +145,7 @@ func blackwhitePlay(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal() ctx.RunWithoutMarshal()
} }
// BlackwhiteShowRawTxCmd 出示密钥
func BlackwhiteShowRawTxCmd() *cobra.Command { func BlackwhiteShowRawTxCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "show", Use: "show",
...@@ -180,6 +184,7 @@ func blackwhiteShow(cmd *cobra.Command, args []string) { ...@@ -180,6 +184,7 @@ func blackwhiteShow(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal() ctx.RunWithoutMarshal()
} }
// BlackwhiteTimeoutDoneTxCmd 触发游戏超时,由外部触发
func BlackwhiteTimeoutDoneTxCmd() *cobra.Command { func BlackwhiteTimeoutDoneTxCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "timeoutDone", Use: "timeoutDone",
...@@ -212,6 +217,7 @@ func blackwhiteTimeoutDone(cmd *cobra.Command, args []string) { ...@@ -212,6 +217,7 @@ func blackwhiteTimeoutDone(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal() ctx.RunWithoutMarshal()
} }
// ShowBlackwhiteInfoCmd 显示黑白配游戏查询信息
func ShowBlackwhiteInfoCmd() *cobra.Command { func ShowBlackwhiteInfoCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "showInfo", Use: "showInfo",
......
...@@ -19,14 +19,14 @@ import ( ...@@ -19,14 +19,14 @@ import (
) )
const ( const (
MaxAmount int64 = 100 * types.Coin maxAmount int64 = 100 * types.Coin
MinAmount int64 = 1 * types.Coin minAmount int64 = 1 * types.Coin
MinPlayerCount int32 = 3 minPlayerCount int32 = 3
MaxPlayerCount int32 = 100000 maxPlayerCount int32 = 100000
lockAmount int64 = types.Coin / 100 //创建者锁定金额 lockAmount int64 = types.Coin / 100 //创建者锁定金额
showTimeout int64 = 60 * 5 // 公布密钥超时时间 showTimeout int64 = 60 * 5 // 公布密钥超时时间
MaxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间 maxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间
MinPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间 minPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间
white = "0" white = "0"
black = "1" black = "1"
...@@ -63,13 +63,13 @@ func newAction(t *Blackwhite, tx *types.Transaction, index int32) *action { ...@@ -63,13 +63,13 @@ func newAction(t *Blackwhite, tx *types.Transaction, index int32) *action {
} }
func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) { func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
if create.PlayAmount < MinAmount || create.PlayAmount > MaxAmount { if create.PlayAmount < minAmount || create.PlayAmount > maxAmount {
return nil, types.ErrAmount return nil, types.ErrAmount
} }
if create.PlayerCount < MinPlayerCount || create.PlayerCount > MaxPlayerCount { if create.PlayerCount < minPlayerCount || create.PlayerCount > maxPlayerCount {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
if create.Timeout < MinPlayTimeout || create.Timeout > MaxPlayTimeout { if create.Timeout < minPlayTimeout || create.Timeout > maxPlayTimeout {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
...@@ -92,12 +92,12 @@ func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) { ...@@ -92,12 +92,12 @@ func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
key := calcMavlRoundKey(round.GameID) key := calcMavlRoundKey(round.GameID)
value := types.Encode(round) value := types.Encode(round)
kv = append(kv, &types.KeyValue{key, value}) kv = append(kv, &types.KeyValue{Key: key, Value: value})
receiptLog := a.GetReceiptLog(round, round.GetCreateAddr()) receiptLog := a.GetReceiptLog(round, round.GetCreateAddr())
logs = append(logs, receiptLog) logs = append(logs, receiptLog)
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) { func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) {
...@@ -184,9 +184,9 @@ func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) { ...@@ -184,9 +184,9 @@ func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) {
//将当前游戏状态保存,便于同一区块中游戏参数的累加 //将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1) a.db.Set(key1, value1)
} }
kv = append(kv, &types.KeyValue{key1, value1}) kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) { func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) {
...@@ -268,9 +268,9 @@ func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) { ...@@ -268,9 +268,9 @@ func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) {
//将当前游戏状态保存,便于同一区块中游戏参数的累加 //将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1) a.db.Set(key1, value1)
} }
kv = append(kv, &types.KeyValue{key1, value1}) kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, error) { func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, error) {
...@@ -364,7 +364,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er ...@@ -364,7 +364,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
//将当前游戏状态保存,便于同一区块中游戏参数的累加 //将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1) a.db.Set(key1, value1)
} }
kv = append(kv, &types.KeyValue{key1, value1}) kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
// 需要更新全部地址状态 // 需要更新全部地址状态
for _, addr := range round.AddrResult { for _, addr := range round.AddrResult {
...@@ -376,7 +376,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er ...@@ -376,7 +376,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
receiptLog := a.GetReceiptLog(&round, round.CreateAddr) receiptLog := a.GetReceiptLog(&round, round.CreateAddr)
logs = append(logs, receiptLog) logs = append(logs, receiptLog)
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
...@@ -514,9 +514,9 @@ func (a *action) StatTransfer(round *gt.BlackwhiteRound) (*types.Receipt, error) ...@@ -514,9 +514,9 @@ func (a *action) StatTransfer(round *gt.BlackwhiteRound) (*types.Receipt, error)
kv = append(kv, receipt.KV...) kv = append(kv, receipt.KV...)
// 将每一轮次的结果保存 // 将每一轮次的结果保存
logs = append(logs, &types.ReceiptLog{gt.TyLogBlackwhiteLoopInfo, types.Encode(loopResults)}) logs = append(logs, &types.ReceiptLog{Ty: gt.TyLogBlackwhiteLoopInfo, Log: types.Encode(loopResults)})
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
...@@ -646,14 +646,14 @@ func (a *action) getLoser(round *gt.BlackwhiteRound) []*addrResult { ...@@ -646,14 +646,14 @@ func (a *action) getLoser(round *gt.BlackwhiteRound) []*addrResult {
return results return results
} }
//状态变化: // GetReceiptLog 根据游戏信息获取log
// 状态变化:
// staus == BlackwhiteStatusCreate (创建,开始游戏) // staus == BlackwhiteStatusCreate (创建,开始游戏)
// status == BlackwhiteStatusPlay (参与) // status == BlackwhiteStatusPlay (参与)
// status == BlackwhiteStatusShow (展示密钥) // status == BlackwhiteStatusShow (展示密钥)
// status == BlackwhiteStatusTime (超时退出情况) // status == BlackwhiteStatusTime (超时退出情况)
// status == BlackwhiteStatusDone (结束情况) // status == BlackwhiteStatusDone (结束情况)
func (a *action) GetReceiptLog(round *gt.BlackwhiteRound, addr string) *types.ReceiptLog {
func (action *action) GetReceiptLog(round *gt.BlackwhiteRound, addr string) *types.ReceiptLog {
log := &types.ReceiptLog{} log := &types.ReceiptLog{}
r := &gt.ReceiptBlackwhiteStatus{} r := &gt.ReceiptBlackwhiteStatus{}
if round.Status == gt.BlackwhiteStatusCreate { if round.Status == gt.BlackwhiteStatusCreate {
......
...@@ -25,7 +25,7 @@ func init() { ...@@ -25,7 +25,7 @@ func init() {
ety.InitFuncList(types.ListMethod(&Blackwhite{})) ety.InitFuncList(types.ListMethod(&Blackwhite{}))
} }
//黑白配可以被重命名执行器名称 // Init 重命名执行器名称
func Init(name string, sub []byte) { func Init(name string, sub []byte) {
driverName = name driverName = name
gt.BlackwhiteX = driverName gt.BlackwhiteX = driverName
...@@ -33,6 +33,7 @@ func Init(name string, sub []byte) { ...@@ -33,6 +33,7 @@ func Init(name string, sub []byte) {
drivers.Register(name, newBlackwhite, types.GetDappFork(driverName, "Enable")) drivers.Register(name, newBlackwhite, types.GetDappFork(driverName, "Enable"))
} }
// Blackwhite 几类执行器结构体
type Blackwhite struct { type Blackwhite struct {
drivers.DriverBase drivers.DriverBase
} }
...@@ -44,10 +45,12 @@ func newBlackwhite() drivers.Driver { ...@@ -44,10 +45,12 @@ func newBlackwhite() drivers.Driver {
return c return c
} }
// GetName 获取执行器别名
func GetName() string { func GetName() string {
return newBlackwhite().GetName() return newBlackwhite().GetName()
} }
// GetDriverName 获取执行器名字
func (c *Blackwhite) GetDriverName() string { func (c *Blackwhite) GetDriverName() string {
return driverName return driverName
} }
...@@ -118,9 +121,10 @@ func (c *Blackwhite) delHeightIndex(res *gt.ReceiptBlackwhiteStatus) (kvs []*typ ...@@ -118,9 +121,10 @@ func (c *Blackwhite) delHeightIndex(res *gt.ReceiptBlackwhiteStatus) (kvs []*typ
return kvs return kvs
} }
// GetBlackwhiteRoundInfo 获取当前游戏信息
func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (types.Message, error) { func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (types.Message, error) {
gameId := req.GameID gameID := req.GameID
key := calcMavlRoundKey(gameId) key := calcMavlRoundKey(gameID)
values, err := c.GetStateDB().Get(key) values, err := c.GetStateDB().Get(key)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -157,6 +161,7 @@ func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (typ ...@@ -157,6 +161,7 @@ func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (typ
return &rep, nil return &rep, nil
} }
// GetBwRoundListInfo 根据要求获取游戏信息,包括游戏所处状态,或者参与者地址
func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.Message, error) { func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.Message, error) {
var key []byte var key []byte
var values [][]byte var values [][]byte
...@@ -234,6 +239,7 @@ func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.M ...@@ -234,6 +239,7 @@ func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.M
return &rep, nil return &rep, nil
} }
// GetBwRoundLoopResult 获取游戏中每轮的胜负结果
func (c *Blackwhite) GetBwRoundLoopResult(req *gt.ReqLoopResult) (types.Message, error) { func (c *Blackwhite) GetBwRoundLoopResult(req *gt.ReqLoopResult) (types.Message, error) {
localDb := c.GetLocalDB() localDb := c.GetLocalDB()
values, err := localDb.Get(calcRoundKey4LoopResult(req.GameID)) values, err := localDb.Get(calcRoundKey4LoopResult(req.GameID))
...@@ -275,6 +281,7 @@ func heightIndexToIndex(height int64, index int32) int64 { ...@@ -275,6 +281,7 @@ func heightIndexToIndex(height int64, index int32) int64 {
return height*types.MaxTxsPerBlock + int64(index) return height*types.MaxTxsPerBlock + int64(index)
} }
// GetPayloadValue 获取执行器action结构体
func (c *Blackwhite) GetPayloadValue() types.Message { func (c *Blackwhite) GetPayloadValue() types.Message {
return &gt.BlackwhiteAction{} return &gt.BlackwhiteAction{}
} }
...@@ -9,21 +9,25 @@ import ( ...@@ -9,21 +9,25 @@ import (
gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types" gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
) )
// Exec_Create 创建游戏
func (c *Blackwhite) Exec_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *Blackwhite) Exec_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index)) action := newAction(c, tx, int32(index))
return action.Create(payload) return action.Create(payload)
} }
// Exec_Play 参与游戏
func (c *Blackwhite) Exec_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *Blackwhite) Exec_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index)) action := newAction(c, tx, int32(index))
return action.Play(payload) return action.Play(payload)
} }
// Exec_Show 出示密钥
func (c *Blackwhite) Exec_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *Blackwhite) Exec_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index)) action := newAction(c, tx, int32(index))
return action.Show(payload) return action.Show(payload)
} }
// Exec_TimeoutDone 超时处理
func (c *Blackwhite) Exec_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *Blackwhite) Exec_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index)) action := newAction(c, tx, int32(index))
return action.TimeoutDone(payload) return action.TimeoutDone(payload)
......
...@@ -59,6 +59,7 @@ func (c *Blackwhite) execDelLocal(receiptData *types.ReceiptData) ([]*types.KeyV ...@@ -59,6 +59,7 @@ func (c *Blackwhite) execDelLocal(receiptData *types.ReceiptData) ([]*types.KeyV
return retKV, nil return retKV, nil
} }
// ExecDelLocal_Create 执行删除创建游戏产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData) kv, err := c.execDelLocal(receiptData)
if err != nil { if err != nil {
...@@ -67,6 +68,7 @@ func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types ...@@ -67,6 +68,7 @@ func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecDelLocal_Play 执行删除参与游戏产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData) kv, err := c.execDelLocal(receiptData)
if err != nil { if err != nil {
...@@ -75,6 +77,7 @@ func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Tra ...@@ -75,6 +77,7 @@ func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Tra
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecDelLocal_Show 执行删除出示密钥产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData) kv, err := c.execDelLocal(receiptData)
if err != nil { if err != nil {
...@@ -83,6 +86,7 @@ func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Tra ...@@ -83,6 +86,7 @@ func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Tra
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecDelLocal_TimeoutDone 执行删除超时产生的本地数据库
func (c *Blackwhite) ExecDelLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecDelLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData) kv, err := c.execDelLocal(receiptData)
if err != nil { if err != nil {
......
...@@ -44,6 +44,7 @@ func (c *Blackwhite) execLocal(receiptData *types.ReceiptData) ([]*types.KeyValu ...@@ -44,6 +44,7 @@ func (c *Blackwhite) execLocal(receiptData *types.ReceiptData) ([]*types.KeyValu
return set, nil return set, nil
} }
// ExecLocal_Create 执行生成创建游戏产生的本地数据库
func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData) kv, err := c.execLocal(receiptData)
if err != nil { if err != nil {
...@@ -52,6 +53,7 @@ func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Tr ...@@ -52,6 +53,7 @@ func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Tr
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecLocal_Play 执行生成参与游戏产生的本地数据库
func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData) kv, err := c.execLocal(receiptData)
if err != nil { if err != nil {
...@@ -60,6 +62,7 @@ func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transa ...@@ -60,6 +62,7 @@ func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transa
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecLocal_Show 执行生成出示密钥产生的本地数据库
func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData) kv, err := c.execLocal(receiptData)
if err != nil { if err != nil {
...@@ -68,6 +71,7 @@ func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transa ...@@ -68,6 +71,7 @@ func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transa
return &types.LocalDBSet{KV: kv}, nil return &types.LocalDBSet{KV: kv}, nil
} }
// ExecLocal_TimeoutDone 执行生成超时产生的本地数据库
func (c *Blackwhite) ExecLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Blackwhite) ExecLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData) kv, err := c.execLocal(receiptData)
if err != nil { if err != nil {
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types" gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
) )
// Query_GetBlackwhiteRoundInfo 查询游戏信息
func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo) (types.Message, error) { func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo) (types.Message, error) {
if in == nil { if in == nil {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
...@@ -16,6 +17,7 @@ func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo) ...@@ -16,6 +17,7 @@ func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo)
return c.GetBlackwhiteRoundInfo(in) return c.GetBlackwhiteRoundInfo(in)
} }
// Query_GetBlackwhiteByStatusAndAddr 查询符合状态以及地址的游戏信息
func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoundList) (types.Message, error) { func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoundList) (types.Message, error) {
if in == nil { if in == nil {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
...@@ -23,6 +25,7 @@ func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoun ...@@ -23,6 +25,7 @@ func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoun
return c.GetBwRoundListInfo(in) return c.GetBwRoundListInfo(in)
} }
// Query_GetBlackwhiteloopResult 查询游戏中每轮次的比赛结果
func (c *Blackwhite) Query_GetBlackwhiteloopResult(in *gt.ReqLoopResult) (types.Message, error) { func (c *Blackwhite) Query_GetBlackwhiteloopResult(in *gt.ReqLoopResult) (types.Message, error) {
if in == nil { if in == nil {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
package executor package executor
// BlackwhiteCreateTxReq 创建游戏结构体
type BlackwhiteCreateTxReq struct { type BlackwhiteCreateTxReq struct {
PlayAmount int64 `json:"amount"` PlayAmount int64 `json:"amount"`
PlayerCount int32 `json:"playerCount"` PlayerCount int32 `json:"playerCount"`
...@@ -12,6 +13,7 @@ type BlackwhiteCreateTxReq struct { ...@@ -12,6 +13,7 @@ type BlackwhiteCreateTxReq struct {
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhitePlayTx 参与游戏结构体
type BlackwhitePlayTx struct { type BlackwhitePlayTx struct {
GameID string `json:"gameID"` GameID string `json:"gameID"`
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
...@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct { ...@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct {
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhiteShowTx 出示密钥结构体
type BlackwhiteShowTx struct { type BlackwhiteShowTx struct {
GameID string `json:"gameID"` GameID string `json:"gameID"`
Secret string `json:"secret"` Secret string `json:"secret"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhiteTimeoutDoneTx 游戏超时结构体
type BlackwhiteTimeoutDoneTx struct { type BlackwhiteTimeoutDoneTx struct {
GameID string `json:"GameID"` GameID string `json:"GameID"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Package blackwhite 黑白配游戏插件
package blackwhite package blackwhite
import ( import (
......
...@@ -12,6 +12,7 @@ import ( ...@@ -12,6 +12,7 @@ import (
bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types" bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
) )
// BlackwhiteCreateTx 创建游戏RPC接口
func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interface{}) error { func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interface{}) error {
if parm == nil { if parm == nil {
return types.ErrInvalidParam return types.ErrInvalidParam
...@@ -30,6 +31,7 @@ func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interf ...@@ -30,6 +31,7 @@ func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interf
return nil return nil
} }
// BlackwhiteShowTx 出示游戏密钥的RPC接口
func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) error { func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) error {
if parm == nil { if parm == nil {
return types.ErrInvalidParam return types.ErrInvalidParam
...@@ -46,6 +48,7 @@ func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) err ...@@ -46,6 +48,7 @@ func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) err
return nil return nil
} }
// BlackwhitePlayTx 参与游戏的RPC接口
func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) error { func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) error {
if parm == nil { if parm == nil {
return types.ErrInvalidParam return types.ErrInvalidParam
...@@ -65,6 +68,7 @@ func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) err ...@@ -65,6 +68,7 @@ func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) err
return nil return nil
} }
// BlackwhiteTimeoutDoneTx 游戏超时RPC接口
func (c *Jrpc) BlackwhiteTimeoutDoneTx(parm *BlackwhiteTimeoutDoneTx, result *interface{}) error { func (c *Jrpc) BlackwhiteTimeoutDoneTx(parm *BlackwhiteTimeoutDoneTx, result *interface{}) error {
if parm == nil { if parm == nil {
return types.ErrInvalidParam return types.ErrInvalidParam
......
...@@ -14,7 +14,7 @@ import ( ...@@ -14,7 +14,7 @@ import (
func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) (*types.UnsignTx, error) { func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{ val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionCreate, Ty: bw.BlackwhiteActionCreate,
Value: &bw.BlackwhiteAction_Create{head}, Value: &bw.BlackwhiteAction_Create{Create: head},
} }
tx := &types.Transaction{ tx := &types.Transaction{
Payload: types.Encode(val), Payload: types.Encode(val),
...@@ -29,7 +29,7 @@ func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) ( ...@@ -29,7 +29,7 @@ func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) (
func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*types.UnsignTx, error) { func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{ val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionShow, Ty: bw.BlackwhiteActionShow,
Value: &bw.BlackwhiteAction_Show{head}, Value: &bw.BlackwhiteAction_Show{Show: head},
} }
tx := &types.Transaction{ tx := &types.Transaction{
Payload: types.Encode(val), Payload: types.Encode(val),
...@@ -44,7 +44,7 @@ func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*typ ...@@ -44,7 +44,7 @@ func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*typ
func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*types.UnsignTx, error) { func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{ val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionPlay, Ty: bw.BlackwhiteActionPlay,
Value: &bw.BlackwhiteAction_Play{head}, Value: &bw.BlackwhiteAction_Play{Play: head},
} }
tx := &types.Transaction{ tx := &types.Transaction{
Payload: types.Encode(val), Payload: types.Encode(val),
...@@ -59,7 +59,7 @@ func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*typ ...@@ -59,7 +59,7 @@ func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*typ
func (c *channelClient) TimeoutDone(ctx context.Context, head *bw.BlackwhiteTimeoutDone) (*types.UnsignTx, error) { func (c *channelClient) TimeoutDone(ctx context.Context, head *bw.BlackwhiteTimeoutDone) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{ val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionTimeoutDone, Ty: bw.BlackwhiteActionTimeoutDone,
Value: &bw.BlackwhiteAction_TimeoutDone{head}, Value: &bw.BlackwhiteAction_TimeoutDone{TimeoutDone: head},
} }
tx := &types.Transaction{ tx := &types.Transaction{
Payload: types.Encode(val), Payload: types.Encode(val),
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
package rpc package rpc
// BlackwhiteCreateTx 创建游戏结构体
type BlackwhiteCreateTx struct { type BlackwhiteCreateTx struct {
PlayAmount int64 `json:"amount"` PlayAmount int64 `json:"amount"`
PlayerCount int32 `json:"playerCount"` PlayerCount int32 `json:"playerCount"`
...@@ -12,6 +13,7 @@ type BlackwhiteCreateTx struct { ...@@ -12,6 +13,7 @@ type BlackwhiteCreateTx struct {
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhitePlayTx 参与游戏结构体
type BlackwhitePlayTx struct { type BlackwhitePlayTx struct {
GameID string `json:"gameID"` GameID string `json:"gameID"`
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
...@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct { ...@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct {
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhiteShowTx 出示密钥结构体
type BlackwhiteShowTx struct { type BlackwhiteShowTx struct {
GameID string `json:"gameID"` GameID string `json:"gameID"`
Secret string `json:"secret"` Secret string `json:"secret"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// BlackwhiteTimeoutDoneTx 游戏超时结构体
type BlackwhiteTimeoutDoneTx struct { type BlackwhiteTimeoutDoneTx struct {
GameID string `json:"GameID"` GameID string `json:"GameID"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
......
...@@ -13,10 +13,12 @@ import ( ...@@ -13,10 +13,12 @@ import (
bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types" bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
) )
// Jrpc json rpc struct
type Jrpc struct { type Jrpc struct {
cli *channelClient cli *channelClient
} }
// Grpc grpc struct
type Grpc struct { type Grpc struct {
*channelClient *channelClient
} }
...@@ -25,6 +27,7 @@ type channelClient struct { ...@@ -25,6 +27,7 @@ type channelClient struct {
rpctypes.ChannelClient rpctypes.ChannelClient
} }
// Init init grpc param
func Init(name string, s rpctypes.RPCServer) { func Init(name string, s rpctypes.RPCServer) {
cli := &channelClient{} cli := &channelClient{}
grpc := &Grpc{channelClient: cli} grpc := &Grpc{channelClient: cli}
...@@ -32,8 +35,10 @@ func Init(name string, s rpctypes.RPCServer) { ...@@ -32,8 +35,10 @@ func Init(name string, s rpctypes.RPCServer) {
bw.RegisterBlackwhiteServer(s.GRPC(), grpc) bw.RegisterBlackwhiteServer(s.GRPC(), grpc)
} }
// BlackwhiteCreateTxRPC ...
type BlackwhiteCreateTxRPC struct{} type BlackwhiteCreateTxRPC struct{}
// Input for convert struct
func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteCreateTxReq var req bw.BlackwhiteCreateTxReq
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -43,6 +48,7 @@ func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) { ...@@ -43,6 +48,7 @@ func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok { if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok { if tx, ok := (*replyData).(*types.Transaction); ok {
...@@ -53,9 +59,11 @@ func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) { ...@@ -53,9 +59,11 @@ func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset return nil, types.ErrTypeAsset
} }
// BlackwhitePlayTxRPC ...
type BlackwhitePlayTxRPC struct { type BlackwhitePlayTxRPC struct {
} }
// Input for convert struct
func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhitePlayTxReq var req bw.BlackwhitePlayTxReq
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -65,6 +73,7 @@ func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) { ...@@ -65,6 +73,7 @@ func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) { func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok { if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok { if tx, ok := (*replyData).(*types.Transaction); ok {
...@@ -75,9 +84,11 @@ func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) { ...@@ -75,9 +84,11 @@ func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset return nil, types.ErrTypeAsset
} }
// BlackwhiteShowTxRPC ...
type BlackwhiteShowTxRPC struct { type BlackwhiteShowTxRPC struct {
} }
// Input for convert struct
func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteShowTxReq var req bw.BlackwhiteShowTxReq
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -87,6 +98,7 @@ func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) { ...@@ -87,6 +98,7 @@ func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok { if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok { if tx, ok := (*replyData).(*types.Transaction); ok {
...@@ -97,9 +109,11 @@ func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) { ...@@ -97,9 +109,11 @@ func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset return nil, types.ErrTypeAsset
} }
// BlackwhiteTimeoutDoneTxRPC ...
type BlackwhiteTimeoutDoneTxRPC struct { type BlackwhiteTimeoutDoneTxRPC struct {
} }
// Input for convert struct
func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteTimeoutDoneTxReq var req bw.BlackwhiteTimeoutDoneTxReq
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -109,6 +123,7 @@ func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, err ...@@ -109,6 +123,7 @@ func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, err
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteTimeoutDoneTxRPC) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteTimeoutDoneTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok { if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok { if tx, ok := (*replyData).(*types.Transaction); ok {
......
...@@ -21,26 +21,36 @@ const ( ...@@ -21,26 +21,36 @@ const (
) )
const ( const (
// log for blackwhite game // TyLogBlackwhiteCreate log for blackwhite create game
TyLogBlackwhiteCreate = 750 TyLogBlackwhiteCreate = 750
TyLogBlackwhitePlay = 751 // TyLogBlackwhitePlay log for blackwhite play game
TyLogBlackwhiteShow = 752 TyLogBlackwhitePlay = 751
TyLogBlackwhiteTimeout = 753 // TyLogBlackwhiteShow log for blackwhite show game
TyLogBlackwhiteDone = 754 TyLogBlackwhiteShow = 752
// TyLogBlackwhiteTimeout log for blackwhite timeout game
TyLogBlackwhiteTimeout = 753
// TyLogBlackwhiteDone log for blackwhite down game
TyLogBlackwhiteDone = 754
// TyLogBlackwhiteLoopInfo log for blackwhite LoopInfo game
TyLogBlackwhiteLoopInfo = 755 TyLogBlackwhiteLoopInfo = 755
) )
const ( const (
GetBlackwhiteRoundInfo = "GetBlackwhiteRoundInfo" // GetBlackwhiteRoundInfo 用于在cmd里面的区分不同的查询
GetBlackwhiteRoundInfo = "GetBlackwhiteRoundInfo"
// GetBlackwhiteByStatusAndAddr 用于在cmd里面的区分不同的查询
GetBlackwhiteByStatusAndAddr = "GetBlackwhiteByStatusAndAddr" GetBlackwhiteByStatusAndAddr = "GetBlackwhiteByStatusAndAddr"
GetBlackwhiteloopResult = "GetBlackwhiteloopResult" // GetBlackwhiteloopResult 用于在cmd里面的区分不同的查询
GetBlackwhiteloopResult = "GetBlackwhiteloopResult"
) )
var ( var (
// BlackwhiteX 执行器名字
BlackwhiteX = "blackwhite" BlackwhiteX = "blackwhite"
glog = log15.New("module", BlackwhiteX) glog = log15.New("module", BlackwhiteX)
//GRPCName = "chain33.blackwhite" // JRPCName json RPC name
JRPCName = "Blackwhite" JRPCName = "Blackwhite"
// ExecerBlackwhite 执行器名字byte形式
ExecerBlackwhite = []byte(BlackwhiteX) ExecerBlackwhite = []byte(BlackwhiteX)
actionName = map[string]int32{ actionName = map[string]int32{
"Create": BlackwhiteActionCreate, "Create": BlackwhiteActionCreate,
......
...@@ -7,9 +7,14 @@ package types ...@@ -7,9 +7,14 @@ package types
import "errors" import "errors"
var ( var (
ErrIncorrectStatus = errors.New("ErrIncorrectStatus") // ErrIncorrectStatus 所处游戏状态不正确
ErrIncorrectStatus = errors.New("ErrIncorrectStatus")
// ErrRepeatPlayerAddr 重复玩家
ErrRepeatPlayerAddr = errors.New("ErrRepeatPlayerAddress") ErrRepeatPlayerAddr = errors.New("ErrRepeatPlayerAddress")
ErrNoTimeoutDone = errors.New("ErrNoTimeoutDone") // ErrNoTimeoutDone 还未超时
ErrNoExistAddr = errors.New("ErrNoExistAddress") ErrNoTimeoutDone = errors.New("ErrNoTimeoutDone")
ErrNoLoopSeq = errors.New("ErrBlackwhiteFinalloopLessThanSeq") // ErrNoExistAddr 不存在地址,未参与游戏
ErrNoExistAddr = errors.New("ErrNoExistAddress")
// ErrNoLoopSeq 查询的轮次大于决出胜负的轮次
ErrNoLoopSeq = errors.New("ErrBlackwhiteFinalloopLessThanSeq")
) )
...@@ -12,9 +12,13 @@ import ( ...@@ -12,9 +12,13 @@ import (
// blackwhite action type // blackwhite action type
const ( const (
// BlackwhiteActionCreate blackwhite create action
BlackwhiteActionCreate = iota BlackwhiteActionCreate = iota
// BlackwhiteActionPlay blackwhite play action
BlackwhiteActionPlay BlackwhiteActionPlay
// BlackwhiteActionShow blackwhite show action
BlackwhiteActionShow BlackwhiteActionShow
// BlackwhiteActionTimeoutDone blackwhite timeout action
BlackwhiteActionTimeoutDone BlackwhiteActionTimeoutDone
) )
...@@ -26,33 +30,40 @@ func init() { ...@@ -26,33 +30,40 @@ func init() {
types.RegisterDappFork(BlackwhiteX, "Enable", 850000) types.RegisterDappFork(BlackwhiteX, "Enable", 850000)
} }
// BlackwhiteType 执行器基类结构体
type BlackwhiteType struct { type BlackwhiteType struct {
types.ExecTypeBase types.ExecTypeBase
} }
// NewType 创建执行器类型
func NewType() *BlackwhiteType { func NewType() *BlackwhiteType {
c := &BlackwhiteType{} c := &BlackwhiteType{}
c.SetChild(c) c.SetChild(c)
return c return c
} }
// GetPayload 获取blackwhite action
func (b *BlackwhiteType) GetPayload() types.Message { func (b *BlackwhiteType) GetPayload() types.Message {
return &BlackwhiteAction{} return &BlackwhiteAction{}
} }
// GetName 获取执行器名称
func (b *BlackwhiteType) GetName() string { func (b *BlackwhiteType) GetName() string {
return BlackwhiteX return BlackwhiteX
} }
// GetLogMap 获取log的映射对应关系
func (b *BlackwhiteType) GetLogMap() map[int64]*types.LogInfo { func (b *BlackwhiteType) GetLogMap() map[int64]*types.LogInfo {
return logInfo return logInfo
} }
// GetTypeMap 根据action的name获取type
func (b *BlackwhiteType) GetTypeMap() map[string]int32 { func (b *BlackwhiteType) GetTypeMap() map[string]int32 {
return actionName return actionName
} }
func (m BlackwhiteType) ActionName(tx *types.Transaction) string { // ActionName 根据交易的payLoad获取blackwhite的action的name
func (b BlackwhiteType) ActionName(tx *types.Transaction) string {
var g BlackwhiteAction var g BlackwhiteAction
err := types.Decode(tx.Payload, &g) err := types.Decode(tx.Payload, &g)
if err != nil { if err != nil {
...@@ -70,20 +81,24 @@ func (m BlackwhiteType) ActionName(tx *types.Transaction) string { ...@@ -70,20 +81,24 @@ func (m BlackwhiteType) ActionName(tx *types.Transaction) string {
return "unkown" return "unkown"
} }
func (m BlackwhiteType) Amount(tx *types.Transaction) (int64, error) { // Amount ...
func (b BlackwhiteType) Amount(tx *types.Transaction) (int64, error) {
return 0, nil return 0, nil
} }
// CreateTx ...
// TODO 暂时不修改实现, 先完成结构的重构 // TODO 暂时不修改实现, 先完成结构的重构
func (m BlackwhiteType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) { func (b BlackwhiteType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) {
glog.Debug("Blackwhite.CreateTx", "action", action) glog.Debug("Blackwhite.CreateTx", "action", action)
var tx *types.Transaction var tx *types.Transaction
return tx, nil return tx, nil
} }
// BlackwhiteRoundInfo ...
type BlackwhiteRoundInfo struct { type BlackwhiteRoundInfo struct {
} }
// Input for convert struct
func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) {
var req ReqBlackwhiteRoundInfo var req ReqBlackwhiteRoundInfo
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -93,13 +108,16 @@ func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) { ...@@ -93,13 +108,16 @@ func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteRoundInfo) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteRoundInfo) Output(reply interface{}) (interface{}, error) {
return reply, nil return reply, nil
} }
// BlackwhiteByStatusAndAddr ...
type BlackwhiteByStatusAndAddr struct { type BlackwhiteByStatusAndAddr struct {
} }
// Input for convert struct
func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, error) {
var req ReqBlackwhiteRoundList var req ReqBlackwhiteRoundList
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -109,13 +127,16 @@ func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, erro ...@@ -109,13 +127,16 @@ func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, erro
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteByStatusAndAddr) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteByStatusAndAddr) Output(reply interface{}) (interface{}, error) {
return reply, nil return reply, nil
} }
// BlackwhiteloopResult ...
type BlackwhiteloopResult struct { type BlackwhiteloopResult struct {
} }
// Input for convert struct
func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) { func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) {
var req ReqLoopResult var req ReqLoopResult
err := json.Unmarshal(message, &req) err := json.Unmarshal(message, &req)
...@@ -125,6 +146,7 @@ func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) { ...@@ -125,6 +146,7 @@ func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil return types.Encode(&req), nil
} }
// Output for convert struct
func (t *BlackwhiteloopResult) Output(reply interface{}) (interface{}, error) { func (t *BlackwhiteloopResult) Output(reply interface{}) (interface{}, error) {
return reply, nil return reply, nil
} }
...@@ -22,6 +22,9 @@ func (c *Cert) ExecLocal_New(payload *ct.CertNew, tx *types.Transaction, receipt ...@@ -22,6 +22,9 @@ func (c *Cert) ExecLocal_New(payload *ct.CertNew, tx *types.Transaction, receipt
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.") clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority return nil, ct.ErrInitializeAuthority
} }
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet var set types.LocalDBSet
historityCertdata := &types.HistoryCertStore{} historityCertdata := &types.HistoryCertStore{}
...@@ -51,6 +54,9 @@ func (c *Cert) ExecLocal_Update(payload *ct.CertUpdate, tx *types.Transaction, r ...@@ -51,6 +54,9 @@ func (c *Cert) ExecLocal_Update(payload *ct.CertUpdate, tx *types.Transaction, r
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.") clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority return nil, ct.ErrInitializeAuthority
} }
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet var set types.LocalDBSet
// 写入上一纪录的next-height // 写入上一纪录的next-height
...@@ -81,6 +87,9 @@ func (c *Cert) ExecLocal_Normal(payload *ct.CertNormal, tx *types.Transaction, r ...@@ -81,6 +87,9 @@ func (c *Cert) ExecLocal_Normal(payload *ct.CertNormal, tx *types.Transaction, r
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.") clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority return nil, ct.ErrInitializeAuthority
} }
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet var set types.LocalDBSet
return &set, nil return &set, nil
......
...@@ -117,7 +117,7 @@ func (action *Action) GetIndex(game *gt.Game) int64 { ...@@ -117,7 +117,7 @@ func (action *Action) GetIndex(game *gt.Game) int64 {
//GetKVSet get kv set //GetKVSet get kv set
func (action *Action) GetKVSet(game *gt.Game) (kvset []*types.KeyValue) { func (action *Action) GetKVSet(game *gt.Game) (kvset []*types.KeyValue) {
value := types.Encode(game) value := types.Encode(game)
kvset = append(kvset, &types.KeyValue{Key(game.GameId), value}) kvset = append(kvset, &types.KeyValue{Key: Key(game.GameId), Value: value})
return kvset return kvset
} }
...@@ -126,7 +126,7 @@ func (action *Action) updateCount(status int32, addr string) (kvset []*types.Key ...@@ -126,7 +126,7 @@ func (action *Action) updateCount(status int32, addr string) (kvset []*types.Key
if err != nil { if err != nil {
glog.Error("updateCount", "Query count have err:", err.Error()) glog.Error("updateCount", "Query count have err:", err.Error())
} }
kvset = append(kvset, &types.KeyValue{calcCountKey(status, addr), []byte(strconv.FormatInt(count+1, 10))}) kvset = append(kvset, &types.KeyValue{Key: calcCountKey(status, addr), Value: []byte(strconv.FormatInt(count+1, 10))})
return kvset return kvset
} }
...@@ -231,7 +231,7 @@ func (action *Action) GameCreate(create *gt.GameCreate) (*types.Receipt, error) ...@@ -231,7 +231,7 @@ func (action *Action) GameCreate(create *gt.GameCreate) (*types.Receipt, error)
kv = append(kv, receipt.KV...) kv = append(kv, receipt.KV...)
kv = append(kv, action.updateCount(game.GetStatus(), "")...) kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...) kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
receipt = &types.Receipt{types.ExecOk, kv, logs} receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil return receipt, nil
} }
...@@ -286,7 +286,7 @@ func (action *Action) GameMatch(match *gt.GameMatch) (*types.Receipt, error) { ...@@ -286,7 +286,7 @@ func (action *Action) GameMatch(match *gt.GameMatch) (*types.Receipt, error) {
kvs = append(kvs, action.updateCount(game.GetStatus(), "")...) kvs = append(kvs, action.updateCount(game.GetStatus(), "")...)
kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetCreateAddress())...) kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetMatchAddress())...) kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetMatchAddress())...)
receipts := &types.Receipt{types.ExecOk, kvs, logs} receipts := &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}
return receipts, nil return receipts, nil
} }
...@@ -338,7 +338,7 @@ func (action *Action) GameCancel(cancel *gt.GameCancel) (*types.Receipt, error) ...@@ -338,7 +338,7 @@ func (action *Action) GameCancel(cancel *gt.GameCancel) (*types.Receipt, error)
kv = append(kv, action.updateCount(game.GetStatus(), "")...) kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...) kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
// GameClose close game // GameClose close game
...@@ -480,7 +480,7 @@ func (action *Action) GameClose(close *gt.GameClose) (*types.Receipt, error) { ...@@ -480,7 +480,7 @@ func (action *Action) GameClose(close *gt.GameClose) (*types.Receipt, error) {
kv = append(kv, action.updateCount(game.GetStatus(), "")...) kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...) kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetMatchAddress())...) kv = append(kv, action.updateCount(game.GetStatus(), game.GetMatchAddress())...)
return &types.Receipt{types.ExecOk, kv, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
} }
// 检查开奖是否超时,若超过一天,则不让庄家开奖,但其他人可以开奖, // 检查开奖是否超时,若超过一天,则不让庄家开奖,但其他人可以开奖,
...@@ -602,7 +602,7 @@ func queryGameListByStatusAndAddr(db dbm.Lister, stateDB dbm.KV, param *gt.Query ...@@ -602,7 +602,7 @@ func queryGameListByStatusAndAddr(db dbm.Lister, stateDB dbm.KV, param *gt.Query
} }
gameIds = append(gameIds, record.GetGameId()) gameIds = append(gameIds, record.GetGameId())
} }
return &gt.ReplyGameList{GetGameList(stateDB, gameIds)}, nil return &gt.ReplyGameList{Games: GetGameList(stateDB, gameIds)}, nil
} }
// QueryGameListCount count数查询 // QueryGameListCount count数查询
...@@ -610,7 +610,7 @@ func QueryGameListCount(stateDB dbm.KV, param *gt.QueryGameListCount) (types.Mes ...@@ -610,7 +610,7 @@ func QueryGameListCount(stateDB dbm.KV, param *gt.QueryGameListCount) (types.Mes
if param.Status < 1 || param.Status > 4 { if param.Status < 1 || param.Status > 4 {
return nil, fmt.Errorf("%s", "the status only fill in 1,2,3,4!") return nil, fmt.Errorf("%s", "the status only fill in 1,2,3,4!")
} }
return &gt.ReplyGameListCount{QueryCountByStatusAndAddr(stateDB, param.GetStatus(), param.GetAddress())}, nil return &gt.ReplyGameListCount{Count: QueryCountByStatusAndAddr(stateDB, param.GetStatus(), param.GetAddress())}, nil
} }
// QueryCountByStatusAndAddr query game count by status and addr // QueryCountByStatusAndAddr query game count by status and addr
......
...@@ -30,5 +30,5 @@ func (g *Game) Query_QueryGameById(in *gt.QueryGameInfo) (types.Message, error) ...@@ -30,5 +30,5 @@ func (g *Game) Query_QueryGameById(in *gt.QueryGameInfo) (types.Message, error)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &gt.ReplyGame{game}, nil return &gt.ReplyGame{Game: game}, nil
} }
...@@ -45,7 +45,7 @@ type GameType struct { ...@@ -45,7 +45,7 @@ type GameType struct {
// GetLogMap get log // GetLogMap get log
func (gt *GameType) GetLogMap() map[int64]*types.LogInfo { func (gt *GameType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{ return map[int64]*types.LogInfo{
TyLogCreateGame: {reflect.TypeOf(ReceiptGame{}), "LogLotteryCreate"}, TyLogCreateGame: {reflect.TypeOf(ReceiptGame{}), "LogCreateGame"},
TyLogCancleGame: {reflect.TypeOf(ReceiptGame{}), "LogCancleGame"}, TyLogCancleGame: {reflect.TypeOf(ReceiptGame{}), "LogCancleGame"},
TyLogMatchGame: {reflect.TypeOf(ReceiptGame{}), "LogMatchGame"}, TyLogMatchGame: {reflect.TypeOf(ReceiptGame{}), "LogMatchGame"},
TyLogCloseGame: {reflect.TypeOf(ReceiptGame{}), "LogCloseGame"}, TyLogCloseGame: {reflect.TypeOf(ReceiptGame{}), "LogCloseGame"},
......
...@@ -12,6 +12,9 @@ import ( ...@@ -12,6 +12,9 @@ import (
// ExecDelLocal_Hlock Action // ExecDelLocal_Hlock Action
func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0} info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info) kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info)
if err != nil { if err != nil {
...@@ -22,6 +25,9 @@ func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transac ...@@ -22,6 +25,9 @@ func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transac
// ExecDelLocal_Hsend Action // ExecDelLocal_Hsend Action
func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0} info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info) kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info)
if err != nil { if err != nil {
...@@ -32,6 +38,9 @@ func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transac ...@@ -32,6 +38,9 @@ func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transac
// ExecDelLocal_Hunlock Action // ExecDelLocal_Hunlock Action
func (h *Hashlock) ExecDelLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecDelLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0} info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info) kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info)
if err != nil { if err != nil {
......
...@@ -12,6 +12,9 @@ import ( ...@@ -12,6 +12,9 @@ import (
// ExecLocal_Hlock Action // ExecLocal_Hlock Action
func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0} info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0}
clog.Error("ExecLocal", "info", info) clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info) kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info)
...@@ -23,6 +26,9 @@ func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transactio ...@@ -23,6 +26,9 @@ func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transactio
// ExecLocal_Hsend Action // ExecLocal_Hsend Action
func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0} info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0}
clog.Error("ExecLocal", "info", info) clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info) kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info)
...@@ -34,6 +40,9 @@ func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transactio ...@@ -34,6 +40,9 @@ func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transactio
// ExecLocal_Hunlock Action // ExecLocal_Hunlock Action
func (h *Hashlock) ExecLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (h *Hashlock) ExecLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0} info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0}
clog.Error("ExecLocal", "info", info) clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info) kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info)
......
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package init package init
import ( import (
......
...@@ -43,20 +43,20 @@ func (l *Lottery) execDelLocal(tx *types.Transaction, receiptData *types.Receipt ...@@ -43,20 +43,20 @@ func (l *Lottery) execDelLocal(tx *types.Transaction, receiptData *types.Receipt
// ExecDelLocal_Create Action // ExecDelLocal_Create Action
func (l *Lottery) ExecDelLocal_Create(payload *pty.LotteryCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (l *Lottery) ExecDelLocal_Create(payload *pty.LotteryCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return l.execDelLocal(tx, receiptData)
} }
// ExecDelLocal_Buy Action // ExecDelLocal_Buy Action
func (l *Lottery) ExecDelLocal_Buy(payload *pty.LotteryBuy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (l *Lottery) ExecDelLocal_Buy(payload *pty.LotteryBuy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return l.execDelLocal(tx, receiptData)
} }
// ExecDelLocal_Draw Action // ExecDelLocal_Draw Action
func (l *Lottery) ExecDelLocal_Draw(payload *pty.LotteryDraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (l *Lottery) ExecDelLocal_Draw(payload *pty.LotteryDraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return l.execDelLocal(tx, receiptData)
} }
// ExecDelLocal_Close Action // ExecDelLocal_Close Action
func (l *Lottery) ExecDelLocal_Close(payload *pty.LotteryClose, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (l *Lottery) ExecDelLocal_Close(payload *pty.LotteryClose, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return l.execDelLocal(tx, receiptData)
} }
...@@ -16,6 +16,7 @@ import ( ...@@ -16,6 +16,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
//ParcCmd paracross cmd register
func ParcCmd() *cobra.Command { func ParcCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "para", Use: "para",
...@@ -32,7 +33,7 @@ func ParcCmd() *cobra.Command { ...@@ -32,7 +33,7 @@ func ParcCmd() *cobra.Command {
return cmd return cmd
} }
// create raw asset transfer tx // CreateRawAssetTransferCmd create raw asset transfer tx
func CreateRawAssetTransferCmd() *cobra.Command { func CreateRawAssetTransferCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "asset_transfer", Use: "asset_transfer",
...@@ -67,7 +68,7 @@ func createAssetTransfer(cmd *cobra.Command, args []string) { ...@@ -67,7 +68,7 @@ func createAssetTransfer(cmd *cobra.Command, args []string) {
fmt.Println(txHex) fmt.Println(txHex)
} }
// create raw asset withdraw tx // CreateRawAssetWithdrawCmd create raw asset withdraw tx
func CreateRawAssetWithdrawCmd() *cobra.Command { func CreateRawAssetWithdrawCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "asset_withdraw", Use: "asset_withdraw",
...@@ -139,7 +140,7 @@ func createAssetTx(cmd *cobra.Command, isWithdraw bool) (string, error) { ...@@ -139,7 +140,7 @@ func createAssetTx(cmd *cobra.Command, isWithdraw bool) (string, error) {
return hex.EncodeToString(txHex), nil return hex.EncodeToString(txHex), nil
} }
// create raw transfer tx //CreateRawTransferCmd create raw transfer tx
func CreateRawTransferCmd() *cobra.Command { func CreateRawTransferCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "transfer", Use: "transfer",
...@@ -174,7 +175,7 @@ func createTransfer(cmd *cobra.Command, args []string) { ...@@ -174,7 +175,7 @@ func createTransfer(cmd *cobra.Command, args []string) {
fmt.Println(txHex) fmt.Println(txHex)
} }
// create raw transfer to exec tx //CreateRawTransferToExecCmd create raw transfer to exec tx
func CreateRawTransferToExecCmd() *cobra.Command { func CreateRawTransferToExecCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "transfer_exec", Use: "transfer_exec",
...@@ -209,7 +210,7 @@ func createTransferToExec(cmd *cobra.Command, args []string) { ...@@ -209,7 +210,7 @@ func createTransferToExec(cmd *cobra.Command, args []string) {
fmt.Println(txHex) fmt.Println(txHex)
} }
// create raw withdraw tx //CreateRawWithdrawCmd create raw withdraw tx
func CreateRawWithdrawCmd() *cobra.Command { func CreateRawWithdrawCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "withdraw", Use: "withdraw",
......
...@@ -13,6 +13,7 @@ import ( ...@@ -13,6 +13,7 @@ import (
// 注: 在计算帐号地址时, 平行链paracross合约地址需要带上title前缀,才能表现出和主链一致, 但是现在不带, // 注: 在计算帐号地址时, 平行链paracross合约地址需要带上title前缀,才能表现出和主链一致, 但是现在不带,
//NewParaAccount create new paracross account
// 其中带{}, 都表示变量, 用需要用真实的地址, 符号代替 // 其中带{}, 都表示变量, 用需要用真实的地址, 符号代替
// 构建主链资产在平行链paracross帐号 // 构建主链资产在平行链paracross帐号
// execName: user.p.{guodun}.paracross // execName: user.p.{guodun}.paracross
...@@ -28,6 +29,7 @@ func NewParaAccount(paraTitle, mainExecName, mainSymbol string, db db.KV) (*acco ...@@ -28,6 +29,7 @@ func NewParaAccount(paraTitle, mainExecName, mainSymbol string, db db.KV) (*acco
return account.NewAccountDB(paraExec, paraSymbol, db) return account.NewAccountDB(paraExec, paraSymbol, db)
} }
//NewMainAccount create new Main account
// 以后如果支持从平行链资产转移到主链, 构建平行链资产在主链的paracross帐号 // 以后如果支持从平行链资产转移到主链, 构建平行链资产在主链的paracross帐号
// execName: paracross // execName: paracross
// symbol: user.p.{guodun}.coins.{guodun} user.p.{guodun}.token.{TEST} // symbol: user.p.{guodun}.coins.{guodun} user.p.{guodun}.token.{TEST}
......
...@@ -448,7 +448,7 @@ func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) { ...@@ -448,7 +448,7 @@ func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) {
log.Log = types.Encode(receipt) log.Log = types.Encode(receipt)
logs = append(logs, log) logs = append(logs, log)
return &types.Receipt{types.ExecOk, nil, logs}, nil return &types.Receipt{Ty: types.ExecOk, KV: nil, Logs: logs}, nil
} }
......
...@@ -30,24 +30,24 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, ...@@ -30,24 +30,24 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt,
clog.Debug("paracross.AssetTransfer not isPara", "execer", string(a.tx.Execer), clog.Debug("paracross.AssetTransfer not isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash())) "txHash", common.Bytes2Hex(a.tx.Hash()))
return accDB.ExecTransfer(a.fromaddr, toAddr, execAddr, transfer.Amount) return accDB.ExecTransfer(a.fromaddr, toAddr, execAddr, transfer.Amount)
}
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if transfer.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else { } else {
paraTitle, err := getTitleFrom(a.tx.Execer) paraAcc, err = NewParaAccount(string(paraTitle), "token", transfer.Cointoken, a.db)
if err != nil { }
return nil, errors.Wrap(err, "assetTransferCoins call getTitleFrom failed") if err != nil {
} return nil, errors.Wrap(err, "assetTransferCoins call NewParaAccount failed")
var paraAcc *account.DB
if transfer.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraAcc, err = NewParaAccount(string(paraTitle), "token", transfer.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call NewParaAccount failed")
}
clog.Debug("paracross.AssetTransfer isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetDepositBalance(paraAcc, transfer.To, transfer.Amount)
} }
clog.Debug("paracross.AssetTransfer isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetDepositBalance(paraAcc, transfer.To, transfer.Amount)
} }
func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types.Transaction) (*types.Receipt, error) { func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types.Transaction) (*types.Receipt, error) {
...@@ -62,24 +62,24 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types ...@@ -62,24 +62,24 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types
clog.Debug("Paracross.Exec", "AssettWithdraw", withdraw.Amount, "from", fromAddr, clog.Debug("Paracross.Exec", "AssettWithdraw", withdraw.Amount, "from", fromAddr,
"to", withdraw.To, "exec", execAddr, "withdrawTx execor", string(withdrawTx.Execer)) "to", withdraw.To, "exec", execAddr, "withdrawTx execor", string(withdrawTx.Execer))
return accDB.ExecTransfer(fromAddr, withdraw.To, execAddr, withdraw.Amount) return accDB.ExecTransfer(fromAddr, withdraw.To, execAddr, withdraw.Amount)
}
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if withdraw.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else { } else {
paraTitle, err := getTitleFrom(a.tx.Execer) paraAcc, err = NewParaAccount(string(paraTitle), "token", withdraw.Cointoken, a.db)
if err != nil { }
return nil, errors.Wrap(err, "assetWithdrawCoins call getTitleFrom failed") if err != nil {
} return nil, errors.Wrap(err, "assetWithdrawCoins call NewParaAccount failed")
var paraAcc *account.DB
if withdraw.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraAcc, err = NewParaAccount(string(paraTitle), "token", withdraw.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call NewParaAccount failed")
}
clog.Debug("paracross.assetWithdrawCoins isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetWithdrawBalance(paraAcc, a.fromaddr, withdraw.Amount)
} }
clog.Debug("paracross.assetWithdrawCoins isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetWithdrawBalance(paraAcc, a.fromaddr, withdraw.Amount)
} }
func createAccount(db db.KV, symbol string) (*account.DB, error) { func createAccount(db db.KV, symbol string) (*account.DB, error) {
......
...@@ -83,13 +83,13 @@ func (suite *AssetTransferTestSuite) SetupTest() { ...@@ -83,13 +83,13 @@ func (suite *AssetTransferTestSuite) SetupTest() {
saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus) saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus)
// setup api // setup api
hashes := &types.ReqHashes{[][]byte{MainBlockHash10}} hashes := &types.ReqHashes{Hashes: [][]byte{MainBlockHash10}}
suite.api.On("GetBlockByHashes", hashes).Return( suite.api.On("GetBlockByHashes", hashes).Return(
&types.BlockDetails{ &types.BlockDetails{
Items: []*types.BlockDetail{blockDetail}, Items: []*types.BlockDetail{blockDetail},
}, nil) }, nil)
suite.api.On("GetBlockHash", &types.ReqInt{MainBlockHeight}).Return( suite.api.On("GetBlockHash", &types.ReqInt{Height: MainBlockHeight}).Return(
&types.ReplyHash{MainBlockHash10}, nil) &types.ReplyHash{Hash: MainBlockHash10}, nil)
} }
func (suite *AssetTransferTestSuite) TestExecTransferNobalance() { func (suite *AssetTransferTestSuite) TestExecTransferNobalance() {
......
...@@ -78,13 +78,13 @@ func (suite *AssetWithdrawTestSuite) SetupTest() { ...@@ -78,13 +78,13 @@ func (suite *AssetWithdrawTestSuite) SetupTest() {
saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus) saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus)
// setup api // setup api
hashes := &types.ReqHashes{[][]byte{MainBlockHash10}} hashes := &types.ReqHashes{Hashes: [][]byte{MainBlockHash10}}
suite.api.On("GetBlockByHashes", hashes).Return( suite.api.On("GetBlockByHashes", hashes).Return(
&types.BlockDetails{ &types.BlockDetails{
Items: []*types.BlockDetail{blockDetail}, Items: []*types.BlockDetail{blockDetail},
}, nil) }, nil)
suite.api.On("GetBlockHash", &types.ReqInt{MainBlockHeight}).Return( suite.api.On("GetBlockHash", &types.ReqInt{Height: MainBlockHeight}).Return(
&types.ReplyHash{MainBlockHash10}, nil) &types.ReplyHash{Hash: MainBlockHash10}, nil)
} }
// 主链先不执行 // 主链先不执行
......
...@@ -53,8 +53,9 @@ func saveTitleHeight(db dbm.KV, key []byte, heightStatus types.Message /* height ...@@ -53,8 +53,9 @@ func saveTitleHeight(db dbm.KV, key []byte, heightStatus types.Message /* height
return db.Set(key, val) return db.Set(key, val)
} }
//GetBlock get block detail by block hash
func GetBlock(api client.QueueProtocolAPI, blockHash []byte) (*types.BlockDetail, error) { func GetBlock(api client.QueueProtocolAPI, blockHash []byte) (*types.BlockDetail, error) {
blockDetails, err := api.GetBlockByHashes(&types.ReqHashes{[][]byte{blockHash}}) blockDetails, err := api.GetBlockByHashes(&types.ReqHashes{Hashes: [][]byte{blockHash}})
if err != nil { if err != nil {
clog.Error("paracross.Commit getBlockHeader", "db", err, clog.Error("paracross.Commit getBlockHeader", "db", err,
"commit tx hash", common.Bytes2Hex(blockHash)) "commit tx hash", common.Bytes2Hex(blockHash))
...@@ -88,8 +89,9 @@ func isNotFound(err error) bool { ...@@ -88,8 +89,9 @@ func isNotFound(err error) bool {
return false return false
} }
//GetTx get tx by tx hash
func GetTx(api client.QueueProtocolAPI, txHash []byte) (*types.TransactionDetail, error) { func GetTx(api client.QueueProtocolAPI, txHash []byte) (*types.TransactionDetail, error) {
txs, err := api.GetTransactionByHash(&types.ReqHashes{[][]byte{txHash}}) txs, err := api.GetTransactionByHash(&types.ReqHashes{Hashes: [][]byte{txHash}})
if err != nil { if err != nil {
clog.Error("paracross.Commit GetTx", "db", err, clog.Error("paracross.Commit GetTx", "db", err,
"commit tx hash", common.Bytes2Hex(txHash)) "commit tx hash", common.Bytes2Hex(txHash))
......
...@@ -11,6 +11,7 @@ import ( ...@@ -11,6 +11,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
) )
//Exec_Commit consensus commit tx exec process
func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx) a := newAction(e, tx)
receipt, err := a.Commit(payload) receipt, err := a.Commit(payload)
...@@ -21,6 +22,7 @@ func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Tra ...@@ -21,6 +22,7 @@ func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Tra
return receipt, nil return receipt, nil
} }
//Exec_AssetTransfer asset transfer exec process
func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) {
clog.Debug("Paracross.Exec", "transfer", "") clog.Debug("Paracross.Exec", "transfer", "")
_, err := e.checkTxGroup(tx, index) _, err := e.checkTxGroup(tx, index)
...@@ -37,6 +39,7 @@ func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types. ...@@ -37,6 +39,7 @@ func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.
return receipt, nil return receipt, nil
} }
//Exec_AssetWithdraw asset withdraw exec process
func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) {
clog.Debug("Paracross.Exec", "withdraw", "") clog.Debug("Paracross.Exec", "withdraw", "")
_, err := e.checkTxGroup(tx, index) _, err := e.checkTxGroup(tx, index)
...@@ -53,6 +56,7 @@ func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types. ...@@ -53,6 +56,7 @@ func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.
return receipt, nil return receipt, nil
} }
//Exec_Miner miner tx exec process
func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, index int) (*types.Receipt, error) {
if index != 0 { if index != 0 {
return nil, pt.ErrParaMinerBaseIndex return nil, pt.ErrParaMinerBaseIndex
...@@ -64,16 +68,19 @@ func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Trans ...@@ -64,16 +68,19 @@ func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Trans
return a.Miner(payload) return a.Miner(payload)
} }
//Exec_Transfer exec asset transfer process
func (e *Paracross) Exec_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx) a := newAction(e, tx)
return a.Transfer(payload, tx, index) return a.Transfer(payload, tx, index)
} }
//Exec_Withdraw exec asset withdraw
func (e *Paracross) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx) a := newAction(e, tx)
return a.Withdraw(payload, tx, index) return a.Withdraw(payload, tx, index)
} }
//Exec_TransferToExec exec transfer asset
func (e *Paracross) Exec_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, index int) (*types.Receipt, error) { func (e *Paracross) Exec_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx) a := newAction(e, tx)
return a.TransferToExec(payload, tx, index) return a.TransferToExec(payload, tx, index)
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
pt "github.com/33cn/plugin/plugin/dapp/paracross/types" pt "github.com/33cn/plugin/plugin/dapp/paracross/types"
) )
//ExecDelLocal_Commit consensus commit tx del local db process
func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
var set types.LocalDBSet var set types.LocalDBSet
for _, log := range receiptData.Logs { for _, log := range receiptData.Logs {
...@@ -18,17 +19,17 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t ...@@ -18,17 +19,17 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t
var r pt.ParacrossTx var r pt.ParacrossTx
r.TxHash = string(tx.Hash()) r.TxHash = string(tx.Hash())
set.KV = append(set.KV, &types.KeyValue{calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), nil}) set.KV = append(set.KV, &types.KeyValue{Key: calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), Value: nil})
} else if log.Ty == pt.TyLogParacrossCommitDone { } else if log.Ty == pt.TyLogParacrossCommitDone {
var g pt.ReceiptParacrossDone var g pt.ReceiptParacrossDone
types.Decode(log.Log, &g) types.Decode(log.Log, &g)
g.Height = g.Height - 1 g.Height = g.Height - 1
key := calcLocalTitleKey(g.Title) key := calcLocalTitleKey(g.Title)
set.KV = append(set.KV, &types.KeyValue{key, types.Encode(&g)}) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: types.Encode(&g)})
key = calcLocalHeightKey(g.Title, g.Height) key = calcLocalHeightKey(g.Title, g.Height)
set.KV = append(set.KV, &types.KeyValue{key, nil}) set.KV = append(set.KV, &types.KeyValue{Key: key, Value: nil})
r, err := e.saveLocalParaTxs(tx, true) r, err := e.saveLocalParaTxs(tx, true)
if err != nil { if err != nil {
...@@ -41,12 +42,13 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t ...@@ -41,12 +42,13 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t
var r pt.ParacrossTx var r pt.ParacrossTx
r.TxHash = string(tx.Hash()) r.TxHash = string(tx.Hash())
set.KV = append(set.KV, &types.KeyValue{calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), nil}) set.KV = append(set.KV, &types.KeyValue{Key: calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), Value: nil})
} }
} }
return &set, nil return &set, nil
} }
//ExecDelLocal_AssetTransfer asset transfer del local db process
func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
var set types.LocalDBSet var set types.LocalDBSet
...@@ -61,29 +63,34 @@ func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx ...@@ -61,29 +63,34 @@ func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx
return &set, nil return &set, nil
} }
//ExecDelLocal_AssetWithdraw asset withdraw local db process
func (e *Paracross) ExecDelLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return nil, nil
} }
//ExecDelLocal_Miner miner tx del local db process
func (e *Paracross) ExecDelLocal_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if index != 0 { if index != 0 {
return nil, pt.ErrParaMinerBaseIndex return nil, pt.ErrParaMinerBaseIndex
} }
var set types.LocalDBSet var set types.LocalDBSet
set.KV = append(set.KV, &types.KeyValue{pt.CalcMinerHeightKey(payload.Status.Title, payload.Status.Height), nil}) set.KV = append(set.KV, &types.KeyValue{Key: pt.CalcMinerHeightKey(payload.Status.Title, payload.Status.Height), Value: nil})
return &set, nil return &set, nil
} }
//ExecDelLocal_Transfer asset transfer del local process
func (e *Paracross) ExecDelLocal_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return nil, nil
} }
//ExecDelLocal_Withdraw asset withdraw del local db process
func (e *Paracross) ExecDelLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return nil, nil
} }
//ExecDelLocal_TransferToExec asset transfer to exec del local db process
func (e *Paracross) ExecDelLocal_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (e *Paracross) ExecDelLocal_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil return nil, nil
} }
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment