Skip to content

Commit

Permalink
Signer functionality to Sender
Browse files Browse the repository at this point in the history
Co-authored-by: Gabriel Díaz <[email protected]>
  • Loading branch information
Jose Luis Lucas and gdiazlo committed Nov 19, 2018
1 parent ac88a2a commit 2a84064
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 102 deletions.
16 changes: 4 additions & 12 deletions api/apihttp/apihttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,12 @@ package apihttp
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"

"github.com/bbva/qed/log"
"github.com/bbva/qed/protocol"
"github.com/bbva/qed/raftwal"
"github.com/bbva/qed/sign"
)

// HealthCheckResponse contains the response from HealthCheckHandler.
Expand Down Expand Up @@ -79,7 +77,7 @@ func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
// "Version": 1,
// "Event": "VGhpcyBpcyBteSBmaXJzdCBldmVudA=="
// }
func Add(balloon raftwal.RaftBalloonApi, signer sign.Signer) http.HandlerFunc {
func Add(balloon raftwal.RaftBalloonApi) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

// Make sure we can only be called with an HTTP POST request.
Expand Down Expand Up @@ -114,13 +112,7 @@ func Add(balloon raftwal.RaftBalloonApi, signer sign.Signer) http.HandlerFunc {
event.Event,
}

signature, err := signer.Sign([]byte(fmt.Sprintf("%v", snapshot)))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

out, err := json.Marshal(protocol.SignedSnapshot{snapshot, signature})
out, err := json.Marshal(snapshot)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
Expand Down Expand Up @@ -252,11 +244,11 @@ func AuthHandlerMiddleware(handler http.HandlerFunc) http.HandlerFunc {
// /health-check -> HealthCheckHandler
// /events -> Add
// /proofs/membership -> Membership
func NewApiHttp(balloon raftwal.RaftBalloonApi, signer sign.Signer) *http.ServeMux {
func NewApiHttp(balloon raftwal.RaftBalloonApi) *http.ServeMux {

api := http.NewServeMux()
api.HandleFunc("/health-check", AuthHandlerMiddleware(HealthCheckHandler))
api.HandleFunc("/events", AuthHandlerMiddleware(Add(balloon, signer)))
api.HandleFunc("/events", AuthHandlerMiddleware(Add(balloon)))
api.HandleFunc("/proofs/membership", AuthHandlerMiddleware(Membership(balloon)))
api.HandleFunc("/proofs/incremental", AuthHandlerMiddleware(Incremental(balloon)))

Expand Down
32 changes: 9 additions & 23 deletions api/apihttp/apihttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import (
"github.com/bbva/qed/hashing"
"github.com/bbva/qed/protocol"
"github.com/bbva/qed/raftwal"
"github.com/bbva/qed/sign"
"github.com/bbva/qed/storage/badger"
"github.com/bbva/qed/testutils/rand"
assert "github.com/stretchr/testify/require"
Expand Down Expand Up @@ -118,8 +117,7 @@ func TestAdd(t *testing.T) {

// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
signer := sign.NewEd25519Signer()
handler := Add(fakeRaftBalloon{}, signer)
handler := Add(fakeRaftBalloon{})

// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
Expand All @@ -132,32 +130,21 @@ func TestAdd(t *testing.T) {
}

// Check the body response
signedSnapshot := &protocol.SignedSnapshot{}
snapshot := &protocol.Snapshot{}

json.Unmarshal([]byte(rr.Body.String()), signedSnapshot)
json.Unmarshal([]byte(rr.Body.String()), snapshot)

if !bytes.Equal(signedSnapshot.Snapshot.HyperDigest, []byte{0x1}) {
t.Errorf("HyperDigest is not consistent: %s", signedSnapshot.Snapshot.HyperDigest)
if !bytes.Equal(snapshot.HyperDigest, []byte{0x1}) {
t.Errorf("HyperDigest is not consistent: %s", snapshot.HyperDigest)
}

if !bytes.Equal(signedSnapshot.Snapshot.HistoryDigest, []byte{0x0}) {
t.Errorf("HistoryDigest is not consistent %s", signedSnapshot.Snapshot.HistoryDigest)
if !bytes.Equal(snapshot.HistoryDigest, []byte{0x0}) {
t.Errorf("HistoryDigest is not consistent %s", snapshot.HistoryDigest)
}

if signedSnapshot.Snapshot.Version != 0 {
if snapshot.Version != 0 {
t.Errorf("Version is not consistent")
}

if !bytes.Equal(signedSnapshot.Snapshot.EventDigest, []byte("this is a sample event")) {
t.Errorf("Event is not consistent ")
}

signature, err := signer.Sign([]byte(fmt.Sprintf("%v", signedSnapshot.Snapshot)))

if !bytes.Equal(signedSnapshot.Signature, signature) {
t.Errorf("Signature is not consistent")
}

}

func TestMembership(t *testing.T) {
Expand Down Expand Up @@ -325,14 +312,13 @@ func newNodeBench(b *testing.B, id int) (*raftwal.RaftBalloon, func()) {
}
func BenchmarkApiAdd(b *testing.B) {

signer := sign.NewEd25519Signer()
r, clean := newNodeBench(b, 1)
defer clean()

err := r.Open(true)
assert.NoError(b, err)

handler := Add(r, signer)
handler := Add(r)

time.Sleep(2 * time.Second)
b.ResetTimer()
Expand Down
22 changes: 11 additions & 11 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func (c HttpClient) doReq(method, path string, data []byte) ([]byte, error) {
}

// Add will do a request to the server with a post data to store a new event.
func (c HttpClient) Add(event string) (*protocol.SignedSnapshot, error) {
func (c HttpClient) Add(event string) (*protocol.Snapshot, error) {

data, _ := json.Marshal(&protocol.Event{[]byte(event)})

Expand All @@ -111,10 +111,10 @@ func (c HttpClient) Add(event string) (*protocol.SignedSnapshot, error) {
return nil, err
}

var signedSnapshot protocol.SignedSnapshot
json.Unmarshal(body, &signedSnapshot)
var snapshot protocol.Snapshot
json.Unmarshal(body, &snapshot)

return &signedSnapshot, nil
return &snapshot, nil

}

Expand Down Expand Up @@ -178,19 +178,19 @@ func (c HttpClient) Verify(result *protocol.MembershipResult, snap *protocol.Sna

}

func (c HttpClient) VerifyIncremental(result *protocol.IncrementalResponse, startSnapshot, endSnapshot *protocol.SignedSnapshot, hasher hashing.Hasher) bool {
func (c HttpClient) VerifyIncremental(result *protocol.IncrementalResponse, startSnapshot, endSnapshot *protocol.Snapshot, hasher hashing.Hasher) bool {

proof := protocol.ToIncrementalProof(result, hasher)

startCommitment := &balloon.Commitment{
startSnapshot.Snapshot.HistoryDigest,
startSnapshot.Snapshot.HyperDigest,
startSnapshot.Snapshot.Version,
startSnapshot.HistoryDigest,
startSnapshot.HyperDigest,
startSnapshot.Version,
}
endCommitment := &balloon.Commitment{
endSnapshot.Snapshot.HistoryDigest,
endSnapshot.Snapshot.HyperDigest,
endSnapshot.Snapshot.Version,
endSnapshot.HistoryDigest,
endSnapshot.HyperDigest,
endSnapshot.Version,
}

return proof.Verify(startCommitment, endCommitment)
Expand Down
14 changes: 3 additions & 11 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,13 @@ package client
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/bbva/qed/balloon/visitor"
"github.com/bbva/qed/log"
"github.com/bbva/qed/protocol"
"github.com/bbva/qed/sign"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -61,19 +59,13 @@ func TestAddSuccess(t *testing.T) {
0,
[]byte(event),
}
signer := sign.NewEd25519Signer()
sig, err := signer.Sign([]byte(fmt.Sprintf("%v", snap)))
fakeSignedSnapshot := &protocol.SignedSnapshot{
snap,
sig,
}

result, _ := json.Marshal(fakeSignedSnapshot)
result, _ := json.Marshal(snap)
mux.HandleFunc("/events", okHandler(result))

signedSnapshot, err := client.Add(event)
snapshot, err := client.Add(event)
assert.NoError(t, err)
assert.Equal(t, fakeSignedSnapshot, signedSnapshot, "The snapshots should match")
assert.Equal(t, snap, snapshot, "The snapshots should match")

}

Expand Down
3 changes: 1 addition & 2 deletions cmd/client_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,10 @@ func newAddCommand(ctx *clientContext) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
log.Infof("Adding key [ %s ] with value [ %s ]\n", key, value)

signedSnapshot, err := ctx.client.Add(key)
snapshot, err := ctx.client.Add(key)
if err != nil {
return err
}
snapshot := signedSnapshot.Snapshot

log.Infof("Received snapshot with values: \n\tEvent: %s\n\tHyperDigest: %x\n\tHistoryDigest: %x\n\tVersion: %d\n",
snapshot.EventDigest, snapshot.HyperDigest, snapshot.HistoryDigest, snapshot.Version)
Expand Down
4 changes: 2 additions & 2 deletions cmd/client_incremental.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ func newIncrementalCommand(ctx *clientContext) *cobra.Command {
if verify {
sdBytes, _ := hex.DecodeString(startDigest)
edBytes, _ := hex.DecodeString(endDigest)
startSnapshot := &protocol.SignedSnapshot{&protocol.Snapshot{sdBytes, nil, start, nil}, nil}
endSnapshot := &protocol.SignedSnapshot{&protocol.Snapshot{edBytes, nil, end, nil}, nil}
startSnapshot := &protocol.Snapshot{sdBytes, nil, start, nil}
endSnapshot := &protocol.Snapshot{edBytes, nil, end, nil}

log.Infof("Verifying with commitments: \n\tStartDigest: %s\n\tEndDigest: %s\n",
startDigest, endDigest)
Expand Down
14 changes: 8 additions & 6 deletions gossip/sender/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
type Sender struct {
Agent *gossip.Agent
Config *Config
signer sign.Signer
quit chan bool
}

Expand All @@ -45,10 +46,11 @@ func DefaultConfig() *Config {
}
}

func NewSender(a *gossip.Agent, c *Config) *Sender {
func NewSender(a *gossip.Agent, c *Config, s sign.Signer) *Sender {
return &Sender{
Agent: a,
Config: c,
signer: s,
quit: make(chan bool),
}
}
Expand All @@ -59,7 +61,7 @@ func (s Sender) Start(ch chan *protocol.Snapshot) {
for {
select {
case <-ticker.C:
msg, _ := encode(getBatch(ch))
msg, _ := encode(s.getBatch(ch))

peers := s.Agent.GetPeers(1, gossip.AuditorType)
peers = append(peers, s.Agent.GetPeers(1, gossip.MonitorType)...)
Expand Down Expand Up @@ -91,7 +93,7 @@ func encode(msg protocol.BatchSnapshots) ([]byte, error) {
return buf.Bytes(), nil
}

func getBatch(ch chan *protocol.Snapshot) protocol.BatchSnapshots {
func (s *Sender) getBatch(ch chan *protocol.Snapshot) protocol.BatchSnapshots {

var snapshot *protocol.Snapshot
var batch protocol.BatchSnapshots
Expand All @@ -108,7 +110,7 @@ func getBatch(ch chan *protocol.Snapshot) protocol.BatchSnapshots {
return batch
}

ss, err := doSign(sign.NewEd25519Signer(), snapshot)
ss, err := s.doSign(snapshot)
if err != nil {
log.Errorf("Failed signing message: %v", err)
}
Expand All @@ -122,9 +124,9 @@ func getBatch(ch chan *protocol.Snapshot) protocol.BatchSnapshots {

}

func doSign(signer sign.Signer, snapshot *protocol.Snapshot) (*protocol.SignedSnapshot, error) {
func (s *Sender) doSign(snapshot *protocol.Snapshot) (*protocol.SignedSnapshot, error) {

signature, err := signer.Sign([]byte(fmt.Sprintf("%v", snapshot)))
signature, err := s.signer.Sign([]byte(fmt.Sprintf("%v", snapshot)))
if err != nil {
fmt.Println("Publisher: error signing commitment")
return nil, err
Expand Down
8 changes: 4 additions & 4 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func NewServer(
server.agentsQueue = make(chan *protocol.Snapshot, 10000)

// Create sender
server.sender = sender.NewSender(server.agent, sender.DefaultConfig())
server.sender = sender.NewSender(server.agent, sender.DefaultConfig(), server.signer)

// Create RaftBalloon
server.raftBalloon, err = raftwal.NewRaftBalloon(raftPath, raftAddr, nodeID, store, server.agentsQueue)
Expand All @@ -147,7 +147,7 @@ func NewServer(
}

// Create http endpoints
server.httpServer = newHTTPServer(server.httpAddr, server.raftBalloon, server.signer)
server.httpServer = newHTTPServer(server.httpAddr, server.raftBalloon)

// Create management endpoints
server.mgmtServer = newMgmtServer(server.mgmtAddr, server.raftBalloon)
Expand Down Expand Up @@ -286,8 +286,8 @@ func (s *Server) Stop() {
log.Debugf("Done. Exiting...\n")
}

func newHTTPServer(endpoint string, raftBalloon raftwal.RaftBalloonApi, signer sign.Signer) *http.Server {
router := apihttp.NewApiHttp(raftBalloon, signer)
func newHTTPServer(endpoint string, raftBalloon raftwal.RaftBalloonApi) *http.Server {
router := apihttp.NewApiHttp(raftBalloon)
return &http.Server{
Addr: endpoint,
Handler: apihttp.LogHandler(router),
Expand Down
Loading

0 comments on commit 2a84064

Please sign in to comment.