add errors and test helpers

This commit is contained in:
zelig 2015-01-14 06:25:43 +00:00
parent 79b046cb0f
commit 3a4ee8c732
2 changed files with 113 additions and 0 deletions

62
bzz/error.go Normal file
View file

@ -0,0 +1,62 @@
package bzz
import (
"fmt"
)
const (
ErrMsgTooLarge = iota
ErrDecode
ErrInvalidMsgCode
ErrVersionMismatch
ErrNetworkIdMismatch
ErrNoStatusMsg
ErrExtraStatusMsg
)
var errorToString = map[int]string{
ErrMsgTooLarge: "Message too long",
ErrDecode: "Invalid message",
ErrInvalidMsgCode: "Invalid message code",
ErrVersionMismatch: "Protocol version mismatch",
ErrNetworkIdMismatch: "NetworkId mismatch",
ErrNoStatusMsg: "No status message",
ErrExtraStatusMsg: "Extra status message",
}
type protocolError struct {
Code int
fatal bool
message string
format string
params []interface{}
// size int
}
func newProtocolError(code int, format string, params ...interface{}) *protocolError {
return &protocolError{Code: code, format: format, params: params}
}
func ProtocolError(code int, format string, params ...interface{}) (err *protocolError) {
err = newProtocolError(code, format, params...)
// report(err)
return
}
func (self protocolError) Error() (message string) {
if len(message) == 0 {
var ok bool
self.message, ok = errorToString[self.Code]
if !ok {
panic("invalid error code")
}
if self.format != "" {
self.message += ": " + fmt.Sprintf(self.format, self.params...)
}
}
return self.message
}
func (self *protocolError) Fatal() bool {
return self.fatal
}

51
bzz/protocol_test.go Normal file
View file

@ -0,0 +1,51 @@
package bzz
import (
"fmt"
"testing"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p"
)
type peerId struct {
pubkey []byte
}
func (self *peerId) String() string {
return fmt.Sprintf("test peer %x", self.Pubkey()[:4])
}
func (self *peerId) Pubkey() (pubkey []byte) {
pubkey = self.pubkey
if len(pubkey) == 0 {
pubkey = crypto.GenerateNewKeyPair().PublicKey
self.pubkey = pubkey
}
return
}
func newTestPeer() (peer *p2p.Peer) {
// peer = NewPeer(&peerId{}, []p2p.Cap{})
// peer.pubkeyHook = func(*peerAddr) error { return nil }
// peer.ourID = &peerId{}
// peer.listenAddr = &peerAddr{}
// peer.otherPeers = func() []*Peer { return nil }
return
}
func expectMsg(r p2p.MsgReader, code uint64) error {
msg, err := r.ReadMsg()
if err != nil {
return err
}
if err := msg.Discard(); err != nil {
return err
}
if msg.Code != code {
return fmt.Errorf("wrong message code: got %d, expected %d", msg.Code, code)
}
return nil
}
func Test(t *testing.T) {}