Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions core/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions core/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
22 changes: 17 additions & 5 deletions network/tcp_transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package network

import (
"bytes"
"encoding/binary"
"fmt"
"io"
"net"
Expand All @@ -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
}
Expand All @@ -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),
}
}
}
Expand Down