Example #1
0
func TestGivePeersMessage(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	addrs := []string{addr, addrb, "7"}
	peers := make([]*pex.Peer, 3)
	for i, addr := range addrs {
		peers[i] = &pex.Peer{Addr: addr}
	}
	m := NewGivePeersMessage(peers)
	assert.Equal(t, len(m.GetPeers()), 2)
	testSimpleMessageHandler(t, d, m)
	assert.Equal(t, m.GetPeers()[0], addrs[0])
	assert.Equal(t, m.GetPeers()[1], addrs[1])

	// Test disabled
	d.Peers.Config.Disabled = true
	m.Process(d)
	assert.Equal(t, len(d.Peers.Peers.Peerlist), 0)

	// Test serialization
	m = NewGivePeersMessage(peers)
	b := encoder.Serialize(m)
	m2 := GivePeersMessage{}
	assert.Nil(t, encoder.DeserializeRaw(b, &m2))
	assert.Equal(t, *m, m2)

	// Peers should be added to the pex when processed
	d.Peers.Config.Disabled = false
	m.Process(d)
	assert.Equal(t, len(d.Peers.Peers.Peerlist), 2)
	gnet.EraseMessages()
}
Example #2
0
func TestPingMessage(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	p := d.Pool.Pool
	m := &PingMessage{}
	testSimpleMessageHandler(t, d, m)

	m.c = messageContext(addr)
	go p.ConnectionWriteLoop(m.c.Conn)
	defer m.c.Conn.Close()
	assert.NotPanics(t, func() { m.Process(d) })
	// A pong message should have been sent
	wait()
	assert.Equal(t, len(p.SendResults), 1)
	if len(p.SendResults) == 0 {
		t.Fatalf("SendResults empty, would block")
	}
	sr := <-p.SendResults
	assert.Equal(t, sr.Connection, m.c.Conn)
	assert.Nil(t, sr.Error)
	_, ok := sr.Message.(*PongMessage)
	assert.True(t, ok)
	assert.False(t, m.c.Conn.LastSent.IsZero())

	// Test serialization
	mm := PingMessage{}
	b := encoder.Serialize(mm)
	m2 := PingMessage{}
	assert.Nil(t, encoder.DeserializeRaw(b, &m2))
	assert.Equal(t, mm, m2)

	gnet.EraseMessages()
}
Example #3
0
func TestGetPeersMessage(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	p := d.Pool
	m := NewGetPeersMessage()
	testSimpleMessageHandler(t, d, m)
	d.Peers.Peers.AddPeer(addr)
	q, err := d.Peers.Peers.AddPeer(addrb)
	assert.Nil(t, err)
	q.Private = true
	d.Peers.Config.ReplyCount = 100
	m.c = messageContext(addr)

	// Peers disabled
	d.Peers.Config.Disabled = true
	assert.NotPanics(t, func() { m.Process(d) })
	wait()
	assert.Equal(t, len(p.Pool.SendResults), 0)
	assert.True(t, m.c.Conn.LastSent.IsZero())

	// Peers enabled
	d.Peers.Config.Disabled = false
	m.c = messageContext(addr)
	defer m.c.Conn.Close()
	go p.Pool.ConnectionWriteLoop(m.c.Conn)
	assert.NotPanics(t, func() { m.Process(d) })
	wait()
	assert.Equal(t, len(p.Pool.SendResults), 1)
	if len(p.Pool.SendResults) == 0 {
		t.Fatal("SendResults empty, would block")
	}
	sr := <-p.Pool.SendResults
	assert.Nil(t, sr.Error)
	assert.Equal(t, sr.Connection, m.c.Conn)
	msg, ok := sr.Message.(*GivePeersMessage)
	assert.True(t, ok)
	// Private peer should not be included
	ipAddr, err := NewIPAddr(addr)
	assert.Nil(t, err)
	assert.Equal(t, msg.Peers, []IPAddr{ipAddr})
	assert.False(t, m.c.Conn.LastSent.IsZero())

	// If no peers, nothing should happen
	m.c.Conn.LastSent = util.ZeroTime()
	delete(d.Peers.Peers.Peerlist, addr)
	assert.NotPanics(t, func() { m.Process(d) })
	wait()
	assert.Equal(t, len(p.Pool.SendResults), 0)
	assert.True(t, m.c.Conn.LastSent.IsZero())

	// Test serialization
	m = NewGetPeersMessage()
	b := encoder.Serialize(m)
	m2 := GetPeersMessage{}
	assert.Nil(t, encoder.DeserializeRaw(b, &m2))
	assert.Equal(t, *m, m2)

	gnet.EraseMessages()
}
Example #4
0
func Serialize(prefix uint16, obj interface{}) []byte {
	b := encoder.Serialize(obj)
	var b1 []byte = make([]byte, 2)
	b1[0] = (uint8)(prefix & 0x00ff)
	b1[1] = (uint8)((prefix & 0xff00) >> 8)
	b2 := append(b1, b...)
	return b2
}
Example #5
0
// May block
func (s *UDPTransport) SendMessage(toPeer cipher.PubKey, contents []byte, retChan chan error) error {
	var retErr error = nil
	// Find pubkey
	peerComm, found := s.safeGetPeerComm(toPeer)
	if !found {
		retErr = errors.New(fmt.Sprintf("Dropping message that is to an unknown peer: %v\n", toPeer))
		if retChan != nil {
			retChan <- retErr
		}
		return retErr
	}

	// Check length
	if len(contents) > int(peerComm.DatagramLength) {
		retErr = errors.New(fmt.Sprintf("Dropping message that is too large: %v > %v\n", len(contents), s.config.DatagramLength))
		if retChan != nil {
			retChan <- retErr
		}
		return retErr
	}

	// Pad to length
	encoderBuffer := encoder.Serialize(contents)
	datagramBuffer := make([]byte, peerComm.DatagramLength)
	copy(datagramBuffer, encoderBuffer)

	// Apply crypto
	if s.crypto != nil {
		datagramBuffer = s.crypto.Encrypt(datagramBuffer, peerComm.CryptoKey)
	}

	// Choose a socket randomly
	conn := s.listenPort.conn

	// Send datagram
	toAddr := peerComm.ExternalHost

	n, err := conn.WriteToUDP(datagramBuffer, &toAddr)
	if err != nil {
		retErr = errors.New(fmt.Sprintf("Error on WriteToUDP: %v\n", err))
		if retChan != nil {
			retChan <- retErr
		}
		return retErr
	}
	if n != int(peerComm.DatagramLength) {
		retErr = errors.New(fmt.Sprintf("WriteToUDP returned %v != %v\n", n, peerComm.DatagramLength))
		if retChan != nil {
			retChan <- retErr
		}
		return retErr
	}
	if retChan != nil {
		retChan <- nil
	}
	return nil
}
Example #6
0
func TestBlockBodySize(t *testing.T) {
	b := makeNewBlock()
	addTransactionToBlock(t, &b)
	assert.Equal(t, b.Size(), b.Body.Size())
	assert.Equal(t, b.Body.Size(), b.Body.Transactions.Size())
	size := 0
	for _, x := range b.Body.Transactions {
		size += len(encoder.Serialize(&x))
	}
	assert.NotEqual(t, size, 0)
	assert.Equal(t, b.Size(), size)
}
Example #7
0
func TestIntroductionMessageHandle(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	mc := messageContext(addr)
	m := NewIntroductionMessage(d.Messages.Mirror, d.Config.Version,
		d.Pool.Pool.Config.Port)

	// Test valid handling
	m.Mirror = d.Messages.Mirror + 1
	err := m.Handle(mc, d)
	assert.Nil(t, err)
	if len(d.messageEvents) == 0 {
		t.Fatalf("messageEvent is empty")
	}
	<-d.messageEvents
	assert.True(t, m.valid)
	m.valid = false

	// Test matching mirror
	m.Mirror = d.Messages.Mirror
	err = m.Handle(mc, d)
	assert.Equal(t, err, DisconnectSelf)
	m.Mirror = d.Messages.Mirror + 1
	assert.False(t, m.valid)

	// Test mismatched d.Config.Version
	m.Version = d.Config.Version + 1
	err = m.Handle(mc, d)
	assert.Equal(t, err, DisconnectInvalidVersion)
	assert.False(t, m.valid)

	// Test serialization
	m = NewIntroductionMessage(d.Messages.Mirror, d.Config.Version,
		d.Pool.Pool.Config.Port)
	b := encoder.Serialize(m)
	m2 := IntroductionMessage{}
	assert.Nil(t, encoder.DeserializeRaw(b, &m2))
	assert.Equal(t, *m, m2)

	// Test already connected
	d.mirrorConnections[m.Mirror] = make(map[string]uint16)
	d.mirrorConnections[m.Mirror][addrIP] = addrPort + 1
	err = m.Handle(mc, d)
	assert.Equal(t, err, DisconnectConnectedTwice)
	delete(d.mirrorConnections, m.Mirror)
	assert.False(t, m.valid)

	for len(d.messageEvents) > 0 {
		<-d.messageEvents
	}
	gnet.EraseMessages()
}
Example #8
0
// Packs a interface{} into []byte containing length, id and data
func (self *Serializer) SerializeMessage(message interface{}) []byte {
	messageType := reflect.TypeOf(message)
	messagePrefix, exists := self.messageTypeToPrefix[messageType]
	if !exists {
		log.Panicf("Attempted to serialize message with unknown type: %v", messageType)
	}
	serializedMessageData := encoder.Serialize(message)

	// message length
	finalMessage := make([]byte, 0)
	finalMessage = append(finalMessage, messagePrefix[:]...)      // message prefix
	finalMessage = append(finalMessage, serializedMessageData...) // message bytes
	return finalMessage
}
Example #9
0
func (self *Dispatcher) EncodeMessage(msg Message) []byte {
	t := reflect.ValueOf(msg).Elem().Type()
	msgId, succ := self.MessageIdMap[t]
	if !succ {
		txt := "Attempted to serialize message struct not in MessageIdMap: %v"
		log.Panicf(txt, msg)
	}
	bMsg := encoder.Serialize(msg)

	m := make([]byte, 0, 4+len(bMsg))
	m = append(m, msgId[:]...) // message id
	m = append(m, bMsg...)     // message bytes
	return m
}
Example #10
0
//encode block to bytes
func Enc_block(sb SignedBlock) []byte {
	var prefix []byte = make([]byte, 16)
	b := encoder.Serialize(sb)

	var dln uint64 = uint64(len(b) + 24) //length include prefix
	var seq uint64 = uint64(sb.Block.Head.BkSeq)
	var chk uint64 = FnvsHash(b)

	le_PutUint64(prefix[0:8], dln)
	le_PutUint64(prefix[8:16], seq)
	le_PutUint64(prefix[16:24], chk)

	b = append(prefix[:], b...)

	return b
}
Example #11
0
func TestPongMessage(t *testing.T) {
	cmsgs := NewMessagesConfig()
	cmsgs.Register()
	m := &PongMessage{}
	// Pongs dont do anything
	assert.Nil(t, m.Handle(messageContext(addr), nil))
	gnet.EraseMessages()

	// Test serialization
	mm := PongMessage{}
	b := encoder.Serialize(mm)
	m2 := PongMessage{}
	assert.Nil(t, encoder.DeserializeRaw(b, &m2))
	assert.Equal(t, mm, m2)

}
Example #12
0
			}
		}
	}()
	n, e = encoder.DeserializeRawToValue(msg, v)
	return
}

// Packgs a Message into []byte containing length, id and data
var encodeMessage = func(msg Message) []byte {
	t := reflect.ValueOf(msg).Elem().Type()
	msgId, succ := MessageIdMap[t]
	if !succ {
		txt := "Attempted to serialize message struct not in MessageIdMap: %v"
		log.Panicf(txt, msg)
	}
	bMsg := encoder.Serialize(msg)

	// message length
	bLen := encoder.SerializeAtomic(uint32(len(bMsg) + len(msgId)))
	m := make([]byte, 0)
	m = append(m, bLen...)     // length prefix
	m = append(m, msgId[:]...) // message id
	m = append(m, bMsg...)     // message bytes
	return m
}

// Sends []byte over a net.Conn
var sendByteMessage = func(conn net.Conn, msg []byte,
	timeout time.Duration) error {
	deadline := time.Time{}
	if timeout != 0 {
Example #13
0
func (self *Transaction) Serialize() []byte {
	return encoder.Serialize(*self)
}
Example #14
0
// Hashes only the Transaction Inputs & Outputs
// This is what is signed
// Client hashes the inner hash with hash of output being spent and signs it with private key
func (self *Transaction) HashInner() cipher.SHA256 {
	b1 := encoder.Serialize(self.In)
	b2 := encoder.Serialize(self.Out)
	b3 := append(b1, b2...)
	return cipher.SumSHA256(b3)
}
Example #15
0
func (self *UxBody) Hash() cipher.SHA256 {
	return cipher.SumSHA256(encoder.Serialize(self))
}
Example #16
0
func (self *BlockHeader) Hash() cipher.SHA256 {
	b1 := encoder.Serialize(*self)
	return cipher.DoubleSHA256(b1)
}
Example #17
0
//encode block as bytes
func (self *Block) Bytes() []byte {
	return encoder.Serialize(*self)
}
Example #18
0
// Returns hash of UxBody + UxHead
func (self *UxOut) SnapshotHash() cipher.SHA256 {
	b1 := encoder.Serialize(self.Body) //body
	b2 := encoder.Serialize(self.Head) //time, bkseq
	b3 := append(b1, b2...)
	return cipher.SumSHA256(b3)
}