/
follower.go
191 lines (169 loc) · 5.87 KB
/
follower.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"time"
"github.com/golang/glog"
"github.com/google/trillian-examples/binary_transparency/firmware/api"
"github.com/google/trillian-examples/binary_transparency/firmware/internal/crypto"
"github.com/transparency-dev/merkle"
"github.com/transparency-dev/merkle/proof"
"github.com/transparency-dev/merkle/rfc6962"
)
// ErrConsistency is returned if two logs roots are found which are inconsistent.
// This allows a motivated client to extract the checkpoints to provide as evidence
// if needed.
type ErrConsistency struct {
Golden, Latest api.LogCheckpoint
}
func (e ErrConsistency) Error() string {
return fmt.Sprintf("failed to verify consistency proof from %s to %s", e.Golden, e.Latest)
}
// ErrInclusion is returned if a proof of inclusion does not validate.
// This allows a motivated client to provide evidence if needed.
type ErrInclusion struct {
Checkpoint api.LogCheckpoint
Proof api.InclusionProof
}
func (e ErrInclusion) Error() string {
return fmt.Sprintf("failed to verify inclusion proof %s in root %s", e.Proof, e.Checkpoint)
}
// LogEntry wraps up a leaf value with its position in the log.
type LogEntry struct {
Root api.LogCheckpoint
Index uint64
Value api.SignedStatement
}
// LogFollower follows a log for new data becoming available.
type LogFollower struct {
c ReadonlyClient
h merkle.LogHasher
}
// NewLogFollower creates a LogFollower that uses the given client.
func NewLogFollower(c ReadonlyClient) LogFollower {
return LogFollower{
c: c,
h: rfc6962.DefaultHasher,
}
}
// Checkpoints polls the log according to the configured interval, returning roots consistent
// with the current golden checkpoint. Should any valid roots be found which are inconsistent
// then an error is returned. The log being unavailable will just cause a retry, giving it
// the benefit of the doubt.
func (f *LogFollower) Checkpoints(ctx context.Context, pollInterval time.Duration, golden api.LogCheckpoint) (<-chan api.LogCheckpoint, <-chan error) {
ticker := time.NewTicker(pollInterval)
outc := make(chan api.LogCheckpoint, 1)
errc := make(chan error, 1)
// Push the starting checkpoint into the channel here to kick off the pipeline
outc <- golden
go func() {
defer close(outc)
// Now keep looking for newer, consistent checkpoints
for {
select {
case <-ticker.C:
// Wait until the next tick.
case <-ctx.Done():
errc <- ctx.Err()
return
}
cp, err := f.c.GetCheckpoint()
if err != nil {
glog.Warningf("Failed to get latest Checkpoint: %q", err)
continue
}
if cp.Size <= golden.Size {
continue
}
glog.V(1).Infof("Got newer checkpoint %s", cp)
// Perform consistency check only for non-zero initial tree size
if golden.Size != 0 {
consistency, err := f.c.GetConsistencyProof(api.GetConsistencyRequest{From: golden.Size, To: cp.Size})
if err != nil {
glog.Warningf("Failed to fetch the Consistency: %q", err)
continue
}
glog.V(1).Infof("Printing the latest Consistency Proof Information")
glog.V(1).Infof("Consistency Proof = %x", consistency.Proof)
// Verify the fetched consistency proof
if err := proof.VerifyConsistency(f.h, golden.Size, cp.Size, consistency.Proof, golden.Hash, cp.Hash); err != nil {
errc <- ErrConsistency{
Golden: golden,
Latest: *cp,
}
return
}
glog.V(1).Infof("Consistency proof for Treesize %d verified", cp.Size)
}
golden = *cp
outc <- *cp
}
}()
return outc, errc
}
// Entries follows the log to output all of the leaves starting from the head index provided.
// This is intended to be set up to consume the output of #Checkpoints(), and will output new
// entries each time a Checkpoint becomes available which is larger than the current head.
// The input channel should be closed in order to clean up the resources used by this method.
func (f *LogFollower) Entries(ctx context.Context, cpc <-chan api.LogCheckpoint, head uint64) (<-chan LogEntry, <-chan error) {
outc := make(chan LogEntry, 1)
errc := make(chan error, 1)
go func() {
defer close(outc)
for cp := range cpc {
for ; head < cp.Size; head++ {
ep, err := f.c.GetManifestEntryAndProof(api.GetFirmwareManifestRequest{Index: head, TreeSize: cp.Size})
if err != nil {
glog.Warningf("Failed to fetch the Manifest: %q", err)
continue
}
lh := f.h.HashLeaf(ep.Value)
if err := proof.VerifyInclusion(f.h, ep.LeafIndex, cp.Size, lh, ep.Proof, cp.Hash); err != nil {
errc <- ErrInclusion{
Checkpoint: cp,
Proof: *ep,
}
return
}
glog.V(1).Infof("Inclusion proof for leafhash 0x%x verified", lh)
statement := ep.Value
stmt := api.SignedStatement{}
if err := json.NewDecoder(bytes.NewReader(statement)).Decode(&stmt); err != nil {
errc <- fmt.Errorf("failed to decode SignedStatement: %q", err)
return
}
claimant, err := crypto.ClaimantForType(stmt.Type)
if err != nil {
errc <- err
return
}
// Verify the signature:
if err := claimant.VerifySignature(stmt.Type, stmt.Statement, stmt.Signature); err != nil {
errc <- fmt.Errorf("failed to verify signature: %q", err)
return
}
outc <- LogEntry{
Root: cp,
Index: head,
Value: stmt,
}
}
}
}()
return outc, errc
}