diff --git a/core/transaction.go b/core/transaction.go index 843efcc..db44f62 100644 --- a/core/transaction.go +++ b/core/transaction.go @@ -53,20 +53,21 @@ func NewTransaction(data []byte) *Transaction { } func (tx *Transaction) Hash(hasher Hasher[*Transaction]) types.Hash { + hash := hasher.Hash(tx) if tx.hash.IsZero() { - tx.hash = hasher.Hash(tx) + tx.hash = hash } - return tx.hash + return hash } func (tx *Transaction) Sign(privKey crypto.PrivateKey) error { + tx.From = privKey.PublicKey() hash := tx.Hash(TxHasher{}) sig, err := privKey.Sign(hash.ToSlice()) if err != nil { return err } - tx.From = privKey.PublicKey() tx.Signature = sig return nil diff --git a/core/transaction_test.go b/core/transaction_test.go index 6576851..225cbb7 100644 --- a/core/transaction_test.go +++ b/core/transaction_test.go @@ -106,3 +106,18 @@ func randomTxWithSignature(t *testing.T) *Transaction { return &tx } + +func TestTemperTxData(t *testing.T) { + userA := crypto.GeneratePrivateKey() + userB := crypto.GeneratePrivateKey() + tx := &Transaction{ + From: userA.PublicKey(), + To: userB.PublicKey(), + Value: 666, + Data: []byte("user a send 666 to user b"), + } + assert.Nil(t, tx.Sign(userA)) + assert.Nil(t, tx.Verify()) + tx.Data = []byte("hhh") + assert.NotNil(t, tx.Verify()) +} diff --git a/network/tcp_transport.go b/network/tcp_transport.go index 5b1d5d2..09f135d 100644 --- a/network/tcp_transport.go +++ b/network/tcp_transport.go @@ -2,6 +2,7 @@ package network import ( "bytes" + "encoding/binary" "fmt" "io" "net" @@ -13,14 +14,26 @@ type TCPPeer struct { } func (p *TCPPeer) Send(b []byte) error { - _, err := p.conn.Write(b) + length := uint32(len(b)) + lengthBytes := make([]byte, 4) + binary.BigEndian.PutUint32(lengthBytes, length) + _, err := p.conn.Write(append(lengthBytes, b...)) return err } func (p *TCPPeer) readLoop(rpcCh chan RPC) { - buf := make([]byte, 4096) for { - n, err := p.conn.Read(buf) + lengthBuf := make([]byte, 4) + if _, err := io.ReadFull(p.conn, lengthBuf); err != nil { + if err == io.EOF { + continue + } + panic(err) + } + + length := binary.BigEndian.Uint32(lengthBuf) + msgBuf := make([]byte, length) + _, err := io.ReadFull(p.conn, msgBuf) if err == io.EOF { continue } @@ -29,10 +42,9 @@ func (p *TCPPeer) readLoop(rpcCh chan RPC) { continue } - msg := buf[:n] rpcCh <- RPC{ From: p.conn.RemoteAddr(), - Payload: bytes.NewReader(msg), + Payload: bytes.NewReader(msgBuf), } } }