messages2.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package wire
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "time"
  8. "github.com/ethereum/go-ethereum/ethutil"
  9. )
  10. // The connection object allows you to set up a connection to the Ethereum network.
  11. // The Connection object takes care of all encoding and sending objects properly over
  12. // the network.
  13. type Connection struct {
  14. conn net.Conn
  15. nTimeout time.Duration
  16. pendingMessages Messages
  17. }
  18. // Create a new connection to the Ethereum network
  19. func New(conn net.Conn) *Connection {
  20. return &Connection{conn: conn, nTimeout: 500}
  21. }
  22. // Read, reads from the network. It will block until the next message is received.
  23. func (self *Connection) Read() *Msg {
  24. if len(self.pendingMessages) == 0 {
  25. self.readMessages()
  26. }
  27. ret := self.pendingMessages[0]
  28. self.pendingMessages = self.pendingMessages[1:]
  29. return ret
  30. }
  31. // Write to the Ethereum network specifying the type of the message and
  32. // the data. Data can be of type RlpEncodable or []interface{}. Returns
  33. // nil or if something went wrong an error.
  34. func (self *Connection) Write(typ MsgType, v ...interface{}) error {
  35. var pack []byte
  36. slice := [][]interface{}{[]interface{}{byte(typ)}}
  37. for _, value := range v {
  38. if encodable, ok := value.(ethutil.RlpEncodeDecode); ok {
  39. slice = append(slice, encodable.RlpValue())
  40. } else if raw, ok := value.([]interface{}); ok {
  41. slice = append(slice, raw)
  42. } else {
  43. panic(fmt.Sprintf("Unable to 'write' object of type %T", value))
  44. }
  45. }
  46. // Encode the type and the (RLP encoded) data for sending over the wire
  47. encoded := ethutil.NewValue(slice).Encode()
  48. payloadLength := ethutil.NumberToBytes(uint32(len(encoded)), 32)
  49. // Write magic token and payload length (first 8 bytes)
  50. pack = append(MagicToken, payloadLength...)
  51. pack = append(pack, encoded...)
  52. // Write to the connection
  53. _, err := self.conn.Write(pack)
  54. if err != nil {
  55. return err
  56. }
  57. return nil
  58. }
  59. func (self *Connection) readMessage(data []byte) (msg *Msg, remaining []byte, done bool, err error) {
  60. if len(data) == 0 {
  61. return nil, nil, true, nil
  62. }
  63. if len(data) <= 8 {
  64. return nil, remaining, false, errors.New("Invalid message")
  65. }
  66. // Check if the received 4 first bytes are the magic token
  67. if bytes.Compare(MagicToken, data[:4]) != 0 {
  68. return nil, nil, false, fmt.Errorf("MagicToken mismatch. Received %v", data[:4])
  69. }
  70. messageLength := ethutil.BytesToNumber(data[4:8])
  71. remaining = data[8+messageLength:]
  72. if int(messageLength) > len(data[8:]) {
  73. return nil, nil, false, fmt.Errorf("message length %d, expected %d", len(data[8:]), messageLength)
  74. }
  75. message := data[8 : 8+messageLength]
  76. decoder := ethutil.NewValueFromBytes(message)
  77. // Type of message
  78. t := decoder.Get(0).Uint()
  79. // Actual data
  80. d := decoder.SliceFrom(1)
  81. msg = &Msg{
  82. Type: MsgType(t),
  83. Data: d,
  84. }
  85. return
  86. }
  87. // The basic message reader waits for data on the given connection, decoding
  88. // and doing a few sanity checks such as if there's a data type and
  89. // unmarhals the given data
  90. func (self *Connection) readMessages() (err error) {
  91. // The recovering function in case anything goes horribly wrong
  92. defer func() {
  93. if r := recover(); r != nil {
  94. err = fmt.Errorf("wire.ReadMessage error: %v", r)
  95. }
  96. }()
  97. // Buff for writing network message to
  98. //buff := make([]byte, 1440)
  99. var buff []byte
  100. var totalBytes int
  101. for {
  102. // Give buffering some time
  103. self.conn.SetReadDeadline(time.Now().Add(self.nTimeout * time.Millisecond))
  104. // Create a new temporarily buffer
  105. b := make([]byte, 1440)
  106. // Wait for a message from this peer
  107. n, _ := self.conn.Read(b)
  108. if err != nil && n == 0 {
  109. if err.Error() != "EOF" {
  110. fmt.Println("err now", err)
  111. return err
  112. } else {
  113. break
  114. }
  115. // Messages can't be empty
  116. } else if n == 0 {
  117. break
  118. }
  119. buff = append(buff, b[:n]...)
  120. totalBytes += n
  121. }
  122. // Reslice buffer
  123. buff = buff[:totalBytes]
  124. msg, remaining, done, err := self.readMessage(buff)
  125. for ; done != true; msg, remaining, done, err = self.readMessage(remaining) {
  126. //log.Println("rx", msg)
  127. if msg != nil {
  128. self.pendingMessages = append(self.pendingMessages, msg)
  129. }
  130. }
  131. return
  132. }
  133. func ReadMessage(data []byte) (msg *Msg, remaining []byte, done bool, err error) {
  134. if len(data) == 0 {
  135. return nil, nil, true, nil
  136. }
  137. if len(data) <= 8 {
  138. return nil, remaining, false, errors.New("Invalid message")
  139. }
  140. // Check if the received 4 first bytes are the magic token
  141. if bytes.Compare(MagicToken, data[:4]) != 0 {
  142. return nil, nil, false, fmt.Errorf("MagicToken mismatch. Received %v", data[:4])
  143. }
  144. messageLength := ethutil.BytesToNumber(data[4:8])
  145. remaining = data[8+messageLength:]
  146. if int(messageLength) > len(data[8:]) {
  147. return nil, nil, false, fmt.Errorf("message length %d, expected %d", len(data[8:]), messageLength)
  148. }
  149. message := data[8 : 8+messageLength]
  150. decoder := ethutil.NewValueFromBytes(message)
  151. // Type of message
  152. t := decoder.Get(0).Uint()
  153. // Actual data
  154. d := decoder.SliceFrom(1)
  155. msg = &Msg{
  156. Type: MsgType(t),
  157. Data: d,
  158. }
  159. return
  160. }
  161. func bufferedRead(conn net.Conn) ([]byte, error) {
  162. return nil, nil
  163. }